/
StandoffTagUtilV2.scala
1523 lines (1292 loc) · 75.4 KB
/
StandoffTagUtilV2.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-2018 the contributors (see Contributors.md).
*
* 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.messages.util.standoff
import java.time.Instant
import java.util.UUID
import akka.actor.ActorRef
import akka.event.LoggingAdapter
import akka.pattern.ask
import akka.util.Timeout
import org.knora.webapi.IRI
import org.knora.webapi.exceptions._
import org.knora.webapi.messages.IriConversions._
import org.knora.webapi.messages.admin.responder.usersmessages.UserADM
import org.knora.webapi.messages.store.triplestoremessages.{LiteralV2, SmartIriLiteralV2}
import org.knora.webapi.messages.util.DateUtilV1
import org.knora.webapi.messages.v1.responder.valuemessages.{
JulianDayNumberValueV1,
KnoraCalendarV1,
KnoraPrecisionV1,
UpdateValueV1
}
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._
import org.knora.webapi.messages.{OntologyConstants, SmartIri, StringFormatter}
import org.knora.webapi.settings.KnoraSettingsImpl
import scala.concurrent.{ExecutionContext, Future}
object StandoffTagUtilV2 {
// string constant used to mark the absence of an XML namespace in the mapping definitioon of an XML element
private val noNamespace = "noNamespace"
// string constant used to mark the absence of a classname in the mapping definition of an XML element
private val noClass = "noClass"
// name of class attribute (used to combine elements and classes in mappings)
private val classAttribute = "class"
// an internal Link in an XML document begins with this character
private val internalLinkMarker = '#'
// A fixed UUID for comparing standoff tags when their UUIDs are not significant.
private val fixedUuid = UUID.fromString("00000000-0000-0000-0000-000000000000")
/**
* Tries to find a data type attribute in the XML attributes of a given standoff node. Throws an appropriate error if information is inconsistent or missing.
*
* @param xmlToStandoffMapping the mapping from XML to standoff classes and properties for the given standoff node.
* @param dataType the expected data type of the given standoff node.
* @param standoffNodeFromXML the given standoff node.
* @return the value of the attribute.
*/
private def getDataTypeAttribute(xmlToStandoffMapping: XMLTagToStandoffClass,
dataType: StandoffDataTypeClasses.Value,
standoffNodeFromXML: StandoffTag): String = {
if (xmlToStandoffMapping.dataType.isEmpty || xmlToStandoffMapping.dataType.get.standoffDataTypeClass != dataType) {
throw BadRequestException(
s"no or wrong data type definition provided in mapping for standoff class ${xmlToStandoffMapping.standoffClassIri}")
}
val attrName = xmlToStandoffMapping.dataType.get.dataTypeXMLAttribute
val attrStringOption: Option[StandoffTagAttribute] =
standoffNodeFromXML.attributes.find(attr => attr.key == attrName)
if (attrStringOption.isEmpty) {
throw BadRequestException(s"required data type attribute '$attrName' could not be found for a $dataType value")
} else {
attrStringOption.get.value
}
}
/**
* Creates a sequence of [[StandoffTagAttributeV2]] for the given standoff node.
*
* @param xmlToStandoffMapping the mapping from XML to standoff classes and properties for the given standoff node.
* @param classSpecificProps the properties that may or have to be created (cardinalities) for the given standoff node.
* @param standoffNodeFromXML the given standoff node.
* @param standoffPropertyEntities the ontology information about the standoff properties.
* @return a sequence of [[StandoffTagAttributeV2]]
*/
private def createAttributes(
xmlToStandoffMapping: XMLTagToStandoffClass,
classSpecificProps: Map[SmartIri, KnoraCardinalityInfo],
existingXMLIDs: Seq[String],
standoffNodeFromXML: StandoffTag,
standoffPropertyEntities: Map[SmartIri, ReadPropertyInfoV2]): Seq[StandoffTagAttributeV2] = {
implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance
if (classSpecificProps.nonEmpty) {
// this standoff class requires additional standoff properties to the standoff data type properties (contained in `StandoffProperties.dataTypeProperties`).
// map over all non data type attributes, ignore the "class" attribute ("class" is only used in the mapping to allow for the reuse of the same tag name, not to store actual data).
val attrs: Seq[StandoffTagAttributeV2] = standoffNodeFromXML.attributes
.filterNot(attr =>
(xmlToStandoffMapping.dataType.nonEmpty && xmlToStandoffMapping.dataType.get.dataTypeXMLAttribute == attr.key) || attr.key == classAttribute)
.map { attr: StandoffTagAttribute =>
// get the standoff property IRI for this XML attribute
val xmlNamespace = attr.xmlNamespace match {
case None => noNamespace
case Some(namespace) => namespace
}
val standoffTagPropIri: SmartIri = xmlToStandoffMapping.attributesToProps
.getOrElse(
xmlNamespace,
throw BadRequestException(s"namespace $xmlNamespace unknown for attribute ${attr.key} in mapping"))
.getOrElse(attr.key, throw BadRequestException(s"mapping for attr '${attr.key}' not provided"))
.toSmartIri
val propPredicates: Map[SmartIri, PredicateInfoV2] =
standoffPropertyEntities(standoffTagPropIri).entityInfoContent.predicates
// check if a cardinality exists for the current attribute
if (!classSpecificProps.contains(standoffTagPropIri)) {
throw BadRequestException(s"no cardinality defined for attr '${attr.key}'")
}
if (propPredicates.contains(OntologyConstants.KnoraBase.ObjectDatatypeConstraint.toSmartIri)) {
// property is a data type property
val propDatatypeConstraint = propPredicates(OntologyConstants.KnoraBase.ObjectDatatypeConstraint.toSmartIri)
propDatatypeConstraint.objects.headOption match {
case Some(SmartIriLiteralV2(SmartIri(OntologyConstants.Xsd.String))) =>
StandoffTagStringAttributeV2(
standoffPropertyIri = standoffTagPropIri,
value = stringFormatter.toSparqlEncodedString(
attr.value,
throw BadRequestException(s"Invalid string attribute: '${attr.value}'"))
)
case Some(SmartIriLiteralV2(SmartIri(OntologyConstants.Xsd.Integer))) =>
StandoffTagIntegerAttributeV2(
standoffPropertyIri = standoffTagPropIri,
value = stringFormatter
.validateInt(attr.value, throw BadRequestException(s"Invalid integer attribute: '${attr.value}'"))
)
case Some(SmartIriLiteralV2(SmartIri(OntologyConstants.Xsd.Decimal))) =>
StandoffTagDecimalAttributeV2(
standoffPropertyIri = standoffTagPropIri,
value = stringFormatter.validateBigDecimal(
attr.value,
throw BadRequestException(s"Invalid decimal attribute: '${attr.value}'"))
)
case Some(SmartIriLiteralV2(SmartIri(OntologyConstants.Xsd.Boolean))) =>
StandoffTagBooleanAttributeV2(
standoffPropertyIri = standoffTagPropIri,
value = stringFormatter.validateBoolean(
attr.value,
throw BadRequestException(s"Invalid boolean attribute: '${attr.value}'"))
)
case Some(SmartIriLiteralV2(SmartIri(OntologyConstants.Xsd.DateTime))) =>
StandoffTagTimeAttributeV2(
standoffPropertyIri = standoffTagPropIri,
value = stringFormatter.xsdDateTimeStampToInstant(
attr.value,
throw BadRequestException(s"Invalid timestamp attribute: '${attr.value}'"))
)
case None =>
throw InconsistentRepositoryDataException(
s"did not find ${OntologyConstants.KnoraBase.ObjectDatatypeConstraint} for $standoffTagPropIri")
case other =>
throw InconsistentRepositoryDataException(
s"triplestore returned unknown ${OntologyConstants.KnoraBase.ObjectDatatypeConstraint} '$other' for $standoffTagPropIri")
}
} else {
// only properties with a `ObjectDatatypeConstraint` are allowed here (linking properties have to be created via data type standoff classes)
throw InconsistentRepositoryDataException(
s"no ${OntologyConstants.KnoraBase.ObjectDatatypeConstraint} given for property '$standoffTagPropIri'")
}
}
.toList
val attrsGroupedByPropIri: Map[SmartIri, Seq[StandoffTagAttributeV2]] =
attrs.groupBy(attr => attr.standoffPropertyIri)
// filter all the required props
val mustExistOnce: Set[SmartIri] = classSpecificProps.filter {
case (propIri, card) =>
card.cardinality == Cardinality.MustHaveOne || card.cardinality == Cardinality.MustHaveSome
}.keySet
// check if all the min cardinalities are respected
mustExistOnce.foreach { propIri =>
attrsGroupedByPropIri.get(propIri) match {
case Some(attrs: Seq[StandoffTagAttributeV2]) => ()
case None =>
throw BadRequestException(
s"the min cardinalities were not respected for the property $propIri (missing attribute for element ${standoffNodeFromXML.tagName})")
}
}
// filter all the props that have a limited occurrence
val mayExistOnce = classSpecificProps.filter {
case (propIri, card) =>
card.cardinality == Cardinality.MustHaveOne || card.cardinality == Cardinality.MayHaveOne
}.keySet
// check if all the max cardinalities are respected
mayExistOnce.foreach { propIri =>
attrsGroupedByPropIri.get(propIri) match {
case Some(attrs: Seq[StandoffTagAttributeV2]) =>
if (attrs.size > 1) {
throw BadRequestException(
s"the max cardinalities were not respected for $propIri (for element ${standoffNodeFromXML.tagName})")
}
case None => ()
}
}
attrs
} else {
// possibly data type properties are required, but no other standoff properties
// check that there no other attributes than data type attributes and 'class'
val unsupportedAttributes: Set[String] = standoffNodeFromXML.attributes
.filterNot { attr =>
(xmlToStandoffMapping.dataType.nonEmpty && xmlToStandoffMapping.dataType.get.dataTypeXMLAttribute == attr.key) || attr.key == classAttribute
}
.map(attr => attr.key)
if (unsupportedAttributes.nonEmpty)
throw BadRequestException(
s"Attributes found that are not defined in the mapping: ${unsupportedAttributes.mkString(", ")}")
Seq.empty[StandoffTagAttributeV2]
}
}
/**
* Represents a text with standoff markup including the mapping.
*
* @param text the text as a mere sequence of characters.
* @param language the language of the text, if known.
* @param standoffTagV2 the text's standoff markup.
*/
case class TextWithStandoffTagsV2(text: String,
language: Option[String] = None,
standoffTagV2: Seq[StandoffTagV2],
mapping: GetMappingResponseV2)
/**
* Converts XML to a [[TextWithStandoffTagsV2]].
*
* @param xml the XML representing text with markup.
* @param mapping the mapping used to convert XML to standoff.
* @param acceptStandoffLinksToClientIDs if `true`, allow standoff link tags to use the client's IDs for target
* resources. In a bulk import, this allows standoff links to resources
* that are to be created by the import.
* @return a [[TextWithStandoffTagsV2]].
*/
def convertXMLtoStandoffTagV2(xml: String,
mapping: GetMappingResponseV2,
acceptStandoffLinksToClientIDs: Boolean,
log: LoggingAdapter): TextWithStandoffTagsV2 = {
// collect all the `XMLTag` from the given mapping that require a separator
// and create a `XMLTagSeparatorRequired` for each of them
//
// namespace = Map("myXMLNamespace" -> Map("myXMLTagName" -> Map("myXMLClassname" -> XMLTag(...))))
val elementsSeparatorRequired: Vector[XMLTagSeparatorRequired] = mapping.mapping.namespace.flatMap {
case (namespace: String, elesForNamespace: Map[String, Map[String, XMLTag]]) =>
elesForNamespace.flatMap {
case (tagname: String, classWithTag: Map[String, XMLTag]) =>
val tagsWithSeparator: Iterable[XMLTagSeparatorRequired] = classWithTag
.filter {
// filter out all `XMLTag` that require a separator
case (classname: String, tag: XMLTag) =>
tag.separatorRequired
}
.map {
case (classname: String, tag: XMLTag) =>
// create a `XMLTagSeparatorRequired` with the current's element
// namespace and class, if any
XMLTagSeparatorRequired(
maybeNamespace = namespace match {
// check for namespace
case `noNamespace` => None
case nspace: String => Some(nspace)
},
tagname = tag.name,
maybeClassname = classname match {
// check for classname
case `noClass` => None
case clname: String => Some(clname)
}
)
}
tagsWithSeparator
}
}.toVector
val xmlStandoffUtil = new XMLToStandoffUtil()
val textWithStandoff: TextWithStandoff = xmlStandoffUtil.xml2TextWithStandoff(xml, elementsSeparatorRequired, log)
val standoffTagsV2: Seq[StandoffTagV2] = convertXMLStandoffTagToStandoffTagV2(
textWithStandoff = textWithStandoff,
mappingXMLtoStandoff = mapping.mapping,
standoffEntities = mapping.standoffEntities,
acceptStandoffLinksToClientIDs = acceptStandoffLinksToClientIDs
)
TextWithStandoffTagsV2(
text = textWithStandoff.text,
standoffTagV2 = standoffTagsV2,
mapping = mapping
)
}
/**
*
* Turns a sequence of [[StandoffTag]] returned by [[XMLToStandoffUtil.xml2TextWithStandoff]] into a sequence of [[StandoffTagV2]].
* This method handles the creation of data type specific properties (e.g. for a date value) on the basis of the provided mapping.
*
* @param textWithStandoff sequence of [[StandoffTag]] returned by [[XMLToStandoffUtil.xml2TextWithStandoff]].
* @param mappingXMLtoStandoff the mapping to be used.
* @param standoffEntities the standoff entities (classes and properties) to be used.
* @param acceptStandoffLinksToClientIDs if `true`, allow standoff link tags to use the client's IDs for target
* resources. In a bulk import, this allows standoff links to resources
* that are to be created by the import.
* @return a sequence of [[StandoffTagV2]].
*/
private def convertXMLStandoffTagToStandoffTagV2(textWithStandoff: TextWithStandoff,
mappingXMLtoStandoff: MappingXMLtoStandoff,
standoffEntities: StandoffEntityInfoGetResponseV2,
acceptStandoffLinksToClientIDs: Boolean): Seq[StandoffTagV2] = {
implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance
// collect al the existing ids from the standoff tags
val existingXMLIDs: Seq[String] =
textWithStandoff.standoff.filter((standoffTag: StandoffTag) => standoffTag.originalID.isDefined).map {
standoffTagWithID =>
standoffTagWithID.originalID.get
}
// get the id of an XML target element from an internal reference
// assumes that an internal references starts with a "#"
def getTargetIDFromInternalReference(internalReference: String): String = {
// make sure that the internal reference starts with a '#'
if (internalReference.charAt(0) != internalLinkMarker)
throw BadRequestException(
s"invalid internal reference (should start with a $internalLinkMarker): '$internalReference'")
val refTarget = internalReference.substring(1)
// make sure that he target of the reference exists in this context
if (!existingXMLIDs.contains(refTarget))
throw BadRequestException(s"invalid internal reference: target '$internalReference' unknown")
refTarget
}
textWithStandoff.standoff.map { standoffNodeFromXML: StandoffTag =>
val xmlNamespace = standoffNodeFromXML.xmlNamespace match {
case None => noNamespace
case Some(namespace) => namespace
}
val classname: String = standoffNodeFromXML.attributes.find(_.key == classAttribute) match {
case None => noClass
case Some(classAttribute: StandoffTagAttribute) => classAttribute.value
}
// get the mapping corresponding to the given namespace and tagname
val standoffDefFromMapping = mappingXMLtoStandoff.namespace
.getOrElse(xmlNamespace, throw BadRequestException(s"namespace $xmlNamespace not defined in mapping"))
.getOrElse(
standoffNodeFromXML.tagName,
throw BadRequestException(
s"the standoff class for the tag '${standoffNodeFromXML.tagName}' could not be found in the provided mapping")
)
.getOrElse(
classname,
throw BadRequestException(
s"the standoff class for the classname $classname in combination with the tag '${standoffNodeFromXML.tagName}' could not be found in the provided mapping")
)
.mapping
val standoffClassIri: SmartIri = standoffDefFromMapping.standoffClassIri.toSmartIri
// get the cardinalities of the current standoff class
val cardinalities: Map[SmartIri, KnoraCardinalityInfo] = standoffEntities.standoffClassInfoMap
.getOrElse(
standoffClassIri,
throw NotFoundException(s"information about standoff class $standoffClassIri was not found in ontology"))
.allCardinalities
// create a standoff base tag with the information available from standoff util
val standoffBaseTagV2: StandoffTagV2 = standoffNodeFromXML match {
case hierarchicalStandoffTag: HierarchicalStandoffTag =>
StandoffTagV2(
standoffTagClassIri = standoffClassIri,
startPosition = hierarchicalStandoffTag.startPosition,
endPosition = hierarchicalStandoffTag.endPosition,
uuid = hierarchicalStandoffTag.uuid,
originalXMLID = hierarchicalStandoffTag.originalID match {
case Some(id: String) =>
Some(
stringFormatter.toSparqlEncodedString(
id,
throw BadRequestException(s"XML id $id cannot be converted to a Sparql conform string")))
case None => None
},
startIndex = hierarchicalStandoffTag.index,
endIndex = None,
startParentIndex = hierarchicalStandoffTag.parentIndex,
endParentIndex = None,
attributes = Seq.empty[StandoffTagAttributeV2]
)
case freeStandoffTag: FreeStandoffTag =>
StandoffTagV2(
standoffTagClassIri = standoffClassIri,
startPosition = freeStandoffTag.startPosition,
endPosition = freeStandoffTag.endPosition,
uuid = freeStandoffTag.uuid,
originalXMLID = freeStandoffTag.originalID match {
case Some(id: String) =>
Some(
stringFormatter.toSparqlEncodedString(
id,
throw BadRequestException(s"XML id $id cannot be converted to a Sparql conform string")))
case None => None
},
startIndex = freeStandoffTag.startIndex,
endIndex = Some(freeStandoffTag.endIndex),
startParentIndex = freeStandoffTag.startParentIndex,
endParentIndex = freeStandoffTag.endParentIndex,
attributes = Seq.empty[StandoffTagAttributeV2]
)
case _ =>
throw InvalidStandoffException(
"StandoffUtil did neither return a HierarchicalStandoff tag nor a FreeStandoffTag")
}
// check the data type of the given standoff class
standoffEntities.standoffClassInfoMap(standoffClassIri).standoffDataType match {
case Some(StandoffDataTypeClasses.StandoffLinkTag) =>
val linkString: String =
getDataTypeAttribute(standoffDefFromMapping, StandoffDataTypeClasses.StandoffLinkTag, standoffNodeFromXML)
val internalLink: StandoffTagAttributeV2 = StandoffTagIriAttributeV2(
standoffPropertyIri = OntologyConstants.KnoraBase.StandoffTagHasLink.toSmartIri,
value = stringFormatter.validateStandoffLinkResourceReference(
linkString,
acceptStandoffLinksToClientIDs,
throw BadRequestException(s"Invalid standoff resource reference: $linkString"))
)
val classSpecificProps = cardinalities -- StandoffProperties.systemProperties.map(_.toSmartIri) -- StandoffProperties.linkProperties
.map(_.toSmartIri)
val attributesV2: Seq[StandoffTagAttributeV2] = createAttributes(standoffDefFromMapping,
classSpecificProps,
existingXMLIDs,
standoffNodeFromXML,
standoffEntities.standoffPropertyInfoMap)
StandoffTagV2(
dataType = Some(StandoffDataTypeClasses.StandoffLinkTag),
standoffTagClassIri = standoffBaseTagV2.standoffTagClassIri,
startPosition = standoffBaseTagV2.startPosition,
endPosition = standoffBaseTagV2.endPosition,
uuid = standoffBaseTagV2.uuid,
originalXMLID = standoffBaseTagV2.originalXMLID,
startIndex = standoffBaseTagV2.startIndex,
endIndex = standoffBaseTagV2.endIndex,
startParentIndex = standoffBaseTagV2.startParentIndex,
endParentIndex = standoffBaseTagV2.endParentIndex,
attributes = attributesV2 :+ internalLink
)
case Some(StandoffDataTypeClasses.StandoffInternalReferenceTag) =>
val internalReferenceString: String =
getDataTypeAttribute(standoffDefFromMapping,
StandoffDataTypeClasses.StandoffInternalReferenceTag,
standoffNodeFromXML)
val internalReference = StandoffTagInternalReferenceAttributeV2(
standoffPropertyIri = OntologyConstants.KnoraBase.StandoffTagHasInternalReference.toSmartIri,
value = getTargetIDFromInternalReference(internalReferenceString)
)
val classSpecificProps = cardinalities -- StandoffProperties.systemProperties.map(_.toSmartIri) -- StandoffProperties.internalReferenceProperties
.map(_.toSmartIri)
val attributesV2: Seq[StandoffTagAttributeV2] = createAttributes(standoffDefFromMapping,
classSpecificProps,
existingXMLIDs,
standoffNodeFromXML,
standoffEntities.standoffPropertyInfoMap)
StandoffTagV2(
dataType = Some(StandoffDataTypeClasses.StandoffInternalReferenceTag),
standoffTagClassIri = standoffBaseTagV2.standoffTagClassIri,
startPosition = standoffBaseTagV2.startPosition,
endPosition = standoffBaseTagV2.endPosition,
uuid = standoffBaseTagV2.uuid,
originalXMLID = standoffBaseTagV2.originalXMLID,
startIndex = standoffBaseTagV2.startIndex,
endIndex = standoffBaseTagV2.endIndex,
startParentIndex = standoffBaseTagV2.startParentIndex,
endParentIndex = standoffBaseTagV2.endParentIndex,
attributes = attributesV2 :+ internalReference
)
case Some(StandoffDataTypeClasses.StandoffColorTag) =>
val colorString: String =
getDataTypeAttribute(standoffDefFromMapping, StandoffDataTypeClasses.StandoffColorTag, standoffNodeFromXML)
val colorValue = StandoffTagStringAttributeV2(
standoffPropertyIri = OntologyConstants.KnoraBase.ValueHasColor.toSmartIri,
value =
stringFormatter.validateColor(colorString, throw BadRequestException(s"Color invalid: $colorString"))
)
val classSpecificProps = cardinalities -- StandoffProperties.systemProperties.map(_.toSmartIri) -- StandoffProperties.colorProperties
.map(_.toSmartIri)
val attributesV2: Seq[StandoffTagAttributeV2] = createAttributes(standoffDefFromMapping,
classSpecificProps,
existingXMLIDs,
standoffNodeFromXML,
standoffEntities.standoffPropertyInfoMap)
StandoffTagV2(
dataType = Some(StandoffDataTypeClasses.StandoffColorTag),
standoffTagClassIri = standoffBaseTagV2.standoffTagClassIri,
startPosition = standoffBaseTagV2.startPosition,
endPosition = standoffBaseTagV2.endPosition,
uuid = standoffBaseTagV2.uuid,
originalXMLID = standoffBaseTagV2.originalXMLID,
startIndex = standoffBaseTagV2.startIndex,
endIndex = standoffBaseTagV2.endIndex,
startParentIndex = standoffBaseTagV2.startParentIndex,
endParentIndex = standoffBaseTagV2.endParentIndex,
attributes = attributesV2 :+ colorValue
)
case Some(StandoffDataTypeClasses.StandoffUriTag) =>
val uriString: String =
getDataTypeAttribute(standoffDefFromMapping, StandoffDataTypeClasses.StandoffUriTag, standoffNodeFromXML)
val uriValue = StandoffTagUriAttributeV2(
standoffPropertyIri = OntologyConstants.KnoraBase.ValueHasUri.toSmartIri,
value =
stringFormatter.validateAndEscapeIri(uriString, throw BadRequestException(s"URI invalid: $uriString"))
)
val classSpecificProps = cardinalities -- StandoffProperties.systemProperties.map(_.toSmartIri) -- StandoffProperties.uriProperties
.map(_.toSmartIri)
val attributesV2: Seq[StandoffTagAttributeV2] = createAttributes(standoffDefFromMapping,
classSpecificProps,
existingXMLIDs,
standoffNodeFromXML,
standoffEntities.standoffPropertyInfoMap)
StandoffTagV2(
dataType = Some(StandoffDataTypeClasses.StandoffUriTag),
standoffTagClassIri = standoffBaseTagV2.standoffTagClassIri,
startPosition = standoffBaseTagV2.startPosition,
endPosition = standoffBaseTagV2.endPosition,
uuid = standoffBaseTagV2.uuid,
originalXMLID = standoffBaseTagV2.originalXMLID,
startIndex = standoffBaseTagV2.startIndex,
endIndex = standoffBaseTagV2.endIndex,
startParentIndex = standoffBaseTagV2.startParentIndex,
endParentIndex = standoffBaseTagV2.endParentIndex,
attributes = attributesV2 :+ uriValue
)
case Some(StandoffDataTypeClasses.StandoffIntegerTag) =>
val integerString: String = getDataTypeAttribute(standoffDefFromMapping,
StandoffDataTypeClasses.StandoffIntegerTag,
standoffNodeFromXML)
val integerValue = StandoffTagIntegerAttributeV2(
standoffPropertyIri = OntologyConstants.KnoraBase.ValueHasInteger.toSmartIri,
value = stringFormatter.validateInt(integerString,
throw BadRequestException(s"Integer value invalid: $integerString"))
)
val classSpecificProps = cardinalities -- StandoffProperties.systemProperties.map(_.toSmartIri) -- StandoffProperties.integerProperties
.map(_.toSmartIri)
val attributesV2: Seq[StandoffTagAttributeV2] = createAttributes(standoffDefFromMapping,
classSpecificProps,
existingXMLIDs,
standoffNodeFromXML,
standoffEntities.standoffPropertyInfoMap)
StandoffTagV2(
dataType = Some(StandoffDataTypeClasses.StandoffIntegerTag),
standoffTagClassIri = standoffBaseTagV2.standoffTagClassIri,
startPosition = standoffBaseTagV2.startPosition,
endPosition = standoffBaseTagV2.endPosition,
uuid = standoffBaseTagV2.uuid,
originalXMLID = standoffBaseTagV2.originalXMLID,
startIndex = standoffBaseTagV2.startIndex,
endIndex = standoffBaseTagV2.endIndex,
startParentIndex = standoffBaseTagV2.startParentIndex,
endParentIndex = standoffBaseTagV2.endParentIndex,
attributes = attributesV2 :+ integerValue
)
case Some(StandoffDataTypeClasses.StandoffDecimalTag) =>
val decimalString: String = getDataTypeAttribute(standoffDefFromMapping,
StandoffDataTypeClasses.StandoffDecimalTag,
standoffNodeFromXML)
val decimalValue = StandoffTagDecimalAttributeV2(
standoffPropertyIri = OntologyConstants.KnoraBase.ValueHasDecimal.toSmartIri,
value =
stringFormatter.validateBigDecimal(decimalString,
throw BadRequestException(s"Decimal value invalid: $decimalString"))
)
val classSpecificProps = cardinalities -- StandoffProperties.systemProperties.map(_.toSmartIri) -- StandoffProperties.decimalProperties
.map(_.toSmartIri)
val attributesV2: Seq[StandoffTagAttributeV2] = createAttributes(standoffDefFromMapping,
classSpecificProps,
existingXMLIDs,
standoffNodeFromXML,
standoffEntities.standoffPropertyInfoMap)
StandoffTagV2(
dataType = Some(StandoffDataTypeClasses.StandoffDecimalTag),
standoffTagClassIri = standoffBaseTagV2.standoffTagClassIri,
startPosition = standoffBaseTagV2.startPosition,
endPosition = standoffBaseTagV2.endPosition,
uuid = standoffBaseTagV2.uuid,
originalXMLID = standoffBaseTagV2.originalXMLID,
startIndex = standoffBaseTagV2.startIndex,
endIndex = standoffBaseTagV2.endIndex,
startParentIndex = standoffBaseTagV2.startParentIndex,
endParentIndex = standoffBaseTagV2.endParentIndex,
attributes = attributesV2 :+ decimalValue
)
case Some(StandoffDataTypeClasses.StandoffBooleanTag) =>
val booleanString: String = getDataTypeAttribute(standoffDefFromMapping,
StandoffDataTypeClasses.StandoffBooleanTag,
standoffNodeFromXML)
val booleanValue = StandoffTagBooleanAttributeV2(
standoffPropertyIri = OntologyConstants.KnoraBase.ValueHasBoolean.toSmartIri,
value = stringFormatter.validateBoolean(booleanString,
throw BadRequestException(s"Boolean value invalid: $booleanString"))
)
val classSpecificProps = cardinalities -- StandoffProperties.systemProperties.map(_.toSmartIri) -- StandoffProperties.booleanProperties
.map(_.toSmartIri)
val attributesV2: Seq[StandoffTagAttributeV2] = createAttributes(standoffDefFromMapping,
classSpecificProps,
existingXMLIDs,
standoffNodeFromXML,
standoffEntities.standoffPropertyInfoMap)
StandoffTagV2(
dataType = Some(StandoffDataTypeClasses.StandoffBooleanTag),
standoffTagClassIri = standoffBaseTagV2.standoffTagClassIri,
startPosition = standoffBaseTagV2.startPosition,
endPosition = standoffBaseTagV2.endPosition,
uuid = standoffBaseTagV2.uuid,
originalXMLID = standoffBaseTagV2.originalXMLID,
startIndex = standoffBaseTagV2.startIndex,
endIndex = standoffBaseTagV2.endIndex,
startParentIndex = standoffBaseTagV2.startParentIndex,
endParentIndex = standoffBaseTagV2.endParentIndex,
attributes = attributesV2 :+ booleanValue
)
case Some(StandoffDataTypeClasses.StandoffIntervalTag) =>
val intervalString: String = getDataTypeAttribute(standoffDefFromMapping,
StandoffDataTypeClasses.StandoffIntervalTag,
standoffNodeFromXML)
// interval String contains two decimals separated by a comma
val interval: Array[String] = intervalString.split(",")
if (interval.length != 2) {
throw BadRequestException(
s"interval string $intervalString is invalid, it should contain two decimals separated by a comma")
}
val intervalStart = StandoffTagDecimalAttributeV2(
standoffPropertyIri = OntologyConstants.KnoraBase.ValueHasIntervalStart.toSmartIri,
value =
stringFormatter.validateBigDecimal(interval(0),
throw BadRequestException(s"Decimal value invalid: ${interval(0)}"))
)
val intervalEnd = StandoffTagDecimalAttributeV2(
standoffPropertyIri = OntologyConstants.KnoraBase.ValueHasIntervalEnd.toSmartIri,
value =
stringFormatter.validateBigDecimal(interval(1),
throw BadRequestException(s"Decimal value invalid: ${interval(1)}"))
)
val classSpecificProps = cardinalities -- StandoffProperties.systemProperties.map(_.toSmartIri) -- StandoffProperties.intervalProperties
.map(_.toSmartIri)
val attributesV2: Seq[StandoffTagAttributeV2] = createAttributes(standoffDefFromMapping,
classSpecificProps,
existingXMLIDs,
standoffNodeFromXML,
standoffEntities.standoffPropertyInfoMap)
StandoffTagV2(
dataType = Some(StandoffDataTypeClasses.StandoffIntervalTag),
standoffTagClassIri = standoffBaseTagV2.standoffTagClassIri,
startPosition = standoffBaseTagV2.startPosition,
endPosition = standoffBaseTagV2.endPosition,
uuid = standoffBaseTagV2.uuid,
originalXMLID = standoffBaseTagV2.originalXMLID,
startIndex = standoffBaseTagV2.startIndex,
endIndex = standoffBaseTagV2.endIndex,
startParentIndex = standoffBaseTagV2.startParentIndex,
endParentIndex = standoffBaseTagV2.endParentIndex,
attributes = attributesV2 ++ List(intervalStart, intervalEnd)
)
case Some(StandoffDataTypeClasses.StandoffTimeTag) =>
val timeStampString: String =
getDataTypeAttribute(standoffDefFromMapping, StandoffDataTypeClasses.StandoffTimeTag, standoffNodeFromXML)
val timeStamp: Instant =
stringFormatter.xsdDateTimeStampToInstant(timeStampString,
throw BadRequestException(s"Invalid timestamp: $timeStampString"))
val timeStampAttr = StandoffTagTimeAttributeV2(standoffPropertyIri =
OntologyConstants.KnoraBase.ValueHasTimeStamp.toSmartIri,
value = timeStamp)
val classSpecificProps = cardinalities -- StandoffProperties.systemProperties.map(_.toSmartIri) -- StandoffProperties.timeProperties
.map(_.toSmartIri)
val attributesV2: Seq[StandoffTagAttributeV2] = createAttributes(standoffDefFromMapping,
classSpecificProps,
existingXMLIDs,
standoffNodeFromXML,
standoffEntities.standoffPropertyInfoMap)
StandoffTagV2(
dataType = Some(StandoffDataTypeClasses.StandoffTimeTag),
standoffTagClassIri = standoffBaseTagV2.standoffTagClassIri,
startPosition = standoffBaseTagV2.startPosition,
endPosition = standoffBaseTagV2.endPosition,
uuid = standoffBaseTagV2.uuid,
originalXMLID = standoffBaseTagV2.originalXMLID,
startIndex = standoffBaseTagV2.startIndex,
endIndex = standoffBaseTagV2.endIndex,
startParentIndex = standoffBaseTagV2.startParentIndex,
endParentIndex = standoffBaseTagV2.endParentIndex,
attributes = attributesV2 :+ timeStampAttr
)
case Some(StandoffDataTypeClasses.StandoffDateTag) =>
val dateString: String =
getDataTypeAttribute(standoffDefFromMapping, StandoffDataTypeClasses.StandoffDateTag, standoffNodeFromXML)
val dateValue = DateUtilV1.createJDNValueV1FromDateString(dateString)
val dateCalendar = StandoffTagStringAttributeV2(standoffPropertyIri =
OntologyConstants.KnoraBase.ValueHasCalendar.toSmartIri,
value = dateValue.calendar.toString)
val dateStart = StandoffTagIntegerAttributeV2(standoffPropertyIri =
OntologyConstants.KnoraBase.ValueHasStartJDN.toSmartIri,
value = dateValue.dateval1)
val dateEnd = StandoffTagIntegerAttributeV2(standoffPropertyIri =
OntologyConstants.KnoraBase.ValueHasEndJDN.toSmartIri,
value = dateValue.dateval2)
val dateStartPrecision =
StandoffTagStringAttributeV2(standoffPropertyIri =
OntologyConstants.KnoraBase.ValueHasStartPrecision.toSmartIri,
value = dateValue.dateprecision1.toString)
val dateEndPrecision =
StandoffTagStringAttributeV2(standoffPropertyIri =
OntologyConstants.KnoraBase.ValueHasEndPrecision.toSmartIri,
value = dateValue.dateprecision2.toString)
val classSpecificProps = cardinalities -- StandoffProperties.systemProperties.map(_.toSmartIri) -- StandoffProperties.dateProperties
.map(_.toSmartIri)
val attributesV2: Seq[StandoffTagAttributeV2] = createAttributes(standoffDefFromMapping,
classSpecificProps,
existingXMLIDs,
standoffNodeFromXML,
standoffEntities.standoffPropertyInfoMap)
StandoffTagV2(
dataType = Some(StandoffDataTypeClasses.StandoffDateTag),
standoffTagClassIri = standoffBaseTagV2.standoffTagClassIri,
startPosition = standoffBaseTagV2.startPosition,
endPosition = standoffBaseTagV2.endPosition,
uuid = standoffBaseTagV2.uuid,
originalXMLID = standoffBaseTagV2.originalXMLID,
startIndex = standoffBaseTagV2.startIndex,
endIndex = standoffBaseTagV2.endIndex,
startParentIndex = standoffBaseTagV2.startParentIndex,
endParentIndex = standoffBaseTagV2.endParentIndex,
attributes = attributesV2 ++ List(dateCalendar, dateStart, dateEnd, dateStartPrecision, dateEndPrecision)
)
case None =>
// ignore the system properties since they are provided by StandoffUtil
val classSpecificProps
: Map[SmartIri, KnoraCardinalityInfo] = cardinalities -- StandoffProperties.systemProperties.map(
_.toSmartIri)
val attributesV2: Seq[StandoffTagAttributeV2] = createAttributes(standoffDefFromMapping,
classSpecificProps,
existingXMLIDs,
standoffNodeFromXML,
standoffEntities.standoffPropertyInfoMap)
standoffBaseTagV2.copy(
attributes = attributesV2
)
case unknownDataType =>
throw InconsistentRepositoryDataException(
s"the triplestore returned the data type $unknownDataType for $standoffClassIri that could be handled")
}
}
}
// maps a standoff class to an XML tag with attributes
case class XMLTagItem(namespace: String,
tagname: String,
classname: String,
tagItem: XMLTag,
attributes: Map[IRI, XMLAttrItem])
// maps a standoff property to XML attributes
case class XMLAttrItem(namespace: String, attrname: String)
/**
* Inverts a [[MappingXMLtoStandoff]] and makes standoff class Iris keys.
* This is makes it easier to map standoff classes back to XML tags (recreating XML from standoff).
*
* This method also checks for duplicate usage of standoff classes and properties in the attribute mapping of a tag.
*
* @param mappingXMLtoStandoff mapping from XML to standoff.
* @return a Map standoff class Iris to [[XMLTagItem]].
*/
def invertXMLToStandoffMapping(mappingXMLtoStandoff: MappingXMLtoStandoff): Map[IRI, XMLTagItem] = {
// check for duplicate standoff class Iris
val classIris: Iterable[IRI] = mappingXMLtoStandoff.namespace.values.flatten.flatMap {
case (tagname: String, tagItem: Map[String, XMLTag]) =>
tagItem.values.map(_.mapping.standoffClassIri)
}
// check for duplicate standoff class Iris
if (classIris.size != classIris.toSet.size) {
throw BadRequestException("the same standoff class IRI is used more than once in the mapping")
}
mappingXMLtoStandoff.namespace.flatMap {
case (tagNamespace: String, tagMapping: Map[String, Map[String, XMLTag]]) =>
tagMapping.flatMap {
case (tagname: String, classnameMapping: Map[String, XMLTag]) =>
classnameMapping.map {
case (classname: String, tagItem: XMLTag) =>
// collect all the property Iris defined in the attributes for the current tag
// over all namespaces
val propIris: Iterable[IRI] = tagItem.mapping.attributesToProps.values.flatten.map {
case (attrName, propIri) =>
propIri
}
// check for duplicate property Iris
if (propIris.size != propIris.toSet.size) {
throw BadRequestException(
s"the same property IRI is used more than once for the attributes mapping for tag $tagname")
}
// inverts the mapping and makes standoff property Iris keys (for attributes)
// this is makes it easier to map standoff properties back to XML attributes
val attrItems: Map[IRI, XMLAttrItem] = tagItem.mapping.attributesToProps.flatMap {
case (attrNamespace: String, attrMappings: Map[String, IRI]) =>
attrMappings.map {
case (attrName, propIri) =>
propIri -> XMLAttrItem(attrNamespace, attrName)
}
}
// standoff class IRI -> XMLTagItem(... attributes -> attrItems)
tagItem.mapping.standoffClassIri -> XMLTagItem(namespace = tagNamespace,
tagname = tagname,
classname = classname,
tagItem = tagItem,
attributes = attrItems)
}
}
}
}
/**
* Creates a sequence of [[StandoffTagV2]] from the given standoff nodes resulting from a SPARQL CONSTRUCT query.
*
* @param standoffAssertions standoff assertions to be converted into [[StandoffTagV2]] objects.
* @return a sequence of [[StandoffTagV2]] objects.
*/
def createStandoffTagsV2FromConstructResults(standoffAssertions: Map[IRI, Map[SmartIri, LiteralV2]],
responderManager: ActorRef,
requestingUser: UserADM)(
implicit timeout: Timeout,
executionContext: ExecutionContext): Future[Vector[StandoffTagV2]] = {
val unwrappedStandoffAssertions: Map[IRI, Map[IRI, String]] = standoffAssertions.map {
case (standoffTagIri, standoffTagAssertions: Map[SmartIri, LiteralV2]) =>
standoffTagIri -> standoffTagAssertions.map {
case (predicateIri: SmartIri, literal: LiteralV2) => predicateIri.toString -> literal.toString
}
}
createStandoffTagsV2FromSelectResults(
standoffAssertions = unwrappedStandoffAssertions,
responderManager = responderManager,
requestingUser = requestingUser
)
}
/**
* Creates a sequence of [[StandoffTagV2]] from the given standoff nodes resulting from a SPARQL SELECT query.
*
* @param standoffAssertions standoff assertions to be converted into [[StandoffTagV2]] objects.
* @return a sequence of [[StandoffTagV2]] objects.
*/
def createStandoffTagsV2FromSelectResults(standoffAssertions: Map[IRI, Map[IRI, String]],
responderManager: ActorRef,
requestingUser: UserADM)(
implicit timeout: Timeout,
executionContext: ExecutionContext): Future[Vector[StandoffTagV2]] = {
implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance
val standoffClassIris: Set[SmartIri] = standoffAssertions.map {
case (standoffTagIri: IRI, standoffTagAssertions: Map[IRI, String]) =>
standoffTagAssertions(OntologyConstants.Rdf.Type).toSmartIri
}.toSet
val standoffPropertyIris: Set[SmartIri] = standoffAssertions.flatMap {
case (standoffTagIri: IRI, standoffTagAssertions: Map[IRI, String]) =>
(standoffTagAssertions.keySet - OntologyConstants.Rdf.Type).map(_.toSmartIri)
}.toSet
for {
standoffEntities: StandoffEntityInfoGetResponseV2 <- (responderManager ? StandoffEntityInfoGetRequestV2(
standoffClassIris = standoffClassIris,
standoffPropertyIris = standoffPropertyIris,
requestingUser = requestingUser)).mapTo[StandoffEntityInfoGetResponseV2]
standoffTags = standoffAssertions
.map {