/
OntologyResponderV2.scala
3284 lines (2751 loc) · 135 KB
/
OntologyResponderV2.scala
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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright © 2015-2021 Data and Service Center for the Humanities (DaSCH)
*
* This file is part of Knora.
*
* Knora is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Knora is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with Knora. If not, see <http://www.gnu.org/licenses/>.
*/
package org.knora.webapi.responders.v2
import akka.http.scaladsl.util.FastFuture
import akka.pattern._
import org.knora.webapi.exceptions._
import org.knora.webapi.messages.IriConversions._
import org.knora.webapi.messages.admin.responder.projectsmessages.{
ProjectGetRequestADM,
ProjectGetResponseADM,
ProjectIdentifierADM
}
import org.knora.webapi.messages.admin.responder.usersmessages.UserADM
import org.knora.webapi.messages.store.triplestoremessages.{
SmartIriLiteralV2,
SparqlUpdateRequest,
SparqlUpdateResponse,
StringLiteralV2
}
import org.knora.webapi.messages.util.{ErrorHandlingMap, ResponderData}
import org.knora.webapi.messages.v2.responder.ontologymessages.Cardinality.KnoraCardinalityInfo
import org.knora.webapi.messages.v2.responder.ontologymessages._
import org.knora.webapi.messages.v2.responder.{CanDoResponseV2, SuccessResponseV2}
import org.knora.webapi.messages.{OntologyConstants, SmartIri}
import org.knora.webapi.responders.Responder.handleUnexpectedMessage
import org.knora.webapi.responders.v2.ontology.Cache.ONTOLOGY_CACHE_LOCK_IRI
import org.knora.webapi.responders.v2.ontology.{Cache, Cardinalities, OntologyHelpers}
import org.knora.webapi.responders.{IriLocker, Responder}
import org.knora.webapi.util._
import org.knora.webapi._
import java.time.Instant
import scala.concurrent.{ExecutionContext, Future}
/**
* Responds to requests dealing with ontologies.
*
* The API v2 ontology responder reads ontologies from two sources:
*
* - The triplestore.
* - The constant knora-api v2 ontologies that are defined in Scala rather than in the triplestore, [[KnoraBaseToApiV2SimpleTransformationRules]] and [[KnoraBaseToApiV2ComplexTransformationRules]].
*
* It maintains an in-memory cache of all ontology data. This cache can be refreshed by sending a [[LoadOntologiesRequestV2]].
*
* Read requests to the ontology responder may contain internal or external IRIs as needed. Response messages from the
* ontology responder will contain internal IRIs and definitions, unless a constant API v2 ontology was requested,
* in which case the response will be in the requested API v2 schema.
*
* In API v2, the ontology responder can also create and update ontologies. Update requests must contain
* [[ApiV2Complex]] IRIs and definitions.
*
* The API v1 ontology responder, which is read-only, delegates most of its work to this responder.
*/
class OntologyResponderV2(responderData: ResponderData) extends Responder(responderData) {
/**
* Receives a message of type [[OntologiesResponderRequestV2]], and returns an appropriate response message.
*/
def receive(msg: OntologiesResponderRequestV2) = msg match {
case LoadOntologiesRequestV2(featureFactoryConfig, requestingUser) =>
Cache.loadOntologies(settings, storeManager, featureFactoryConfig, requestingUser)
case EntityInfoGetRequestV2(classIris, propertyIris, requestingUser) =>
getEntityInfoResponseV2(classIris, propertyIris, requestingUser)
case StandoffEntityInfoGetRequestV2(standoffClassIris, standoffPropertyIris, requestingUser) =>
getStandoffEntityInfoResponseV2(standoffClassIris, standoffPropertyIris, requestingUser)
case StandoffClassesWithDataTypeGetRequestV2(requestingUser) =>
getStandoffStandoffClassesWithDataTypeV2(requestingUser)
case StandoffAllPropertyEntitiesGetRequestV2(requestingUser) => getAllStandoffPropertyEntitiesV2(requestingUser)
case CheckSubClassRequestV2(subClassIri, superClassIri, requestingUser) =>
checkSubClassV2(subClassIri, superClassIri)
case SubClassesGetRequestV2(resourceClassIri, requestingUser) => getSubClassesV2(resourceClassIri, requestingUser)
case OntologyKnoraEntityIrisGetRequestV2(namedGraphIri, requestingUser) =>
getKnoraEntityIrisInNamedGraphV2(namedGraphIri, requestingUser)
case OntologyEntitiesGetRequestV2(ontologyIri, allLanguages, requestingUser) =>
getOntologyEntitiesV2(ontologyIri, allLanguages, requestingUser)
case ClassesGetRequestV2(resourceClassIris, allLanguages, requestingUser) =>
getClassDefinitionsFromOntologyV2(resourceClassIris, allLanguages, requestingUser)
case PropertiesGetRequestV2(propertyIris, allLanguages, requestingUser) =>
getPropertyDefinitionsFromOntologyV2(propertyIris, allLanguages, requestingUser)
case OntologyMetadataGetByProjectRequestV2(projectIris, requestingUser) =>
getOntologyMetadataForProjectsV2(projectIris, requestingUser)
case OntologyMetadataGetByIriRequestV2(ontologyIris, requestingUser) =>
getOntologyMetadataByIriV2(ontologyIris, requestingUser)
case createOntologyRequest: CreateOntologyRequestV2 => createOntology(createOntologyRequest)
case changeOntologyMetadataRequest: ChangeOntologyMetadataRequestV2 =>
changeOntologyMetadata(changeOntologyMetadataRequest)
case deleteOntologyCommentRequest: DeleteOntologyCommentRequestV2 =>
deleteOntologyComment(deleteOntologyCommentRequest)
case createClassRequest: CreateClassRequestV2 => createClass(createClassRequest)
case changeClassLabelsOrCommentsRequest: ChangeClassLabelsOrCommentsRequestV2 =>
changeClassLabelsOrComments(changeClassLabelsOrCommentsRequest)
case addCardinalitiesToClassRequest: AddCardinalitiesToClassRequestV2 =>
addCardinalitiesToClass(addCardinalitiesToClassRequest)
case canChangeCardinalitiesRequest: CanChangeCardinalitiesRequestV2 =>
canChangeClassCardinalities(canChangeCardinalitiesRequest)
case changeCardinalitiesRequest: ChangeCardinalitiesRequestV2 =>
changeClassCardinalities(changeCardinalitiesRequest)
case canDeleteCardinalitiesFromClassRequestV2: CanDeleteCardinalitiesFromClassRequestV2 =>
canDeleteCardinalitiesFromClass(canDeleteCardinalitiesFromClassRequestV2)
case deleteCardinalitiesfromClassRequest: DeleteCardinalitiesFromClassRequestV2 =>
deleteCardinalitiesFromClass(deleteCardinalitiesfromClassRequest)
case changeGuiOrderRequest: ChangeGuiOrderRequestV2 => changeGuiOrder(changeGuiOrderRequest)
case canDeleteClassRequest: CanDeleteClassRequestV2 => canDeleteClass(canDeleteClassRequest)
case deleteClassRequest: DeleteClassRequestV2 => deleteClass(deleteClassRequest)
case createPropertyRequest: CreatePropertyRequestV2 => createProperty(createPropertyRequest)
case changePropertyLabelsOrCommentsRequest: ChangePropertyLabelsOrCommentsRequestV2 =>
changePropertyLabelsOrComments(changePropertyLabelsOrCommentsRequest)
case changePropertyGuiElementRequest: ChangePropertyGuiElementRequest =>
changePropertyGuiElement(changePropertyGuiElementRequest)
case canDeletePropertyRequest: CanDeletePropertyRequestV2 => canDeleteProperty(canDeletePropertyRequest)
case deletePropertyRequest: DeletePropertyRequestV2 => deleteProperty(deletePropertyRequest)
case canDeleteOntologyRequest: CanDeleteOntologyRequestV2 => canDeleteOntology(canDeleteOntologyRequest)
case deleteOntologyRequest: DeleteOntologyRequestV2 => deleteOntology(deleteOntologyRequest)
case other => handleUnexpectedMessage(other, log, this.getClass.getName)
}
/**
* Given a list of resource IRIs and a list of property IRIs (ontology entities), returns an [[EntityInfoGetResponseV2]] describing both resource and property entities.
*
* @param classIris the IRIs of the resource entities to be queried.
* @param propertyIris the IRIs of the property entities to be queried.
* @param requestingUser the user making the request.
* @return an [[EntityInfoGetResponseV2]].
*/
private def getEntityInfoResponseV2(
classIris: Set[SmartIri] = Set.empty[SmartIri],
propertyIris: Set[SmartIri] = Set.empty[SmartIri],
requestingUser: UserADM
): Future[EntityInfoGetResponseV2] =
OntologyHelpers.getEntityInfoResponseV2(classIris, propertyIris, requestingUser)
/**
* Given a list of standoff class IRIs and a list of property IRIs (ontology entities), returns an [[StandoffEntityInfoGetResponseV2]] describing both resource and property entities.
*
* @param standoffClassIris the IRIs of the resource entities to be queried.
* @param standoffPropertyIris the IRIs of the property entities to be queried.
* @param requestingUser the user making the request.
* @return a [[StandoffEntityInfoGetResponseV2]].
*/
private def getStandoffEntityInfoResponseV2(
standoffClassIris: Set[SmartIri] = Set.empty[SmartIri],
standoffPropertyIris: Set[SmartIri] = Set.empty[SmartIri],
requestingUser: UserADM
): Future[StandoffEntityInfoGetResponseV2] =
for {
cacheData <- Cache.getCacheData
entitiesInWrongSchema =
(standoffClassIris ++ standoffPropertyIris).filter(_.getOntologySchema.contains(ApiV2Simple))
_ = if (entitiesInWrongSchema.nonEmpty) {
throw NotFoundException(
s"Some requested standoff classes were not found: ${entitiesInWrongSchema.mkString(", ")}"
)
}
classIrisForCache = standoffClassIris.map(_.toOntologySchema(InternalSchema))
propertyIrisForCache = standoffPropertyIris.map(_.toOntologySchema(InternalSchema))
classOntologies: Iterable[ReadOntologyV2] = cacheData.ontologies.view
.filterKeys(classIrisForCache.map(_.getOntologyFromEntity))
.values
propertyOntologies: Iterable[ReadOntologyV2] = cacheData.ontologies.view
.filterKeys(propertyIrisForCache.map(_.getOntologyFromEntity))
.values
classDefsAvailable: Map[SmartIri, ReadClassInfoV2] = classOntologies.flatMap { ontology =>
ontology.classes.filter { case (classIri, classDef) =>
classDef.isStandoffClass && standoffClassIris.contains(
classIri
)
}
}.toMap
propertyDefsAvailable: Map[SmartIri, ReadPropertyInfoV2] = propertyOntologies.flatMap { ontology =>
ontology.properties.filter { case (propertyIri, _) =>
standoffPropertyIris.contains(
propertyIri
) && cacheData.standoffProperties.contains(
propertyIri
)
}
}.toMap
missingClassDefs = classIrisForCache -- classDefsAvailable.keySet
missingPropertyDefs = propertyIrisForCache -- propertyDefsAvailable.keySet
_ = if (missingClassDefs.nonEmpty) {
throw NotFoundException(
s"Some requested standoff classes were not found: ${missingClassDefs.mkString(", ")}"
)
}
_ = if (missingPropertyDefs.nonEmpty) {
throw NotFoundException(
s"Some requested standoff properties were not found: ${missingPropertyDefs.mkString(", ")}"
)
}
response = StandoffEntityInfoGetResponseV2(
standoffClassInfoMap = new ErrorHandlingMap(classDefsAvailable, key => s"Resource class $key not found"),
standoffPropertyInfoMap = new ErrorHandlingMap(propertyDefsAvailable, key => s"Property $key not found")
)
} yield response
/**
* Gets information about all standoff classes that are a subclass of a data type standoff class.
*
* @param requestingUser the user making the request.
* @return a [[StandoffClassesWithDataTypeGetResponseV2]]
*/
private def getStandoffStandoffClassesWithDataTypeV2(
requestingUser: UserADM
): Future[StandoffClassesWithDataTypeGetResponseV2] =
for {
cacheData <- Cache.getCacheData
} yield StandoffClassesWithDataTypeGetResponseV2(
standoffClassInfoMap = cacheData.ontologies.values.flatMap { ontology =>
ontology.classes.filter { case (_, classDef) =>
classDef.isStandoffClass && classDef.standoffDataType.isDefined
}
}.toMap
)
/**
* Gets all standoff property entities.
*
* @param requestingUser the user making the request.
* @return a [[StandoffAllPropertyEntitiesGetResponseV2]].
*/
private def getAllStandoffPropertyEntitiesV2(
requestingUser: UserADM
): Future[StandoffAllPropertyEntitiesGetResponseV2] =
for {
cacheData <- Cache.getCacheData
} yield StandoffAllPropertyEntitiesGetResponseV2(
standoffAllPropertiesEntityInfoMap = cacheData.ontologies.values.flatMap { ontology =>
ontology.properties.view.filterKeys(cacheData.standoffProperties)
}.toMap
)
/**
* Checks whether a certain Knora resource or value class is a subclass of another class.
*
* @param subClassIri the IRI of the resource or value class whose subclassOf relations have to be checked.
* @param superClassIri the IRI of the resource or value class to check for (whether it is a a super class of `subClassIri` or not).
* @return a [[CheckSubClassResponseV2]].
*/
private def checkSubClassV2(subClassIri: SmartIri, superClassIri: SmartIri): Future[CheckSubClassResponseV2] =
for {
cacheData <- Cache.getCacheData
response = CheckSubClassResponseV2(
isSubClass = cacheData.subClassOfRelations.get(subClassIri) match {
case Some(baseClasses) => baseClasses.contains(superClassIri)
case None => throw BadRequestException(s"Class $subClassIri not found")
}
)
} yield response
/**
* Gets the IRIs of the subclasses of a class.
*
* @param classIri the IRI of the class whose subclasses should be returned.
* @return a [[SubClassesGetResponseV2]].
*/
private def getSubClassesV2(classIri: SmartIri, requestingUser: UserADM): Future[SubClassesGetResponseV2] =
for {
cacheData <- Cache.getCacheData
subClassIris = cacheData.superClassOfRelations(classIri).toVector.sorted
subClasses = subClassIris.map { subClassIri =>
val classInfo: ReadClassInfoV2 =
cacheData.ontologies(subClassIri.getOntologyFromEntity).classes(subClassIri)
SubClassInfoV2(
id = subClassIri,
label = classInfo.entityInfoContent
.getPredicateStringLiteralObject(
predicateIri = OntologyConstants.Rdfs.Label.toSmartIri,
preferredLangs = Some(requestingUser.lang, settings.fallbackLanguage)
)
.getOrElse(
throw InconsistentRepositoryDataException(s"Resource class $subClassIri has no rdfs:label")
)
)
}
} yield SubClassesGetResponseV2(
subClasses = subClasses
)
/**
* Gets the [[OntologyKnoraEntitiesIriInfoV2]] for an ontology.
*
* @param ontologyIri the IRI of the ontology to query
* @param requestingUser the user making the request.
* @return an [[OntologyKnoraEntitiesIriInfoV2]].
*/
private def getKnoraEntityIrisInNamedGraphV2(
ontologyIri: SmartIri,
requestingUser: UserADM
): Future[OntologyKnoraEntitiesIriInfoV2] =
for {
cacheData <- Cache.getCacheData
ontology = cacheData.ontologies(ontologyIri)
} yield OntologyKnoraEntitiesIriInfoV2(
ontologyIri = ontologyIri,
propertyIris = ontology.properties.keySet.filter { propertyIri =>
OntologyHelpers.isKnoraResourceProperty(propertyIri, cacheData)
},
classIris = ontology.classes.filter { case (_, classDef) =>
classDef.isResourceClass
}.keySet,
standoffClassIris = ontology.classes.filter { case (_, classDef) =>
classDef.isStandoffClass
}.keySet,
standoffPropertyIris = ontology.properties.keySet.filter(cacheData.standoffProperties)
)
/**
* Gets the metadata describing the ontologies that belong to selected projects, or to all projects.
*
* @param projectIris the IRIs of the projects selected, or an empty set if all projects are selected.
* @param requestingUser the user making the request.
* @return a [[ReadOntologyMetadataV2]].
*/
private def getOntologyMetadataForProjectsV2(
projectIris: Set[SmartIri],
requestingUser: UserADM
): Future[ReadOntologyMetadataV2] =
for {
cacheData <- Cache.getCacheData
returnAllOntologies: Boolean = projectIris.isEmpty
ontologyMetadata: Set[OntologyMetadataV2] =
if (returnAllOntologies) {
cacheData.ontologies.values.map(_.ontologyMetadata).toSet
} else {
cacheData.ontologies.values.filter { ontology =>
projectIris.contains(ontology.ontologyMetadata.projectIri.get)
}.map { ontology =>
ontology.ontologyMetadata
}.toSet
}
} yield ReadOntologyMetadataV2(
ontologies = ontologyMetadata
)
/**
* Gets the metadata describing the specified ontologies, or all ontologies.
*
* @param ontologyIris the IRIs of the ontologies selected, or an empty set if all ontologies are selected.
* @param requestingUser the user making the request.
* @return a [[ReadOntologyMetadataV2]].
*/
private def getOntologyMetadataByIriV2(
ontologyIris: Set[SmartIri],
requestingUser: UserADM
): Future[ReadOntologyMetadataV2] =
for {
cacheData <- Cache.getCacheData
returnAllOntologies: Boolean = ontologyIris.isEmpty
ontologyMetadata: Set[OntologyMetadataV2] =
if (returnAllOntologies) {
cacheData.ontologies.values.map(_.ontologyMetadata).toSet
} else {
val ontologyIrisForCache =
ontologyIris.map(_.toOntologySchema(InternalSchema))
val missingOntologies =
ontologyIrisForCache -- cacheData.ontologies.keySet
if (missingOntologies.nonEmpty) {
throw BadRequestException(
s"One or more requested ontologies were not found: ${missingOntologies
.mkString(", ")}"
)
}
cacheData.ontologies.view
.filterKeys(ontologyIrisForCache)
.values
.map { ontology =>
ontology.ontologyMetadata
}
.toSet
}
} yield ReadOntologyMetadataV2(
ontologies = ontologyMetadata
)
/**
* Requests the entities defined in the given ontology.
*
* @param ontologyIri the IRI (internal or external) of the ontology to be queried.
* @param requestingUser the user making the request.
* @return a [[ReadOntologyV2]].
*/
private def getOntologyEntitiesV2(
ontologyIri: SmartIri,
allLanguages: Boolean,
requestingUser: UserADM
): Future[ReadOntologyV2] =
for {
cacheData <- Cache.getCacheData
_ = if (ontologyIri.getOntologyName == "standoff" && ontologyIri.getOntologySchema.contains(ApiV2Simple)) {
throw BadRequestException(s"The standoff ontology is not available in the API v2 simple schema")
}
ontology = cacheData.ontologies.get(ontologyIri.toOntologySchema(InternalSchema)) match {
case Some(cachedOntology) => cachedOntology
case None => throw NotFoundException(s"Ontology not found: $ontologyIri")
}
// Are we returning data in the user's preferred language, or in all available languages?
userLang =
if (!allLanguages) {
// Just the user's preferred language.
Some(requestingUser.lang)
} else {
// All available languages.
None
}
} yield ontology.copy(
userLang = userLang
)
/**
* Requests information about OWL classes in a single ontology.
*
* @param classIris the IRIs (internal or external) of the classes to query for.
* @param requestingUser the user making the request.
* @return a [[ReadOntologyV2]].
*/
private def getClassDefinitionsFromOntologyV2(
classIris: Set[SmartIri],
allLanguages: Boolean,
requestingUser: UserADM
): Future[ReadOntologyV2] =
OntologyHelpers.getClassDefinitionsFromOntologyV2(classIris, allLanguages, requestingUser)
/**
* Requests information about properties in a single ontology.
*
* @param propertyIris the IRIs (internal or external) of the properties to query for.
* @param requestingUser the user making the request.
* @return a [[ReadOntologyV2]].
*/
private def getPropertyDefinitionsFromOntologyV2(
propertyIris: Set[SmartIri],
allLanguages: Boolean,
requestingUser: UserADM
): Future[ReadOntologyV2] =
for {
cacheData <- Cache.getCacheData
ontologyIris = propertyIris.map(_.getOntologyFromEntity)
_ = if (ontologyIris.size != 1) {
throw BadRequestException(s"Only one ontology may be queried per request")
}
propertyInfoResponse: EntityInfoGetResponseV2 <-
getEntityInfoResponseV2(propertyIris = propertyIris, requestingUser = requestingUser)
internalOntologyIri = ontologyIris.head.toOntologySchema(InternalSchema)
// Are we returning data in the user's preferred language, or in all available languages?
userLang =
if (!allLanguages) {
// Just the user's preferred language.
Some(requestingUser.lang)
} else {
// All available languages.
None
}
} yield ReadOntologyV2(
ontologyMetadata = cacheData.ontologies(internalOntologyIri).ontologyMetadata,
properties = propertyInfoResponse.propertyInfoMap,
userLang = userLang
)
/**
* Creates a new, empty ontology.
*
* @param createOntologyRequest the request message.
* @return a [[SuccessResponseV2]].
*/
private def createOntology(createOntologyRequest: CreateOntologyRequestV2): Future[ReadOntologyMetadataV2] = {
def makeTaskFuture(internalOntologyIri: SmartIri): Future[ReadOntologyMetadataV2] =
for {
cacheData <- Cache.getCacheData
// Make sure the ontology doesn't already exist.
existingOntologyMetadata: Option[OntologyMetadataV2] <- OntologyHelpers.loadOntologyMetadata(
settings,
storeManager,
internalOntologyIri = internalOntologyIri,
featureFactoryConfig = createOntologyRequest.featureFactoryConfig
)
_ = if (existingOntologyMetadata.nonEmpty) {
throw BadRequestException(
s"Ontology ${internalOntologyIri.toOntologySchema(ApiV2Complex)} cannot be created, because it already exists"
)
}
// If this is a shared ontology, make sure it's in the default shared ontologies project.
_ =
if (
createOntologyRequest.isShared && createOntologyRequest.projectIri.toString != OntologyConstants.KnoraAdmin.DefaultSharedOntologiesProject
) {
throw BadRequestException(
s"Shared ontologies must be created in project <${OntologyConstants.KnoraAdmin.DefaultSharedOntologiesProject}>"
)
}
// If it's in the default shared ontologies project, make sure it's a shared ontology.
_ =
if (
createOntologyRequest.projectIri.toString == OntologyConstants.KnoraAdmin.DefaultSharedOntologiesProject && !createOntologyRequest.isShared
) {
throw BadRequestException(
s"Ontologies created in project <${OntologyConstants.KnoraAdmin.DefaultSharedOntologiesProject}> must be shared"
)
}
// Create the ontology.
currentTime: Instant = Instant.now
createOntologySparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt
.createOntology(
triplestore = settings.triplestoreType,
ontologyNamedGraphIri = internalOntologyIri,
ontologyIri = internalOntologyIri,
projectIri = createOntologyRequest.projectIri,
isShared = createOntologyRequest.isShared,
ontologyLabel = createOntologyRequest.label,
ontologyComment = createOntologyRequest.comment,
currentTime = currentTime
)
.toString
_ <- (storeManager ? SparqlUpdateRequest(createOntologySparql)).mapTo[SparqlUpdateResponse]
// Check that the update was successful. To do this, we have to undo the SPARQL-escaping of the input.
unescapedNewMetadata = OntologyMetadataV2(
ontologyIri = internalOntologyIri,
projectIri = Some(createOntologyRequest.projectIri),
label = Some(createOntologyRequest.label),
comment = createOntologyRequest.comment,
lastModificationDate = Some(currentTime)
).unescape
maybeLoadedOntologyMetadata: Option[OntologyMetadataV2] <- OntologyHelpers.loadOntologyMetadata(
settings,
storeManager,
internalOntologyIri = internalOntologyIri,
featureFactoryConfig = createOntologyRequest.featureFactoryConfig
)
_ = maybeLoadedOntologyMetadata match {
case Some(loadedOntologyMetadata) =>
if (loadedOntologyMetadata != unescapedNewMetadata) {
throw UpdateNotPerformedException()
}
case None => throw UpdateNotPerformedException()
}
// Update the ontology cache with the unescaped metadata.
_ =
Cache.storeCacheData(
cacheData.copy(
ontologies =
cacheData.ontologies + (internalOntologyIri -> ReadOntologyV2(ontologyMetadata = unescapedNewMetadata))
)
)
} yield ReadOntologyMetadataV2(ontologies = Set(unescapedNewMetadata))
for {
requestingUser <- FastFuture.successful(createOntologyRequest.requestingUser)
projectIri = createOntologyRequest.projectIri
// check if the requesting user is allowed to create an ontology
_ =
if (
!(requestingUser.permissions.isProjectAdmin(projectIri.toString) || requestingUser.permissions.isSystemAdmin)
) {
// println(s"requestingUser: $requestingUser")
// println(s"requestingUser.permissionData.isProjectAdmin(<${projectIri.toString}>): ${requestingUser.permissionData.isProjectAdmin(projectIri.toString)}")
throw ForbiddenException(
s"A new ontology in the project ${createOntologyRequest.projectIri} can only be created by an admin of that project, or by a system admin."
)
}
// Get project info for the shortcode.
projectInfo: ProjectGetResponseADM <- (responderManager ? ProjectGetRequestADM(
identifier = ProjectIdentifierADM(maybeIri = Some(projectIri.toString)),
featureFactoryConfig = createOntologyRequest.featureFactoryConfig,
requestingUser = requestingUser
)).mapTo[ProjectGetResponseADM]
// Check that the ontology name is valid.
validOntologyName =
stringFormatter.validateProjectSpecificOntologyName(
createOntologyRequest.ontologyName,
throw BadRequestException(s"Invalid project-specific ontology name: ${createOntologyRequest.ontologyName}")
)
// Make the internal ontology IRI.
internalOntologyIri = stringFormatter.makeProjectSpecificInternalOntologyIri(
validOntologyName,
createOntologyRequest.isShared,
projectInfo.project.shortcode
)
// Do the remaining pre-update checks and the update while holding a global ontology cache lock.
taskResult <- IriLocker.runWithIriLock(
apiRequestID = createOntologyRequest.apiRequestID,
iri = ONTOLOGY_CACHE_LOCK_IRI,
task = () => makeTaskFuture(internalOntologyIri)
)
} yield taskResult
}
/**
* Changes ontology metadata.
*
* @param changeOntologyMetadataRequest the request to change the metadata.
* @return a [[ReadOntologyMetadataV2]] containing the new metadata.
*/
def changeOntologyMetadata(
changeOntologyMetadataRequest: ChangeOntologyMetadataRequestV2
): Future[ReadOntologyMetadataV2] = {
def makeTaskFuture(internalOntologyIri: SmartIri): Future[ReadOntologyMetadataV2] =
for {
cacheData <- Cache.getCacheData
// Check that the user has permission to update the ontology.
projectIri <- OntologyHelpers.checkPermissionsForOntologyUpdate(
internalOntologyIri = internalOntologyIri,
requestingUser = changeOntologyMetadataRequest.requestingUser
)
// Check that the ontology exists and has not been updated by another user since the client last read its metadata.
_ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate(
settings,
storeManager,
internalOntologyIri = internalOntologyIri,
expectedLastModificationDate = changeOntologyMetadataRequest.lastModificationDate,
featureFactoryConfig = changeOntologyMetadataRequest.featureFactoryConfig
)
// get the metadata of the ontology.
oldMetadata: OntologyMetadataV2 = cacheData.ontologies(internalOntologyIri).ontologyMetadata
// Was there a comment in the ontology metadata?
ontologyHasComment: Boolean = oldMetadata.comment.nonEmpty
// Update the metadata.
currentTime: Instant = Instant.now
updateSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt
.changeOntologyMetadata(
triplestore = settings.triplestoreType,
ontologyNamedGraphIri = internalOntologyIri,
ontologyIri = internalOntologyIri,
newLabel = changeOntologyMetadataRequest.label,
hasOldComment = ontologyHasComment,
deleteOldComment = ontologyHasComment && changeOntologyMetadataRequest.comment.nonEmpty,
newComment = changeOntologyMetadataRequest.comment,
lastModificationDate = changeOntologyMetadataRequest.lastModificationDate,
currentTime = currentTime
)
.toString()
_ <- (storeManager ? SparqlUpdateRequest(updateSparql)).mapTo[SparqlUpdateResponse]
// Check that the update was successful. To do this, we have to undo the SPARQL-escaping of the input.
// Is there any new label given?
label =
if (changeOntologyMetadataRequest.label.isEmpty) {
// No. Consider the old label for checking the update.
oldMetadata.label
} else {
// Yes. Consider the new label for checking the update.
changeOntologyMetadataRequest.label
}
// Is there any new comment given?
comment =
if (changeOntologyMetadataRequest.comment.isEmpty) {
// No. Consider the old comment for checking the update.
oldMetadata.comment
} else {
// Yes. Consider the new comment for checking the update.
changeOntologyMetadataRequest.comment
}
unescapedNewMetadata = OntologyMetadataV2(
ontologyIri = internalOntologyIri,
projectIri = Some(projectIri),
label = label,
comment = comment,
lastModificationDate = Some(currentTime)
).unescape
maybeLoadedOntologyMetadata: Option[OntologyMetadataV2] <-
OntologyHelpers.loadOntologyMetadata(
settings,
storeManager,
internalOntologyIri = internalOntologyIri,
featureFactoryConfig = changeOntologyMetadataRequest.featureFactoryConfig
)
_ = maybeLoadedOntologyMetadata match {
case Some(loadedOntologyMetadata) =>
if (loadedOntologyMetadata != unescapedNewMetadata) {
throw UpdateNotPerformedException()
}
case None => throw UpdateNotPerformedException()
}
// Update the ontology cache with the unescaped metadata.
_ = Cache.storeCacheData(
cacheData.copy(
ontologies = cacheData.ontologies + (internalOntologyIri -> cacheData
.ontologies(internalOntologyIri)
.copy(ontologyMetadata = unescapedNewMetadata))
)
)
} yield ReadOntologyMetadataV2(ontologies = Set(unescapedNewMetadata))
for {
_ <- OntologyHelpers.checkExternalOntologyIriForUpdate(changeOntologyMetadataRequest.ontologyIri)
internalOntologyIri = changeOntologyMetadataRequest.ontologyIri.toOntologySchema(InternalSchema)
// Do the remaining pre-update checks and the update while holding a global ontology cache lock.
taskResult <- IriLocker.runWithIriLock(
apiRequestID = changeOntologyMetadataRequest.apiRequestID,
iri = ONTOLOGY_CACHE_LOCK_IRI,
task = () => makeTaskFuture(internalOntologyIri = internalOntologyIri)
)
} yield taskResult
}
def deleteOntologyComment(
deleteOntologyCommentRequestV2: DeleteOntologyCommentRequestV2
): Future[ReadOntologyMetadataV2] = {
def makeTaskFuture(internalOntologyIri: SmartIri): Future[ReadOntologyMetadataV2] =
for {
cacheData <- Cache.getCacheData
// Check that the user has permission to update the ontology.
projectIri <- OntologyHelpers.checkPermissionsForOntologyUpdate(
internalOntologyIri = internalOntologyIri,
requestingUser = deleteOntologyCommentRequestV2.requestingUser
)
// Check that the ontology exists and has not been updated by another user since the client last read its metadata.
_ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate(
settings,
storeManager,
internalOntologyIri = internalOntologyIri,
expectedLastModificationDate = deleteOntologyCommentRequestV2.lastModificationDate,
featureFactoryConfig = deleteOntologyCommentRequestV2.featureFactoryConfig
)
// get the metadata of the ontology.
oldMetadata: OntologyMetadataV2 = cacheData.ontologies(internalOntologyIri).ontologyMetadata
// Was there a comment in the ontology metadata?
ontologyHasComment: Boolean = oldMetadata.comment.nonEmpty
// Update the metadata.
currentTime: Instant = Instant.now
updateSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt
.changeOntologyMetadata(
triplestore = settings.triplestoreType,
ontologyNamedGraphIri = internalOntologyIri,
ontologyIri = internalOntologyIri,
newLabel = None,
hasOldComment = ontologyHasComment,
deleteOldComment = true,
newComment = None,
lastModificationDate = deleteOntologyCommentRequestV2.lastModificationDate,
currentTime = currentTime
)
.toString()
_ <- (storeManager ? SparqlUpdateRequest(updateSparql)).mapTo[SparqlUpdateResponse]
// Check that the update was successful.
unescapedNewMetadata = OntologyMetadataV2(
ontologyIri = internalOntologyIri,
projectIri = Some(projectIri),
label = oldMetadata.label,
comment = None,
lastModificationDate = Some(currentTime)
).unescape
maybeLoadedOntologyMetadata: Option[OntologyMetadataV2] <-
OntologyHelpers.loadOntologyMetadata(
settings,
storeManager,
internalOntologyIri = internalOntologyIri,
featureFactoryConfig = deleteOntologyCommentRequestV2.featureFactoryConfig
)
_ = maybeLoadedOntologyMetadata match {
case Some(loadedOntologyMetadata) =>
if (loadedOntologyMetadata != unescapedNewMetadata) {
throw UpdateNotPerformedException()
}
case None => throw UpdateNotPerformedException()
}
// Update the ontology cache with the unescaped metadata.
_ = Cache.storeCacheData(
cacheData.copy(
ontologies = cacheData.ontologies + (internalOntologyIri -> cacheData
.ontologies(internalOntologyIri)
.copy(ontologyMetadata = unescapedNewMetadata))
)
)
} yield ReadOntologyMetadataV2(ontologies = Set(unescapedNewMetadata))
for {
_ <- OntologyHelpers.checkExternalOntologyIriForUpdate(deleteOntologyCommentRequestV2.ontologyIri)
internalOntologyIri = deleteOntologyCommentRequestV2.ontologyIri.toOntologySchema(InternalSchema)
// Do the remaining pre-update checks and the update while holding a global ontology cache lock.
taskResult <- IriLocker.runWithIriLock(
apiRequestID = deleteOntologyCommentRequestV2.apiRequestID,
iri = ONTOLOGY_CACHE_LOCK_IRI,
task = () => makeTaskFuture(internalOntologyIri = internalOntologyIri)
)
} yield taskResult
}
/**
* Creates a class in an existing ontology.
*
* @param createClassRequest the request to create the class.
* @return a [[ReadOntologyV2]] in the internal schema, the containing the definition of the new class.
*/
private def createClass(createClassRequest: CreateClassRequestV2): Future[ReadOntologyV2] = {
def makeTaskFuture(internalClassIri: SmartIri, internalOntologyIri: SmartIri): Future[ReadOntologyV2] = {
for {
cacheData <- Cache.getCacheData
internalClassDef: ClassInfoContentV2 = createClassRequest.classInfoContent.toOntologySchema(InternalSchema)
// Check that the ontology exists and has not been updated by another user since the client last read it.
_ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate(
settings,
storeManager,
internalOntologyIri = internalOntologyIri,
expectedLastModificationDate = createClassRequest.lastModificationDate,
featureFactoryConfig = createClassRequest.featureFactoryConfig
)
// Check that the class's rdf:type is owl:Class.
rdfType: SmartIri = internalClassDef.requireIriObject(
OntologyConstants.Rdf.Type.toSmartIri,
throw BadRequestException(s"No rdf:type specified")
)
_ = if (rdfType != OntologyConstants.Owl.Class.toSmartIri) {
throw BadRequestException(s"Invalid rdf:type for property: $rdfType")
}
ontology = cacheData.ontologies(internalOntologyIri)
// Check that the class doesn't exist yet.
_ = if (ontology.classes.contains(internalClassIri)) {
throw BadRequestException(s"Class ${createClassRequest.classInfoContent.classIri} already exists")
}
// Check that the class's IRI isn't already used for something else.
_ = if (ontology.properties.contains(internalClassIri) || ontology.individuals.contains(internalClassIri)) {
throw BadRequestException(s"IRI ${createClassRequest.classInfoContent.classIri} is already used")
}
// Check that the base classes that have Knora IRIs are defined as Knora resource classes.
missingBaseClasses =
internalClassDef.subClassOf
.filter(_.isKnoraInternalEntityIri)
.filter(baseClassIri => !OntologyHelpers.isKnoraInternalResourceClass(baseClassIri, cacheData))
_ = if (missingBaseClasses.nonEmpty) {
throw BadRequestException(
s"One or more specified base classes are invalid: ${missingBaseClasses.mkString(", ")}"
)
}
// Check for rdfs:subClassOf cycles.
allBaseClassIrisWithoutSelf: Set[SmartIri] = internalClassDef.subClassOf.flatMap { baseClassIri =>
cacheData.subClassOfRelations
.getOrElse(baseClassIri, Set.empty[SmartIri])
.toSet
}
_ = if (allBaseClassIrisWithoutSelf.contains(internalClassIri)) {
throw BadRequestException(
s"Class ${createClassRequest.classInfoContent.classIri} would have a cyclical rdfs:subClassOf"
)
}
// Check that the class is a subclass of knora-base:Resource.
allBaseClassIris: Seq[SmartIri] = internalClassIri +: allBaseClassIrisWithoutSelf.toSeq
_ = if (!allBaseClassIris.contains(OntologyConstants.KnoraBase.Resource.toSmartIri)) {
throw BadRequestException(
s"Class ${createClassRequest.classInfoContent.classIri} would not be a subclass of knora-api:Resource"
)
}
// Check that the cardinalities are valid, and add any inherited cardinalities.
(internalClassDefWithLinkValueProps, cardinalitiesForClassWithInheritance) =
OntologyHelpers
.checkCardinalitiesBeforeAddingAndIfNecessaryAddLinkValueProperties(
internalClassDef = internalClassDef,
allBaseClassIris = allBaseClassIris.toSet,
cacheData = cacheData
)
// Check that the class definition doesn't refer to any non-shared ontologies in other projects.
_ = Cache.checkOntologyReferencesInClassDef(
ontologyCacheData = cacheData,
classDef = internalClassDefWithLinkValueProps,
errorFun = { msg: String =>
throw BadRequestException(msg)
}
)
// Prepare to update the ontology cache, undoing the SPARQL-escaping of the input.
propertyIrisOfAllCardinalitiesForClass = cardinalitiesForClassWithInheritance.keySet
inheritedCardinalities: Map[SmartIri, KnoraCardinalityInfo] =
cardinalitiesForClassWithInheritance.filterNot { case (propertyIri, _) =>
internalClassDefWithLinkValueProps.directCardinalities.contains(propertyIri)
}
unescapedClassDefWithLinkValueProps = internalClassDefWithLinkValueProps.unescape
readClassInfo = ReadClassInfoV2(
entityInfoContent = unescapedClassDefWithLinkValueProps,
allBaseClasses = allBaseClassIris,
isResourceClass = true,
canBeInstantiated = true,
inheritedCardinalities = inheritedCardinalities,
knoraResourceProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri =>
OntologyHelpers.isKnoraResourceProperty(propertyIri, cacheData)
),
linkProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri =>
OntologyHelpers.isLinkProp(propertyIri, cacheData)
),
linkValueProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri =>
OntologyHelpers.isLinkValueProp(propertyIri, cacheData)
),
fileValueProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri =>
OntologyHelpers.isFileValueProp(propertyIri, cacheData)
)