/
OntologyHelpers.scala
2211 lines (1947 loc) · 96.4 KB
/
OntologyHelpers.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 © 2021 - 2022 Swiss National Data and Service Center for the Humanities and/or DaSCH Service Platform contributors.
* SPDX-License-Identifier: Apache-2.0
*/
package org.knora.webapi.responders.v2.ontology
import akka.actor.ActorRef
import akka.http.scaladsl.util.FastFuture
import akka.pattern._
import akka.util.Timeout
import org.knora.webapi.exceptions._
import org.knora.webapi.feature.FeatureFactoryConfig
import org.knora.webapi.messages.IriConversions._
import org.knora.webapi.messages.StringFormatter.{SalsahGuiAttribute, SalsahGuiAttributeDefinition}
import org.knora.webapi.messages.admin.responder.usersmessages.UserADM
import org.knora.webapi.messages.store.triplestoremessages._
import org.knora.webapi.messages.util.ErrorHandlingMap
import org.knora.webapi.messages.util.rdf.{SparqlSelectResult, VariableResultsRow}
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.standoffmessages.StandoffDataTypeClasses
import org.knora.webapi.messages.{OntologyConstants, SmartIri, StringFormatter}
import org.knora.webapi.responders.v2.ontology.Cache.OntologyCacheData
import org.knora.webapi.settings.KnoraSettingsImpl
import org.knora.webapi.{ApiV2Complex, ApiV2Schema, ApiV2Simple, IRI, InternalSchema, OntologySchema}
import java.time.Instant
import scala.collection.immutable
import scala.concurrent.{ExecutionContext, Future}
object OntologyHelpers {
/**
* Represents the contents of a named graph representing an ontology.
*
* @param ontologyIri the ontology IRI, which is also the IRI of the named graph.
* @param constructResponse the triplestore's response to a CONSTRUCT query that gets the contents of the named graph.
*/
case class OntologyGraph(ontologyIri: SmartIri, constructResponse: SparqlExtendedConstructResponse)
/**
* Given the triplestore's response to `getAllOntologyMetadata.scala.txt`, constructs a map of ontology IRIs
* to ontology metadata for the ontology cache.
*
* @param allOntologyMetadataResponse the triplestore's response to the SPARQL query `getAllOntologyMetadata.scala.txt`.
* @return a map of ontology IRIs to ontology metadata.
*/
def buildOntologyMetadata(
allOntologyMetadataResponse: SparqlSelectResult
)(implicit stringFormatter: StringFormatter): Map[SmartIri, OntologyMetadataV2] =
allOntologyMetadataResponse.results.bindings.groupBy(_.rowMap("ontologyGraph")).map {
case (ontologyGraph: IRI, rows: Seq[VariableResultsRow]) =>
val ontologyIri = rows.head.rowMap("ontologyIri")
if (ontologyIri != ontologyGraph) {
throw InconsistentRepositoryDataException(
s"Ontology $ontologyIri must be stored in named graph $ontologyIri, but it is in $ontologyGraph"
)
}
val ontologySmartIri = ontologyIri.toSmartIri
if (!ontologySmartIri.isKnoraOntologyIri) {
throw InconsistentRepositoryDataException(s"Ontology $ontologySmartIri is not a Knora ontology")
}
val ontologyMetadataMap: Map[IRI, String] = rows.map { row =>
val pred =
row.rowMap.getOrElse(
"ontologyPred",
throw InconsistentRepositoryDataException(s"Empty predicate in ontology $ontologyIri")
)
val obj = row.rowMap.getOrElse(
"ontologyObj",
throw InconsistentRepositoryDataException(s"Empty object for predicate $pred in ontology $ontologyIri")
)
pred -> obj
}.toMap
val projectIri: SmartIri = ontologyMetadataMap
.getOrElse(
OntologyConstants.KnoraBase.AttachedToProject,
throw InconsistentRepositoryDataException(s"Ontology $ontologyIri has no knora-base:attachedToProject")
)
.toSmartIri
val ontologyLabel: String =
ontologyMetadataMap.getOrElse(OntologyConstants.Rdfs.Label, ontologySmartIri.getOntologyName)
val lastModificationDate: Option[Instant] = ontologyMetadataMap
.get(OntologyConstants.KnoraBase.LastModificationDate)
.map(instant =>
stringFormatter.xsdDateTimeStampToInstant(
instant,
throw InconsistentRepositoryDataException(s"Invalid UTC instant: $instant")
)
)
val ontologyVersion: Option[String] = ontologyMetadataMap.get(OntologyConstants.KnoraBase.OntologyVersion)
ontologySmartIri -> OntologyMetadataV2(
ontologyIri = ontologySmartIri,
projectIri = Some(projectIri),
label = Some(ontologyLabel),
lastModificationDate = lastModificationDate,
ontologyVersion = ontologyVersion
)
}
/**
* Reads an ontology's metadata.
*
* @param internalOntologyIri the ontology's internal IRI.
* @param featureFactoryConfig the feature factory configuration.
* @return an [[OntologyMetadataV2]], or [[None]] if the ontology is not found.
*/
def loadOntologyMetadata(
settings: KnoraSettingsImpl,
storeManager: ActorRef,
internalOntologyIri: SmartIri,
featureFactoryConfig: FeatureFactoryConfig
)(implicit
executionContext: ExecutionContext,
stringFormatter: StringFormatter,
timeout: Timeout
): Future[Option[OntologyMetadataV2]] = {
for {
_ <- Future {
if (!internalOntologyIri.getOntologySchema.contains(InternalSchema)) {
throw AssertionException(s"Expected an internal ontology IRI: $internalOntologyIri")
}
}
getOntologyInfoSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt
.getOntologyInfo(
triplestore = settings.triplestoreType,
ontologyIri = internalOntologyIri
)
.toString()
getOntologyInfoResponse <- (storeManager ? SparqlConstructRequest(
sparql = getOntologyInfoSparql,
featureFactoryConfig = featureFactoryConfig
)).mapTo[SparqlConstructResponse]
metadata: Option[OntologyMetadataV2] =
if (getOntologyInfoResponse.statements.isEmpty) {
None
} else {
getOntologyInfoResponse.statements.get(
internalOntologyIri.toString
) match {
case Some(statements: Seq[(IRI, String)]) =>
val statementMap: Map[IRI, Seq[String]] = statements.groupBy { case (pred, _) =>
pred
}.map { case (pred, predStatements) =>
pred -> predStatements.map { case (_, obj) =>
obj
}
}
val projectIris: Seq[String] = statementMap.getOrElse(
OntologyConstants.KnoraBase.AttachedToProject,
throw InconsistentRepositoryDataException(
s"Ontology $internalOntologyIri has no knora-base:attachedToProject"
)
)
val labels: Seq[String] = statementMap.getOrElse(
OntologyConstants.Rdfs.Label,
Seq.empty[String]
)
val comments: Seq[String] = statementMap.getOrElse(
OntologyConstants.Rdfs.Comment,
Seq.empty[String]
)
val lastModDates: Seq[String] =
statementMap.getOrElse(
OntologyConstants.KnoraBase.LastModificationDate,
Seq.empty[String]
)
val projectIri = if (projectIris.size > 1) {
throw InconsistentRepositoryDataException(
s"Ontology $internalOntologyIri has more than one knora-base:attachedToProject"
)
} else {
projectIris.head.toSmartIri
}
if (!internalOntologyIri.isKnoraBuiltInDefinitionIri) {
if (projectIri.toString == OntologyConstants.KnoraAdmin.SystemProject) {
throw InconsistentRepositoryDataException(
s"Ontology $internalOntologyIri cannot be in project ${OntologyConstants.KnoraAdmin.SystemProject}"
)
}
if (
internalOntologyIri.isKnoraSharedDefinitionIri && projectIri.toString != OntologyConstants.KnoraAdmin.DefaultSharedOntologiesProject
) {
throw InconsistentRepositoryDataException(
s"Shared ontology $internalOntologyIri must be in project ${OntologyConstants.KnoraAdmin.DefaultSharedOntologiesProject}"
)
}
}
val label: String = if (labels.size > 1) {
throw InconsistentRepositoryDataException(
s"Ontology $internalOntologyIri has more than one rdfs:label"
)
} else if (labels.isEmpty) {
internalOntologyIri.getOntologyName
} else {
labels.head
}
val comment: Option[String] = if (comments.size > 1) {
throw InconsistentRepositoryDataException(
s"Ontology $internalOntologyIri has more than one rdfs:comment"
)
} else comments.headOption
val lastModificationDate: Option[Instant] =
if (lastModDates.size > 1) {
throw InconsistentRepositoryDataException(
s"Ontology $internalOntologyIri has more than one ${OntologyConstants.KnoraBase.LastModificationDate}"
)
} else if (lastModDates.isEmpty) {
None
} else {
val dateStr = lastModDates.head
Some(
stringFormatter.xsdDateTimeStampToInstant(
dateStr,
throw InconsistentRepositoryDataException(
s"Invalid ${OntologyConstants.KnoraBase.LastModificationDate}: $dateStr"
)
)
)
}
Some(
OntologyMetadataV2(
ontologyIri = internalOntologyIri,
projectIri = Some(projectIri),
label = Some(label),
comment = comment,
lastModificationDate = lastModificationDate
)
)
case None => None
}
}
} yield metadata
}
/**
* Given a list of ontology graphs, finds the IRIs of all subjects whose `rdf:type` is contained in a given set of types.
*
* @param ontologyGraphs a list of ontology graphs.
* @param entityTypes the types of entities to be found.
* @return a map of ontology IRIs to sets of the IRIs of entities with matching types in each ontology.
*/
def getEntityIrisFromOntologyGraphs(ontologyGraphs: Iterable[OntologyGraph], entityTypes: Set[IRI])(implicit
stringFormatter: StringFormatter
): Map[SmartIri, Set[SmartIri]] = {
val entityTypesAsIriLiterals = entityTypes.map(entityType => IriLiteralV2(entityType))
ontologyGraphs.map { ontologyGraph =>
val entityIrisInGraph: Set[SmartIri] =
ontologyGraph.constructResponse.statements.foldLeft(Set.empty[SmartIri]) {
case (acc, (subjectIri: IriSubjectV2, subjectStatements: Map[SmartIri, Seq[LiteralV2]])) =>
val subjectTypeLiterals: Seq[IriLiteralV2] = subjectStatements
.getOrElse(
OntologyConstants.Rdf.Type.toSmartIri,
throw InconsistentRepositoryDataException(s"Subject $subjectIri has no rdf:type")
)
.collect { case iriLiteral: IriLiteralV2 =>
iriLiteral
}
if (subjectTypeLiterals.exists(entityTypesAsIriLiterals.contains)) {
acc + subjectIri.value.toSmartIri
} else {
acc
}
case (acc, _) => acc
}
ontologyGraph.ontologyIri -> entityIrisInGraph
}.toMap
}
/**
* Constructs a map of class IRIs to [[ReadClassInfoV2]] instances, based on class definitions loaded from the
* triplestore.
*
* @param classDefs a map of class IRIs to class definitions.
* @param directClassCardinalities a map of the cardinalities defined directly on each class. Each resource class
* IRI points to a map of property IRIs to [[KnoraCardinalityInfo]] objects.
* @param classCardinalitiesWithInheritance a map of the cardinalities defined directly on each class or inherited from
* base classes. Each class IRI points to a map of property IRIs to
* [[KnoraCardinalityInfo]] objects.
* @param directSubClassOfRelations a map of class IRIs to their immediate base classes.
* @param allSubClassOfRelations a map of class IRIs to all their base classes.
* @param allSubPropertyOfRelations a map of property IRIs to all their base properties.
* @param allPropertyDefs a map of property IRIs to property definitions.
* @param allKnoraResourceProps a set of the IRIs of all Knora resource properties.
* @param allLinkProps a set of the IRIs of all link properties.
* @param allLinkValueProps a set of the IRIs of link value properties.
* @param allFileValueProps a set of the IRIs of all file value properties.
* @return a map of resource class IRIs to their definitions.
*/
def makeReadClassInfos(
classDefs: Map[SmartIri, ClassInfoContentV2],
directClassCardinalities: Map[SmartIri, Map[SmartIri, KnoraCardinalityInfo]],
classCardinalitiesWithInheritance: Map[SmartIri, Map[SmartIri, KnoraCardinalityInfo]],
directSubClassOfRelations: Map[SmartIri, Set[SmartIri]],
allSubClassOfRelations: Map[SmartIri, Seq[SmartIri]],
allSubPropertyOfRelations: Map[SmartIri, Set[SmartIri]],
allPropertyDefs: Map[SmartIri, PropertyInfoContentV2],
allKnoraResourceProps: Set[SmartIri],
allLinkProps: Set[SmartIri],
allLinkValueProps: Set[SmartIri],
allFileValueProps: Set[SmartIri]
)(implicit stringFormatter: StringFormatter): Map[SmartIri, ReadClassInfoV2] = {
classDefs.map { case (classIri, classDef) =>
val ontologyIri = classIri.getOntologyFromEntity
// Get the OWL cardinalities for the class.
val allOwlCardinalitiesForClass: Map[SmartIri, KnoraCardinalityInfo] =
classCardinalitiesWithInheritance(classIri)
val allPropertyIrisForCardinalitiesInClass: Set[SmartIri] = allOwlCardinalitiesForClass.keys.toSet
// Identify the Knora resource properties, link properties, link value properties, and file value properties in the cardinalities.
val knoraResourcePropsInClass = allPropertyIrisForCardinalitiesInClass.filter(allKnoraResourceProps)
val linkPropsInClass = allPropertyIrisForCardinalitiesInClass.filter(allLinkProps)
val linkValuePropsInClass = allPropertyIrisForCardinalitiesInClass.filter(allLinkValueProps)
val fileValuePropsInClass = allPropertyIrisForCardinalitiesInClass.filter(allFileValueProps)
// Make sure there is a link value property for each link property.
val missingLinkValueProps = linkPropsInClass.map(_.fromLinkPropToLinkValueProp) -- linkValuePropsInClass
if (missingLinkValueProps.nonEmpty) {
throw InconsistentRepositoryDataException(
s"Resource class $classIri has cardinalities for one or more link properties without corresponding link value properties. The missing (or incorrectly defined) property or properties: ${missingLinkValueProps
.mkString(", ")}"
)
}
// Make sure there is a link property for each link value property.
val missingLinkProps = linkValuePropsInClass.map(_.fromLinkValuePropToLinkProp) -- linkPropsInClass
if (missingLinkProps.nonEmpty) {
throw InconsistentRepositoryDataException(
s"Resource class $classIri has cardinalities for one or more link value properties without corresponding link properties. The missing (or incorrectly defined) property or properties: ${missingLinkProps
.mkString(", ")}"
)
}
// Make sure that the cardinality for each link property is the same as the cardinality for the corresponding link value property.
for (linkProp <- linkPropsInClass) {
val linkValueProp: SmartIri = linkProp.fromLinkPropToLinkValueProp
val linkPropCardinality: KnoraCardinalityInfo = allOwlCardinalitiesForClass(linkProp)
val linkValuePropCardinality: KnoraCardinalityInfo = allOwlCardinalitiesForClass(linkValueProp)
if (!linkPropCardinality.equalsWithoutGuiOrder(linkValuePropCardinality)) {
throw InconsistentRepositoryDataException(
s"In class $classIri, the cardinality for $linkProp is different from the cardinality for $linkValueProp"
)
}
}
// The class's direct cardinalities.
val directCardinalities: Map[SmartIri, KnoraCardinalityInfo] = directClassCardinalities(classIri)
val directCardinalityPropertyIris = directCardinalities.keySet
val allBaseClasses: Seq[SmartIri] = allSubClassOfRelations(classIri)
val isKnoraResourceClass = allBaseClasses.contains(OntologyConstants.KnoraBase.Resource.toSmartIri)
val isStandoffClass = allBaseClasses.contains(OntologyConstants.KnoraBase.StandoffTag.toSmartIri)
val isValueClass = !(isKnoraResourceClass || isStandoffClass) && allBaseClasses.contains(
OntologyConstants.KnoraBase.Value.toSmartIri
)
// If the class is defined in project-specific ontology, do the following checks.
if (!ontologyIri.isKnoraBuiltInDefinitionIri) {
// It must be either a resource class or a standoff class, but not both.
if (!(isKnoraResourceClass ^ isStandoffClass)) {
throw InconsistentRepositoryDataException(
s"Class $classIri must be a subclass either of knora-base:Resource or of knora-base:StandoffTag (but not both)"
)
}
// All its cardinalities must be on properties that are defined.
val cardinalitiesOnMissingProps = directCardinalityPropertyIris.filterNot(allPropertyDefs.keySet)
if (cardinalitiesOnMissingProps.nonEmpty) {
throw InconsistentRepositoryDataException(
s"Class $classIri has one or more cardinalities on undefined properties: ${cardinalitiesOnMissingProps
.mkString(", ")}"
)
}
// It cannot have cardinalities both on property P and on a subproperty of P.
val maybePropertyAndSubproperty: Option[(SmartIri, SmartIri)] = findPropertyAndSubproperty(
propertyIris = allPropertyIrisForCardinalitiesInClass,
subPropertyOfRelations = allSubPropertyOfRelations
)
maybePropertyAndSubproperty match {
case Some((basePropertyIri, propertyIri)) =>
throw InconsistentRepositoryDataException(
s"Class $classIri has a cardinality on property $basePropertyIri and on its subproperty $propertyIri"
)
case None => ()
}
if (isKnoraResourceClass) {
// If it's a resource class, all its directly defined cardinalities must be on Knora resource properties, not including knora-base:resourceProperty or knora-base:hasValue.
val cardinalitiesOnInvalidProps = directCardinalityPropertyIris.filterNot(allKnoraResourceProps)
if (cardinalitiesOnInvalidProps.nonEmpty) {
throw InconsistentRepositoryDataException(
s"Resource class $classIri has one or more cardinalities on properties that are not Knora resource properties: ${cardinalitiesOnInvalidProps
.mkString(", ")}"
)
}
Set(OntologyConstants.KnoraBase.ResourceProperty, OntologyConstants.KnoraBase.HasValue).foreach {
invalidProp =>
if (directCardinalityPropertyIris.contains(invalidProp.toSmartIri)) {
throw InconsistentRepositoryDataException(
s"Class $classIri has a cardinality on property $invalidProp, which is not allowed"
)
}
}
// Check for invalid cardinalities on boolean properties.
checkForInvalidBooleanCardinalities(
classIri = classIri,
directCardinalities = directCardinalities,
allPropertyDefs = allPropertyDefs,
schemaForErrors = InternalSchema,
errorFun = { msg: String =>
throw InconsistentRepositoryDataException(msg)
}
)
// All its base classes with Knora IRIs must also be resource classes.
for (baseClass <- classDef.subClassOf) {
if (
baseClass.isKnoraDefinitionIri && !allSubClassOfRelations(baseClass).contains(
OntologyConstants.KnoraBase.Resource.toSmartIri
)
) {
throw InconsistentRepositoryDataException(
s"Class $classIri is a subclass of knora-base:Resource, but its base class $baseClass is not"
)
}
}
// It must have an rdfs:label.
if (!classDef.predicates.contains(OntologyConstants.Rdfs.Label.toSmartIri)) {
throw InconsistentRepositoryDataException(s"Class $classIri has no rdfs:label")
}
} else {
// If it's a standoff class, none of its cardinalities must be on Knora resource properties.
val cardinalitiesOnInvalidProps = directCardinalityPropertyIris.filter(allKnoraResourceProps)
if (cardinalitiesOnInvalidProps.nonEmpty) {
throw InconsistentRepositoryDataException(
s"Standoff class $classIri has one or more cardinalities on properties that are Knora resource properties: ${cardinalitiesOnInvalidProps
.mkString(", ")}"
)
}
// All its base classes with Knora IRIs must also be standoff classes.
for (baseClass <- classDef.subClassOf) {
if (baseClass.isKnoraDefinitionIri) {
if (
isStandoffClass && !allSubClassOfRelations(baseClass).contains(
OntologyConstants.KnoraBase.StandoffTag.toSmartIri
)
) {
throw InconsistentRepositoryDataException(
s"Class $classIri is a subclass of knora-base:StandoffTag, but its base class $baseClass is not"
)
}
}
}
}
}
// Each class must be a subclass of all the classes that are subject class constraints of the properties in its cardinalities.
checkSubjectClassConstraintsViaCardinalities(
internalClassDef = classDef,
allBaseClassIris = allBaseClasses.toSet,
allClassCardinalityKnoraPropertyDefs =
allPropertyDefs.view.filterKeys(allOwlCardinalitiesForClass.keySet).toMap,
errorSchema = InternalSchema,
errorFun = { msg: String =>
throw InconsistentRepositoryDataException(msg)
}
)
val inheritedCardinalities: Map[SmartIri, KnoraCardinalityInfo] = allOwlCardinalitiesForClass.filterNot {
case (propertyIri, _) => directCardinalityPropertyIris.contains(propertyIri)
}
// Get the class's standoff data type, if any. A standoff class that has a datatype is a subclass of one of the classes
// in StandoffDataTypeClasses.
val standoffDataType: Set[SmartIri] = allSubClassOfRelations(classIri).toSet
.intersect(StandoffDataTypeClasses.getStandoffClassIris.map(_.toSmartIri))
if (standoffDataType.size > 1) {
throw InconsistentRepositoryDataException(
s"Class $classIri is a subclass of more than one standoff datatype: ${standoffDataType.mkString(", ")}"
)
}
// A class can be instantiated if it's in a built-in ontology and marked with knora-base:canBeInstantiated, or if it's
// a resource class in a project-specific ontology.
val canBeInstantiated = if (ontologyIri.isKnoraBuiltInDefinitionIri) {
classDef.predicates
.get(OntologyConstants.KnoraBase.CanBeInstantiated.toSmartIri)
.flatMap(_.objects.headOption) match {
case Some(booleanLiteral: BooleanLiteralV2) => booleanLiteral.value
case _ => false
}
} else {
isKnoraResourceClass
}
val readClassInfo = ReadClassInfoV2(
entityInfoContent = classDef,
allBaseClasses = allBaseClasses,
isResourceClass = isKnoraResourceClass,
isStandoffClass = isStandoffClass,
isValueClass = isValueClass,
canBeInstantiated = canBeInstantiated,
inheritedCardinalities = inheritedCardinalities,
knoraResourceProperties = knoraResourcePropsInClass,
linkProperties = linkPropsInClass,
linkValueProperties = linkValuePropsInClass,
fileValueProperties = fileValuePropsInClass,
standoffDataType = standoffDataType.headOption match {
case Some(dataType: SmartIri) =>
Some(
StandoffDataTypeClasses.lookup(
dataType.toString,
throw InconsistentRepositoryDataException(s"$dataType is not a valid standoff datatype")
)
)
case None => None
}
)
classIri -> readClassInfo
}
}
/**
* Checks that a class is a subclass of all the classes that are subject class constraints of the Knora resource properties in its cardinalities.
*
* @param internalClassDef the class definition.
* @param allBaseClassIris the IRIs of all the class's base classes.
* @param allClassCardinalityKnoraPropertyDefs the definitions of all the Knora resource properties on which the class has cardinalities (whether directly defined
* or inherited).
* @param errorSchema the ontology schema to be used in error messages.
* @param errorFun a function that throws an exception. It will be called with an error message argument if the cardinalities are invalid.
*/
private def checkSubjectClassConstraintsViaCardinalities(
internalClassDef: ClassInfoContentV2,
allBaseClassIris: Set[SmartIri],
allClassCardinalityKnoraPropertyDefs: Map[SmartIri, PropertyInfoContentV2],
errorSchema: OntologySchema,
errorFun: String => Nothing
)(implicit stringFormatter: StringFormatter): Unit =
allClassCardinalityKnoraPropertyDefs.foreach { case (propertyIri, propertyDef) =>
propertyDef.predicates.get(OntologyConstants.KnoraBase.SubjectClassConstraint.toSmartIri) match {
case Some(subjectClassConstraintPred) =>
val subjectClassConstraint = subjectClassConstraintPred.requireIriObject(
throw InconsistentRepositoryDataException(
s"Property $propertyIri has an invalid object for ${OntologyConstants.KnoraBase.SubjectClassConstraint}"
)
)
if (!allBaseClassIris.contains(subjectClassConstraint)) {
val hasOrWouldInherit = if (internalClassDef.directCardinalities.contains(propertyIri)) {
"has"
} else {
"would inherit"
}
errorFun(
s"Class ${internalClassDef.classIri.toOntologySchema(errorSchema)} $hasOrWouldInherit a cardinality for property ${propertyIri
.toOntologySchema(errorSchema)}, but is not a subclass of that property's ${OntologyConstants.KnoraBase.SubjectClassConstraint.toSmartIri
.toOntologySchema(errorSchema)}, ${subjectClassConstraint.toOntologySchema(errorSchema)}"
)
}
case None => ()
}
}
/**
* Checks for invalid cardinalities on boolean properties.
*
* @param classIri the class IRI.
* @param directCardinalities the cardinalities directly defined on the class.
* @param allPropertyDefs all property definitions.
*/
def checkForInvalidBooleanCardinalities(
classIri: SmartIri,
directCardinalities: Map[SmartIri, KnoraCardinalityInfo],
allPropertyDefs: Map[SmartIri, PropertyInfoContentV2],
schemaForErrors: OntologySchema,
errorFun: String => Nothing
)(implicit stringFormatter: StringFormatter): Unit = {
// A cardinality on a property with a boolean object must be 1 or 0-1.
val invalidCardinalitiesOnBooleanProps: Set[SmartIri] = directCardinalities.filter {
case (propertyIri, knoraCardinalityInfo) =>
val objectClassConstraintIri = OntologyConstants.KnoraBase.ObjectClassConstraint.toSmartIri
val propertyObjectClassConstraint: SmartIri = allPropertyDefs(propertyIri).requireIriObject(
objectClassConstraintIri,
errorFun(s"Property ${propertyIri
.toOntologySchema(schemaForErrors)} has no ${objectClassConstraintIri.toOntologySchema(schemaForErrors)}")
)
propertyObjectClassConstraint == OntologyConstants.KnoraBase.BooleanValue.toSmartIri &&
!(knoraCardinalityInfo.cardinality == Cardinality.MustHaveOne || knoraCardinalityInfo.cardinality == Cardinality.MayHaveOne)
}.keySet
if (invalidCardinalitiesOnBooleanProps.nonEmpty) {
errorFun(
s"Class ${classIri.toOntologySchema(schemaForErrors).toSparql} has one or more invalid cardinalities on boolean properties: ${invalidCardinalitiesOnBooleanProps
.map(_.toOntologySchema(schemaForErrors).toSparql)
.mkString(", ")}"
)
}
}
/**
* Constructs a map of property IRIs to [[ReadPropertyInfoV2]] instances, based on property definitions loaded from the
* triplestore.
*
* @param propertyDefs a map of property IRIs to property definitions.
* @param directSubPropertyOfRelations a map of property IRIs to their immediate base properties.
* @param allSubPropertyOfRelations a map of property IRIs to all their base properties.
* @param allSubClassOfRelations a map of class IRIs to all their base classes.
* @param allGuiAttributeDefinitions a map of `Guielement` IRIs to sets of [[SalsahGuiAttributeDefinition]].
* @param allKnoraResourceProps a set of the IRIs of all Knora resource properties.
* @param allLinkProps a set of the IRIs of all link properties.
* @param allLinkValueProps a set of the IRIs of link value properties.
* @param allFileValueProps a set of the IRIs of all file value properties.
* @return a map of property IRIs to [[ReadPropertyInfoV2]] instances.
*/
def makeReadPropertyInfos(
propertyDefs: Map[SmartIri, PropertyInfoContentV2],
directSubPropertyOfRelations: Map[SmartIri, Set[SmartIri]],
allSubPropertyOfRelations: Map[SmartIri, Set[SmartIri]],
allSubClassOfRelations: Map[SmartIri, Seq[SmartIri]],
allGuiAttributeDefinitions: Map[SmartIri, Set[SalsahGuiAttributeDefinition]],
allKnoraResourceProps: Set[SmartIri],
allLinkProps: Set[SmartIri],
allLinkValueProps: Set[SmartIri],
allFileValueProps: Set[SmartIri]
)(implicit stringFormatter: StringFormatter): Map[SmartIri, ReadPropertyInfoV2] =
propertyDefs.map { case (propertyIri, propertyDef) =>
val ontologyIri = propertyIri.getOntologyFromEntity
validateGuiAttributes(
propertyInfoContent = propertyDef,
allGuiAttributeDefinitions = allGuiAttributeDefinitions,
errorFun = { msg: String =>
throw InconsistentRepositoryDataException(msg)
}
)
val isResourceProp = allKnoraResourceProps.contains(propertyIri)
val isValueProp =
allSubPropertyOfRelations(propertyIri).contains(OntologyConstants.KnoraBase.HasValue.toSmartIri)
val isLinkProp = allLinkProps.contains(propertyIri)
val isLinkValueProp = allLinkValueProps.contains(propertyIri)
val isFileValueProp = allFileValueProps.contains(propertyIri)
// If the property is defined in a project-specific ontology and is a Knora resource property (a subproperty of knora-base:hasValue or knora-base:hasLinkTo), do the following checks.
if (!propertyIri.isKnoraBuiltInDefinitionIri && isResourceProp) {
// The property must be a subproperty of knora-base:hasValue or knora-base:hasLinkTo, but not both.
if (isValueProp && isLinkProp) {
throw InconsistentRepositoryDataException(
s"Property $propertyIri cannot be a subproperty of both knora-base:hasValue and knora-base:hasLinkTo"
)
}
// It can't be a subproperty of knora-base:hasFileValue.
if (isFileValueProp) {
throw InconsistentRepositoryDataException(
s"Property $propertyIri cannot be a subproperty of knora-base:hasFileValue"
)
}
// Each of its base properties that has a Knora IRI must also be a Knora resource property.
for (baseProperty <- propertyDef.subPropertyOf) {
if (baseProperty.isKnoraDefinitionIri && !allKnoraResourceProps.contains(baseProperty)) {
throw InconsistentRepositoryDataException(
s"Property $propertyIri is a subproperty of knora-base:hasValue or knora-base:hasLinkTo, but its base property $baseProperty is not"
)
}
}
// It must have an rdfs:label.
if (!propertyDef.predicates.contains(OntologyConstants.Rdfs.Label.toSmartIri)) {
throw InconsistentRepositoryDataException(s"Property $propertyIri has no rdfs:label")
}
}
// A property is editable if it's in a built-in ontology and marked with knora-base:isEditable,
// or if it's a resource property in a project-specific ontology.
val isEditable = if (ontologyIri.isKnoraBuiltInDefinitionIri) {
propertyDef.predicates
.get(OntologyConstants.KnoraBase.IsEditable.toSmartIri)
.flatMap(_.objects.headOption) match {
case Some(booleanLiteral: BooleanLiteralV2) => booleanLiteral.value
case _ => false
}
} else {
isResourceProp
}
val propertyEntityInfo = ReadPropertyInfoV2(
entityInfoContent = propertyDef,
isResourceProp = isResourceProp,
isEditable = isEditable,
isLinkProp = isLinkProp,
isLinkValueProp = isLinkValueProp,
isFileValueProp = isFileValueProp,
isStandoffInternalReferenceProperty = allSubPropertyOfRelations(propertyIri).contains(
OntologyConstants.KnoraBase.StandoffTagHasInternalReference.toSmartIri
)
)
propertyIri -> propertyEntityInfo
}
/**
* Constructs a map of OWL named individual IRIs to [[ReadIndividualInfoV2]] instances.
*
* @param individualDefs a map of OWL named individual IRIs to named individuals.
* @return a map of individual IRIs to [[ReadIndividualInfoV2]] instances.
*/
def makeReadIndividualInfos(
individualDefs: Map[SmartIri, IndividualInfoContentV2]
): Map[SmartIri, ReadIndividualInfoV2] =
individualDefs.map { case (individualIri, individual) =>
individualIri -> ReadIndividualInfoV2(individual)
}
/**
* Given all the OWL named individuals available, constructs a map of `salsah-gui:Guielement` individuals to
* their GUI attribute definitions.
*
* @param allIndividuals all the OWL named individuals available.
* @return a map of `salsah-gui:Guielement` individuals to their GUI attribute definitions.
*/
def makeGuiAttributeDefinitions(
allIndividuals: Map[SmartIri, IndividualInfoContentV2]
)(implicit stringFormatter: StringFormatter): Map[SmartIri, Set[SalsahGuiAttributeDefinition]] = {
val guiElementIndividuals: Map[SmartIri, IndividualInfoContentV2] = allIndividuals.filter { case (_, individual) =>
individual.getRdfType.toString == OntologyConstants.SalsahGui.GuiElementClass
}
guiElementIndividuals.map { case (guiElementIri, guiElementIndividual) =>
val attributeDefs: Set[SalsahGuiAttributeDefinition] =
guiElementIndividual.predicates.get(OntologyConstants.SalsahGui.GuiAttributeDefinition.toSmartIri) match {
case Some(predicateInfo) =>
predicateInfo.objects.map {
case StringLiteralV2(attributeDefStr, None) =>
stringFormatter.toSalsahGuiAttributeDefinition(
attributeDefStr,
throw InconsistentRepositoryDataException(
s"Invalid salsah-gui:guiAttributeDefinition in $guiElementIri: $attributeDefStr"
)
)
case other =>
throw InconsistentRepositoryDataException(
s"Invalid salsah-gui:guiAttributeDefinition in $guiElementIri: $other"
)
}.toSet
case None => Set.empty[SalsahGuiAttributeDefinition]
}
guiElementIri -> attributeDefs
}
}
/**
* Validates the GUI attributes of a resource class property.
*
* @param propertyInfoContent the property definition.
* @param allGuiAttributeDefinitions the GUI attribute definitions for each GUI element.
* @param errorFun a function that throws an exception. It will be passed the message to be included in the exception.
*/
def validateGuiAttributes(
propertyInfoContent: PropertyInfoContentV2,
allGuiAttributeDefinitions: Map[SmartIri, Set[SalsahGuiAttributeDefinition]],
errorFun: String => Nothing
)(implicit stringFormatter: StringFormatter): Unit = {
val propertyIri = propertyInfoContent.propertyIri
val predicates = propertyInfoContent.predicates
// Find out which salsah-gui:Guielement the property uses, if any.
val maybeGuiElementPred: Option[PredicateInfoV2] =
predicates.get(OntologyConstants.SalsahGui.GuiElementProp.toSmartIri)
val maybeGuiElementIri: Option[SmartIri] = maybeGuiElementPred.map(
_.requireIriObject(
throw InconsistentRepositoryDataException(
s"Property $propertyIri has an invalid object for ${OntologyConstants.SalsahGui.GuiElementProp}"
)
)
)
// Get that Guielement's attribute definitions, if any.
val guiAttributeDefs: Set[SalsahGuiAttributeDefinition] = maybeGuiElementIri match {
case Some(guiElementIri) =>
allGuiAttributeDefinitions.getOrElse(
guiElementIri,
errorFun(s"Property $propertyIri has salsah-gui:guiElement $guiElementIri, which doesn't exist")
)
case None => Set.empty[SalsahGuiAttributeDefinition]
}
// If the property has the predicate salsah-gui:guiAttribute, syntactically validate the objects of that predicate.
val guiAttributes: Set[SalsahGuiAttribute] =
predicates.get(OntologyConstants.SalsahGui.GuiAttribute.toSmartIri) match {
case Some(guiAttributePred) =>
val guiElementIri = maybeGuiElementIri.getOrElse(
errorFun(s"Property $propertyIri has salsah-gui:guiAttribute, but no salsah-gui:guiElement")
)
if (guiAttributeDefs.isEmpty) {
errorFun(
s"Property $propertyIri has salsah-gui:guiAttribute, but $guiElementIri has no salsah-gui:guiAttributeDefinition"
)
}
// Syntactically validate each attribute.
guiAttributePred.objects.map {
case StringLiteralV2(guiAttributeObj, None) =>
stringFormatter.toSalsahGuiAttribute(
s = guiAttributeObj,
attributeDefs = guiAttributeDefs,
errorFun =
errorFun(s"Property $propertyIri contains an invalid salsah-gui:guiAttribute: $guiAttributeObj")
)
case other =>
errorFun(s"Property $propertyIri contains an invalid salsah-gui:guiAttribute: $other")
}.toSet
case None => Set.empty[SalsahGuiAttribute]
}
// Check that all required GUI attributes are provided.
val requiredAttributeNames = guiAttributeDefs.filter(_.isRequired).map(_.attributeName)
val providedAttributeNames = guiAttributes.map(_.attributeName)
val missingAttributeNames: Set[String] = requiredAttributeNames -- providedAttributeNames
if (missingAttributeNames.nonEmpty) {
errorFun(
s"Property $propertyIri has one or more missing objects of salsah-gui:guiAttribute: ${missingAttributeNames
.mkString(", ")}"
)
}
}
/**
* Before creating a new class or adding cardinalities to an existing class, checks the validity of the
* cardinalities directly defined on the class. Adds link value properties for the corresponding
* link properties.
*
* @param internalClassDef the internal definition of the class.
* @param allBaseClassIris the IRIs of all the class's base classes, including the class itself.
* @param cacheData the ontology cache.
* @param existingLinkPropsToKeep the link properties that are already defined on the class and that
* will be kept after the update.
* @return the updated class definition, and the cardinalities resulting from inheritance.
*/
def checkCardinalitiesBeforeAddingAndIfNecessaryAddLinkValueProperties(
internalClassDef: ClassInfoContentV2,
allBaseClassIris: Set[SmartIri],
cacheData: OntologyCacheData,
existingLinkPropsToKeep: Set[SmartIri] = Set.empty
)(implicit stringFormatter: StringFormatter): (ClassInfoContentV2, Map[SmartIri, KnoraCardinalityInfo]) = {
// If the class has cardinalities, check that the properties are already defined as Knora properties.
val propertyDefsForDirectCardinalities: Set[ReadPropertyInfoV2] = internalClassDef.directCardinalities.keySet.map {
propertyIri =>
if (
!isKnoraResourceProperty(
propertyIri,
cacheData
) || propertyIri.toString == OntologyConstants.KnoraBase.ResourceProperty || propertyIri.toString == OntologyConstants.KnoraBase.HasValue
) {
throw NotFoundException(s"Invalid property for cardinality: <${propertyIri.toOntologySchema(ApiV2Complex)}>")
}
cacheData.ontologies(propertyIri.getOntologyFromEntity).properties(propertyIri)
}
val existingLinkValuePropsToKeep = existingLinkPropsToKeep.map(_.fromLinkPropToLinkValueProp)
val newLinkPropsInClass: Set[SmartIri] = propertyDefsForDirectCardinalities
.filter(_.isLinkProp)
.map(_.entityInfoContent.propertyIri) -- existingLinkPropsToKeep
val newLinkValuePropsInClass: Set[SmartIri] = propertyDefsForDirectCardinalities
.filter(_.isLinkValueProp)
.map(_.entityInfoContent.propertyIri) -- existingLinkValuePropsToKeep
// Don't allow link value prop cardinalities to be included in the request.
if (newLinkValuePropsInClass.nonEmpty) {
throw BadRequestException(
s"In class ${internalClassDef.classIri.toOntologySchema(ApiV2Complex)}, cardinalities have been submitted for one or more link value properties: ${newLinkValuePropsInClass
.map(_.toOntologySchema(ApiV2Complex))
.mkString(", ")}. Just submit the link properties, and the link value properties will be included automatically."
)
}
// Add a link value prop cardinality for each new link prop cardinality.
val linkValuePropCardinalitiesToAdd: Map[SmartIri, KnoraCardinalityInfo] = newLinkPropsInClass.map { linkPropIri =>
val linkValuePropIri = linkPropIri.fromLinkPropToLinkValueProp
// Ensure that the link value prop exists.
cacheData
.ontologies(linkValuePropIri.getOntologyFromEntity)
.properties
.getOrElse(linkValuePropIri, throw NotFoundException(s"Link value property <$linkValuePropIri> not found"))
linkValuePropIri -> internalClassDef.directCardinalities(linkPropIri)
}.toMap
val classDefWithAddedLinkValueProps: ClassInfoContentV2 = internalClassDef.copy(
directCardinalities = internalClassDef.directCardinalities ++ linkValuePropCardinalitiesToAdd
)
// Get the cardinalities that the class can inherit. If the ontology of the base class can't be found, it's assumed to be an external ontology (p.ex. foaf).
val cardinalitiesAvailableToInherit: Map[SmartIri, KnoraCardinalityInfo] =
classDefWithAddedLinkValueProps.subClassOf.flatMap { baseClassIri: SmartIri =>
val ontology = cacheData.ontologies.getOrElse(baseClassIri.getOntologyFromEntity, None)
ontology match {
case ontology: ReadOntologyV2 => ontology.classes(baseClassIri).allCardinalities
case _ => None
}
}.toMap
// Check that the cardinalities directly defined on the class are compatible with any inheritable
// cardinalities, and let directly-defined cardinalities override cardinalities in base classes.
val cardinalitiesForClassWithInheritance: Map[SmartIri, KnoraCardinalityInfo] = overrideCardinalities(
classIri = internalClassDef.classIri,
thisClassCardinalities = classDefWithAddedLinkValueProps.directCardinalities,
inheritableCardinalities = cardinalitiesAvailableToInherit,
allSubPropertyOfRelations = cacheData.subPropertyOfRelations,
errorSchema = ApiV2Complex,
errorFun = { msg: String =>
throw BadRequestException(msg)
}
)
// Check that the class is a subclass of all the classes that are subject class constraints of the Knora resource properties in its cardinalities.
val knoraResourcePropertyIrisInCardinalities = cardinalitiesForClassWithInheritance.keySet.filter { propertyIri =>
isKnoraResourceProperty(
propertyIri = propertyIri,
cacheData = cacheData
)
}
val allClassCardinalityKnoraPropertyDefs: Map[SmartIri, PropertyInfoContentV2] =
knoraResourcePropertyIrisInCardinalities.map { propertyIri =>
propertyIri -> cacheData.ontologies(propertyIri.getOntologyFromEntity).properties(propertyIri).entityInfoContent
}.toMap
checkSubjectClassConstraintsViaCardinalities(
internalClassDef = classDefWithAddedLinkValueProps,
allBaseClassIris = allBaseClassIris,