/
ResourcesRouteV1.scala
1640 lines (1434 loc) · 77.3 KB
/
ResourcesRouteV1.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.routing.v1
import akka.http.scaladsl.model._
import akka.http.scaladsl.model.headers._
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
import akka.http.scaladsl.util.FastFuture
import akka.pattern._
import org.w3c.dom.ls.LSInput
import org.w3c.dom.ls.LSResourceResolver
import org.xml.sax.SAXException
import java.io._
import java.nio.charset.StandardCharsets
import java.time.Instant
import java.util.UUID
import javax.xml.XMLConstants
import javax.xml.transform.stream.StreamSource
import javax.xml.validation.Schema
import javax.xml.validation.SchemaFactory
import javax.xml.validation.Validator
import scala.collection.immutable
import scala.concurrent.Future
import scala.util.Failure
import scala.util.Success
import scala.util.Try
import scala.xml._
import dsp.errors.AssertionException
import dsp.errors.BadRequestException
import dsp.errors.ForbiddenException
import dsp.errors.InconsistentRepositoryDataException
import org.knora.webapi._
import org.knora.webapi.messages.IriConversions._
import org.knora.webapi.messages.OntologyConstants
import org.knora.webapi.messages.SmartIri
import org.knora.webapi.messages.StringFormatter.XmlImportNamespaceInfoV1
import org.knora.webapi.messages.admin.responder.projectsmessages.ProjectGetRequestADM
import org.knora.webapi.messages.admin.responder.projectsmessages.ProjectGetResponseADM
import org.knora.webapi.messages.admin.responder.projectsmessages.ProjectIdentifierADM
import org.knora.webapi.messages.admin.responder.usersmessages.UserADM
import org.knora.webapi.messages.store.sipimessages.GetFileMetadataRequest
import org.knora.webapi.messages.store.sipimessages.GetFileMetadataResponse
import org.knora.webapi.messages.twirl.ResourceHtmlView
import org.knora.webapi.messages.util.DateUtilV1
import org.knora.webapi.messages.util.standoff.StandoffTagUtilV2.TextWithStandoffTagsV2
import org.knora.webapi.messages.v1.responder.ontologymessages._
import org.knora.webapi.messages.v1.responder.resourcemessages.ResourceV1JsonProtocol._
import org.knora.webapi.messages.v1.responder.resourcemessages._
import org.knora.webapi.messages.v1.responder.valuemessages._
import org.knora.webapi.routing.Authenticator
import org.knora.webapi.routing.KnoraRoute
import org.knora.webapi.routing.KnoraRouteData
import org.knora.webapi.routing.RouteUtilV1
import org.knora.webapi.util.ActorUtil
import org.knora.webapi.util.FileUtil
/**
* Provides API routes that deal with resources.
*/
class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) with Authenticator {
// A scala.xml.PrettyPrinter for formatting generated XML import schemas.
private val xmlPrettyPrinter = new scala.xml.PrettyPrinter(width = 160, step = 4)
/**
* Returns the route.
*/
override def makeRoute(): Route = {
def makeResourceRequestMessage(
resIri: String,
resinfo: Boolean,
requestType: String,
userADM: UserADM
): ResourcesResponderRequestV1 = {
val validResIri =
stringFormatter.validateAndEscapeIri(resIri, throw BadRequestException(s"Invalid resource IRI: $resIri"))
requestType match {
case "info" =>
ResourceInfoGetRequestV1(
iri = validResIri,
userProfile = userADM
)
case "rights" =>
ResourceRightsGetRequestV1(
iri = validResIri,
userProfile = userADM
)
case "context" =>
ResourceContextGetRequestV1(
iri = validResIri,
userProfile = userADM,
resinfo = resinfo
)
case "" =>
ResourceFullGetRequestV1(
iri = validResIri,
userADM = userADM
)
case other => throw BadRequestException(s"Invalid request type: $other")
}
}
def makeResourceSearchRequestMessage(
searchString: String,
resourceTypeIri: Option[IRI],
numberOfProps: Int,
limitOfResults: Int,
userProfile: UserADM
): ResourceSearchGetRequestV1 =
ResourceSearchGetRequestV1(
searchString = searchString,
resourceTypeIri = resourceTypeIri,
numberOfProps = numberOfProps,
limitOfResults = limitOfResults,
userProfile = userProfile
)
def valuesToCreate(
properties: Map[IRI, Seq[CreateResourceValueV1]],
acceptStandoffLinksToClientIDs: Boolean,
userProfile: UserADM
): Map[IRI, Future[Seq[CreateValueV1WithComment]]] = {
properties.map { case (propIri: IRI, values: Seq[CreateResourceValueV1]) =>
(
stringFormatter.validateAndEscapeIri(propIri, throw BadRequestException(s"Invalid property IRI $propIri")),
values.map { givenValue: CreateResourceValueV1 =>
givenValue.getValueClassIri match {
// create corresponding UpdateValueV1
case OntologyConstants.KnoraBase.TextValue =>
val richtext: CreateRichtextV1 = givenValue.richtext_value.get
// check if text has markup
if (richtext.utf8str.nonEmpty && richtext.xml.isEmpty && richtext.mapping_id.isEmpty) {
// simple text
Future(
CreateValueV1WithComment(
TextValueSimpleV1(
utf8str = stringFormatter.toSparqlEncodedString(
richtext.utf8str.get,
throw BadRequestException(s"Invalid text: '${richtext.utf8str.get}'")
),
language = richtext.language
),
givenValue.comment
)
)
} else if (richtext.xml.nonEmpty && richtext.mapping_id.nonEmpty) {
// XML: text with markup
val mappingIri = stringFormatter.validateAndEscapeIri(
richtext.mapping_id.get,
throw BadRequestException(s"mapping_id ${richtext.mapping_id.get} is invalid")
)
for {
textWithStandoffTags: TextWithStandoffTagsV2 <- RouteUtilV1.convertXMLtoStandoffTagV1(
xml = richtext.xml.get,
mappingIri = mappingIri,
acceptStandoffLinksToClientIDs =
acceptStandoffLinksToClientIDs,
userProfile = userProfile,
settings = settings,
appActor = appActor,
log = log
)
// collect the resource references from the linking standoff nodes
resourceReferences: Set[IRI] = stringFormatter.getResourceIrisFromStandoffTags(
textWithStandoffTags.standoffTagV2
)
} yield CreateValueV1WithComment(
TextValueWithStandoffV1(
utf8str = stringFormatter.toSparqlEncodedString(
textWithStandoffTags.text,
throw InconsistentRepositoryDataException("utf8str for TextValue contains invalid characters")
),
language = richtext.language,
resource_reference = resourceReferences,
standoff = textWithStandoffTags.standoffTagV2,
mappingIri = textWithStandoffTags.mapping.mappingIri,
mapping = textWithStandoffTags.mapping.mapping
),
givenValue.comment
)
} else {
throw BadRequestException("invalid parameters given for TextValueV1")
}
case OntologyConstants.KnoraBase.LinkValue =>
(givenValue.link_value, givenValue.link_to_client_id) match {
case (Some(targetIri: IRI), None) =>
// This is a link to an existing Knora IRI, so make sure the IRI is valid.
val validatedTargetIri = stringFormatter.validateAndEscapeIri(
targetIri,
throw BadRequestException(s"Invalid Knora resource IRI: $targetIri")
)
Future(CreateValueV1WithComment(LinkUpdateV1(validatedTargetIri), givenValue.comment))
case (None, Some(clientIDForTargetResource: String)) =>
// This is a link to the client's ID for a resource that hasn't been created yet.
Future(
CreateValueV1WithComment(LinkToClientIDUpdateV1(clientIDForTargetResource), givenValue.comment)
)
case (_, _) => throw AssertionException(s"Invalid link: $givenValue")
}
case OntologyConstants.KnoraBase.IntValue =>
Future(CreateValueV1WithComment(IntegerValueV1(givenValue.int_value.get), givenValue.comment))
case OntologyConstants.KnoraBase.DecimalValue =>
Future(CreateValueV1WithComment(DecimalValueV1(givenValue.decimal_value.get), givenValue.comment))
case OntologyConstants.KnoraBase.BooleanValue =>
Future(CreateValueV1WithComment(BooleanValueV1(givenValue.boolean_value.get), givenValue.comment))
case OntologyConstants.KnoraBase.UriValue =>
val uriValue = stringFormatter.validateAndEscapeIri(
givenValue.uri_value.get,
throw BadRequestException(s"Invalid URI: ${givenValue.uri_value.get}")
)
Future(CreateValueV1WithComment(UriValueV1(uriValue), givenValue.comment))
case OntologyConstants.KnoraBase.DateValue =>
val dateVal: JulianDayNumberValueV1 =
DateUtilV1.createJDNValueV1FromDateString(givenValue.date_value.get)
Future(CreateValueV1WithComment(dateVal, givenValue.comment))
case OntologyConstants.KnoraBase.ColorValue =>
val colorValue = stringFormatter.validateColor(
givenValue.color_value.get,
throw BadRequestException(s"Invalid color value: ${givenValue.color_value.get}")
)
Future(CreateValueV1WithComment(ColorValueV1(colorValue), givenValue.comment))
case OntologyConstants.KnoraBase.GeomValue =>
val geometryValue = stringFormatter.validateGeometryString(
givenValue.geom_value.get,
throw BadRequestException(s"Invalid geometry value: ${givenValue.geom_value.get}")
)
Future(CreateValueV1WithComment(GeomValueV1(geometryValue), givenValue.comment))
case OntologyConstants.KnoraBase.ListValue =>
val listNodeIri = stringFormatter.validateAndEscapeIri(
givenValue.hlist_value.get,
throw BadRequestException(s"Invalid value IRI: ${givenValue.hlist_value.get}")
)
Future(CreateValueV1WithComment(HierarchicalListValueV1(listNodeIri), givenValue.comment))
case OntologyConstants.KnoraBase.IntervalValue =>
val timeVals: Seq[BigDecimal] = givenValue.interval_value.get
if (timeVals.length != 2) throw BadRequestException("parameters for interval_value invalid")
Future(CreateValueV1WithComment(IntervalValueV1(timeVals.head, timeVals(1)), givenValue.comment))
case OntologyConstants.KnoraBase.TimeValue =>
val timeValStr: String = givenValue.time_value.get
val timeStamp: Instant = stringFormatter.xsdDateTimeStampToInstant(
timeValStr,
throw BadRequestException(s"Invalid timestamp: $timeValStr")
)
Future(CreateValueV1WithComment(TimeValueV1(timeStamp), givenValue.comment))
case OntologyConstants.KnoraBase.GeonameValue =>
Future(CreateValueV1WithComment(GeonameValueV1(givenValue.geoname_value.get), givenValue.comment))
case _ => throw BadRequestException(s"No value submitted")
}
}
)
}.map {
// transform Seq of Futures to a Future of a Seq
case (propIri: IRI, values: Seq[Future[CreateValueV1WithComment]]) =>
(propIri, Future.sequence(values))
}
}
def makeCreateResourceRequestMessage(
apiRequest: CreateResourceApiRequestV1,
userADM: UserADM
): Future[ResourceCreateRequestV1] = {
val projectIri = stringFormatter.validateAndEscapeIri(
apiRequest.project_id,
throw BadRequestException(s"Invalid project IRI: ${apiRequest.project_id}")
)
val resourceTypeIri = stringFormatter.validateAndEscapeIri(
apiRequest.restype_id,
throw BadRequestException(s"Invalid resource IRI: ${apiRequest.restype_id}")
)
val label = stringFormatter.toSparqlEncodedString(
apiRequest.label,
throw BadRequestException(s"Invalid label: '${apiRequest.label}'")
)
for {
projectShortcode: String <- for {
projectResponse: ProjectGetResponseADM <-
appActor
.ask(
ProjectGetRequestADM(
ProjectIdentifierADM(maybeIri = Some(projectIri)),
requestingUser = userADM
)
)
.mapTo[ProjectGetResponseADM]
} yield projectResponse.project.shortcode
file: Option[FileValueV1] <- apiRequest.file match {
case Some(filename) =>
// Ask Sipi about the file's metadata.
val tempFilePath = stringFormatter.makeSipiTempFilePath(settings, filename)
for {
fileMetadataResponse: GetFileMetadataResponse <-
appActor
.ask(
GetFileMetadataRequest(
filePath = tempFilePath,
requestingUser = userADM
)
)
.mapTo[GetFileMetadataResponse]
} yield Some(
RouteUtilV1.makeFileValue(
filename = filename,
fileMetadataResponse = fileMetadataResponse,
projectShortcode = projectShortcode
)
)
case None => FastFuture.successful(None)
}
valuesToBeCreatedWithFuture: Map[IRI, Future[Seq[CreateValueV1WithComment]]] =
valuesToCreate(
properties = apiRequest.properties,
acceptStandoffLinksToClientIDs = false,
userProfile = userADM
)
// make the whole Map a Future
valuesToBeCreated: Map[IRI, Seq[CreateValueV1WithComment]] <- ActorUtil.sequenceFutureSeqsInMap(
valuesToBeCreatedWithFuture
)
} yield ResourceCreateRequestV1(
resourceTypeIri = resourceTypeIri,
label = label,
projectIri = projectIri,
values = valuesToBeCreated,
file = file,
userProfile = userADM,
apiRequestID = UUID.randomUUID
)
}
def createOneResourceRequestFromXmlImport(
resourceRequest: CreateResourceFromXmlImportRequestV1,
projectShortcode: String,
userProfile: UserADM
): Future[OneOfMultipleResourceCreateRequestV1] = {
val values: Map[IRI, Future[Seq[CreateValueV1WithComment]]] = valuesToCreate(
properties = resourceRequest.properties,
acceptStandoffLinksToClientIDs = true,
userProfile = userProfile
)
// make the whole Map a Future
for {
valuesToBeCreated: Map[IRI, Seq[CreateValueV1WithComment]] <- ActorUtil.sequenceFutureSeqsInMap(values)
convertedFile <- resourceRequest.file match {
case Some(filename) =>
// Ask Sipi about the file's metadata.
val tempFilePath = stringFormatter.makeSipiTempFilePath(settings, filename)
for {
fileMetadataResponse: GetFileMetadataResponse <- appActor
.ask(
GetFileMetadataRequest(
filePath = tempFilePath,
requestingUser = userProfile
)
)
.mapTo[GetFileMetadataResponse]
} yield Some(
RouteUtilV1.makeFileValue(
filename = filename,
fileMetadataResponse = fileMetadataResponse,
projectShortcode = projectShortcode
)
)
case None => FastFuture.successful(None)
}
} yield OneOfMultipleResourceCreateRequestV1(
resourceTypeIri = resourceRequest.restype_id,
clientResourceID = resourceRequest.client_id,
label = stringFormatter.toSparqlEncodedString(
resourceRequest.label,
throw BadRequestException(s"The resource label is invalid: '${resourceRequest.label}'")
),
values = valuesToBeCreated,
file = convertedFile,
creationDate = resourceRequest.creationDate
)
}
def makeMultiResourcesRequestMessage(
resourceRequest: Seq[CreateResourceFromXmlImportRequestV1],
projectId: IRI,
apiRequestID: UUID,
userProfile: UserADM
): Future[MultipleResourceCreateRequestV1] = {
// Make sure there are no duplicate client resource IDs.
val duplicateClientIDs: immutable.Iterable[String] = resourceRequest.map(_.client_id).groupBy(identity).collect {
case (clientID, occurrences) if occurrences.size > 1 => clientID
}
if (duplicateClientIDs.nonEmpty) {
throw BadRequestException(
s"One or more client resource IDs were used for multiple resources: ${duplicateClientIDs.mkString(", ")}"
)
}
for {
projectShortcode: String <- for {
projectResponse: ProjectGetResponseADM <-
appActor
.ask(
ProjectGetRequestADM(
identifier = ProjectIdentifierADM(maybeIri = Some(projectId)),
requestingUser = userProfile
)
)
.mapTo[ProjectGetResponseADM]
} yield projectResponse.project.shortcode
resourcesToCreate: Seq[Future[OneOfMultipleResourceCreateRequestV1]] =
resourceRequest.map { createResourceRequest =>
createOneResourceRequestFromXmlImport(
resourceRequest = createResourceRequest,
projectShortcode = projectShortcode,
userProfile = userProfile
)
}
resToCreateCollection: Seq[OneOfMultipleResourceCreateRequestV1] <- Future.sequence(resourcesToCreate)
} yield MultipleResourceCreateRequestV1(
resourcesToCreate = resToCreateCollection,
projectIri = projectId,
userProfile = userProfile,
apiRequestID = apiRequestID
)
}
def makeGetPropertiesRequestMessage(resIri: IRI, userADM: UserADM): PropertiesGetRequestV1 =
PropertiesGetRequestV1(
iri = resIri,
userProfile = userADM
)
def makeResourceDeleteMessage(
resIri: IRI,
deleteComment: Option[String],
userADM: UserADM
): ResourceDeleteRequestV1 =
ResourceDeleteRequestV1(
resourceIri =
stringFormatter.validateAndEscapeIri(resIri, throw BadRequestException(s"Invalid resource IRI: $resIri")),
deleteComment = deleteComment.map(comment =>
stringFormatter.toSparqlEncodedString(comment, throw BadRequestException(s"Invalid comment: '$comment'"))
),
userADM = userADM,
apiRequestID = UUID.randomUUID
)
/**
* Given the IRI the main internal ontology to be used in an XML import, recursively gets instances of
* [[NamedGraphEntityInfoV1]] for that ontology, for `knora-base`, and for any other ontologies containing
* classes used in object class constraints in the main ontology.
*
* @param mainOntologyIri the IRI of the main ontology used in the XML import.
* @param userProfile the profile of the user making the request.
* @return a map of internal ontology IRIs to [[NamedGraphEntityInfoV1]] objects.
*/
def getNamedGraphInfos(mainOntologyIri: IRI, userProfile: UserADM): Future[Map[IRI, NamedGraphEntityInfoV1]] = {
/**
* Does the actual recursion for `getNamedGraphInfos`, loading only information about project-specific
* ontologies (i.e. ontologies other than `knora-base`).
*
* @param initialOntologyIri the IRI of the internal project-specific ontology to start with.
* @param intermediateResults the intermediate results collected so far (a map of internal ontology IRIs to
* [[NamedGraphEntityInfoV1]] objects). When this method is first called, this
* collection must already contain a [[NamedGraphEntityInfoV1]] for
* the `knora-base` ontology. This is an optimisation to avoid getting
* information about `knora-base` repeatedly, since every project-specific
* ontology depends on `knora-base`.
* @param userProfile the profile of the user making the request.
* @return a map of internal ontology IRIs to [[NamedGraphEntityInfoV1]] objects.
*/
def getNamedGraphInfosRec(
initialOntologyIri: IRI,
intermediateResults: Map[IRI, NamedGraphEntityInfoV1],
userProfile: UserADM
): Future[Map[IRI, NamedGraphEntityInfoV1]] = {
assert(intermediateResults.contains(OntologyConstants.KnoraBase.KnoraBaseOntologyIri))
for {
// Get a NamedGraphEntityInfoV1 listing the IRIs of the classes and properties defined in the initial ontology.
initialNamedGraphInfo: NamedGraphEntityInfoV1 <- appActor
.ask(
NamedGraphEntityInfoRequestV1(
initialOntologyIri,
userProfile
)
)
.mapTo[NamedGraphEntityInfoV1]
// Get details about those classes and properties.
entityInfoResponse: EntityInfoGetResponseV1 <-
appActor
.ask(
EntityInfoGetRequestV1(
resourceClassIris = initialNamedGraphInfo.resourceClasses,
propertyIris = initialNamedGraphInfo.propertyIris,
userProfile = userProfile
)
)
.mapTo[EntityInfoGetResponseV1]
// Look at the base classes of all the resource classes in the initial ontology. Make a set of
// the ontologies containing the definitions of those classes, not including including the initial ontology itself
// or any other ontologies we've already looked at.
ontologyIrisFromBaseClasses: Set[IRI] = entityInfoResponse.resourceClassInfoMap.foldLeft(Set.empty[IRI]) {
case (acc, (_, resourceClassInfo)) =>
val subClassOfOntologies: Set[IRI] = resourceClassInfo.subClassOf
.map(_.toSmartIri)
.filter(_.isKnoraDefinitionIri)
.map(_.getOntologyFromEntity.toString)
acc ++ subClassOfOntologies
} -- intermediateResults.keySet - initialOntologyIri
// Look at the properties that have cardinalities in the resource classes in the initial ontology.
// Make a set of the ontologies containing the definitions of those properties, not including the initial ontology itself
// or any other ontologies we've already looked at.
ontologyIrisFromCardinalities: Set[IRI] = entityInfoResponse.resourceClassInfoMap.foldLeft(Set.empty[IRI]) {
case (acc, (_, resourceClassInfo)) =>
val resourceCardinalityOntologies: Set[IRI] =
resourceClassInfo.knoraResourceCardinalities.map {
case (propertyIri, _) =>
propertyIri.toSmartIri.getOntologyFromEntity.toString
}.toSet
acc ++ resourceCardinalityOntologies
} -- intermediateResults.keySet - initialOntologyIri
// Look at the object class constraints of the properties in the initial ontology. Make a set of the ontologies containing those classes,
// not including the initial ontology itself or any other ontologies we've already looked at.
ontologyIrisFromObjectClassConstraints: Set[IRI] = entityInfoResponse.propertyInfoMap.map {
case (propertyIri, propertyInfo) =>
val propertyObjectClassConstraint =
propertyInfo
.getPredicateObject(
OntologyConstants.KnoraBase.ObjectClassConstraint
)
.getOrElse {
throw InconsistentRepositoryDataException(
s"Property $propertyIri has no knora-base:objectClassConstraint"
)
}
propertyObjectClassConstraint.toSmartIri.getOntologyFromEntity.toString
}.toSet -- intermediateResults.keySet - initialOntologyIri
// Make a set of all the ontologies referenced by the initial ontology.
referencedOntologies: Set[IRI] =
ontologyIrisFromBaseClasses ++ ontologyIrisFromCardinalities ++ ontologyIrisFromObjectClassConstraints
// Recursively get NamedGraphEntityInfoV1 instances for each of those ontologies.
lastResults: Map[IRI, NamedGraphEntityInfoV1] <-
referencedOntologies.foldLeft(
FastFuture.successful(intermediateResults + (initialOntologyIri -> initialNamedGraphInfo))
) { case (accFuture, ontologyIri) =>
for {
acc: Map[IRI, NamedGraphEntityInfoV1] <- accFuture
// Has a previous recursion already dealt with this ontology?
nextResults: Map[IRI, NamedGraphEntityInfoV1] <-
if (acc.contains(ontologyIri)) {
// Yes, so there's no need to get it again.
FastFuture.successful(acc)
} else {
// No. Recursively get it and the ontologies it depends on.
getNamedGraphInfosRec(
initialOntologyIri = ontologyIri,
intermediateResults = acc,
userProfile = userProfile
)
}
} yield acc ++ nextResults
}
} yield lastResults
}
for {
// Get a NamedGraphEntityInfoV1 for the knora-base ontology.
knoraBaseGraphEntityInfo <- appActor
.ask(
NamedGraphEntityInfoRequestV1(
OntologyConstants.KnoraBase.KnoraBaseOntologyIri,
userProfile
)
)
.mapTo[NamedGraphEntityInfoV1]
// Recursively get NamedGraphEntityInfoV1 instances for the main ontology to be used in the XML import,
// as well as any other project-specific ontologies it depends on.
graphInfos <- getNamedGraphInfosRec(
initialOntologyIri = mainOntologyIri,
intermediateResults =
Map(OntologyConstants.KnoraBase.KnoraBaseOntologyIri -> knoraBaseGraphEntityInfo),
userProfile = userProfile
)
} yield graphInfos
}
/**
* Given the IRI of an internal project-specific ontology, generates an [[XmlImportSchemaBundleV1]] for validating
* XML imports for that ontology and any other ontologies it depends on.
*
* @param internalOntologyIri the IRI of the main internal project-specific ontology to be used in the XML import.
* @param userProfile the profile of the user making the request.
* @return an [[XmlImportSchemaBundleV1]] for validating the import.
*/
def generateSchemasFromOntologies(
internalOntologyIri: IRI,
userProfile: UserADM
): Future[XmlImportSchemaBundleV1] = {
/**
* Called by the schema generation template to get the prefix label for an internal ontology
* entity IRI. The schema generation template gets these IRIs from resource cardinalities
* and property object class constraints, which we get from the ontology responder.
*
* @param internalEntityIri an internal ontology entity IRI.
* @return the prefix label that Knora uses to refer to the ontology.
*/
def getNamespacePrefixLabel(internalEntityIri: IRI): String = {
val prefixLabel = internalEntityIri.toSmartIri.getLongPrefixLabel
// If the schema generation template asks for the prefix label of something in knora-base, return
// the prefix label of the Knora XML import v1 namespace instead.
if (prefixLabel == OntologyConstants.KnoraBase.KnoraBaseOntologyLabel) {
OntologyConstants.KnoraXmlImportV1.KnoraXmlImportNamespacePrefixLabel
} else {
prefixLabel
}
}
/**
* Called by the schema generation template to get the entity name (i.e. the local name part) of an
* internal ontology entity IRI. The schema generation template gets these IRIs from resource cardinalities
* and property object class constraints, which we get from the ontology responder.
*
* @param internalEntityIri an internal ontology entity IRI.
* @return the local name of the entity.
*/
def getEntityName(internalEntityIri: IRI): String =
internalEntityIri.toSmartIri.getEntityName
for {
// Get a NamedGraphEntityInfoV1 for each ontology that we need to generate an XML schema for.
namedGraphInfos: Map[IRI, NamedGraphEntityInfoV1] <- getNamedGraphInfos(
mainOntologyIri = internalOntologyIri,
userProfile = userProfile
)
// Get information about the resource classes and properties in each ontology.
entityInfoResponseFutures: immutable.Iterable[Future[(IRI, EntityInfoGetResponseV1)]] =
namedGraphInfos.map { case (ontologyIri: IRI, namedGraphInfo: NamedGraphEntityInfoV1) =>
for {
entityInfoResponse: EntityInfoGetResponseV1 <- appActor
.ask(
EntityInfoGetRequestV1(
resourceClassIris = namedGraphInfo.resourceClasses,
propertyIris = namedGraphInfo.propertyIris,
userProfile = userProfile
)
)
.mapTo[EntityInfoGetResponseV1]
} yield ontologyIri -> entityInfoResponse
}
// Sequence the futures of entity info responses.
entityInfoResponses: immutable.Iterable[(IRI, EntityInfoGetResponseV1)] <- Future.sequence(
entityInfoResponseFutures
)
// Make a Map of internal ontology IRIs to EntityInfoGetResponseV1 objects.
entityInfoResponsesMap: Map[IRI, EntityInfoGetResponseV1] = entityInfoResponses.toMap
// Collect all the property definitions in a single Map. Since any schema could use any property, we will
// pass this Map to the schema generation template for every schema.
propertyInfoMap: Map[IRI, PropertyInfoV1] = entityInfoResponsesMap.values.flatMap(_.propertyInfoMap).toMap
// Make a map of internal ontology IRIs to XmlImportNamespaceInfoV1 objects describing the XML namespace
// of each schema to be generated. Don't generate a schema for knora-base, because the built-in Knora
// types are specified in the handwritten standard Knora XML import v1 schema.
schemasToGenerate: Map[IRI, XmlImportNamespaceInfoV1] =
(namedGraphInfos.keySet - OntologyConstants.KnoraBase.KnoraBaseOntologyIri).map { ontologyIri =>
ontologyIri -> stringFormatter.internalOntologyIriToXmlNamespaceInfoV1(ontologyIri.toSmartIri)
}.toMap
// Make an XmlImportNamespaceInfoV1 for the standard Knora XML import v1 schema's namespace.
knoraXmlImportSchemaNamespaceInfo: XmlImportNamespaceInfoV1 = XmlImportNamespaceInfoV1(
namespace =
OntologyConstants.KnoraXmlImportV1.KnoraXmlImportNamespaceV1,
prefixLabel =
OntologyConstants.KnoraXmlImportV1.KnoraXmlImportNamespacePrefixLabel
)
// Read the standard Knora XML import v1 schema from a file.
knoraXmlImportSchemaXml: String =
FileUtil.readTextResource(
OntologyConstants.KnoraXmlImportV1.KnoraXmlImportNamespacePrefixLabel + ".xsd"
)
// Construct an XmlImportSchemaV1 for the standard Knora XML import v1 schema.
knoraXmlImportSchema: XmlImportSchemaV1 = XmlImportSchemaV1(
namespaceInfo = knoraXmlImportSchemaNamespaceInfo,
schemaXml = knoraXmlImportSchemaXml
)
// Generate a schema for each project-specific ontology.
generatedSchemas: Map[IRI, XmlImportSchemaV1] = schemasToGenerate.map { case (ontologyIri, namespaceInfo) =>
// Each schema imports all the other generated schemas, plus the standard Knora XML import v1 schema.
// Sort the imports to make schema generation deterministic.
val importedNamespaceInfos: Seq[XmlImportNamespaceInfoV1] =
(schemasToGenerate - ontologyIri).values.toVector.sortBy {
importedNamespaceInfo =>
importedNamespaceInfo.prefixLabel
} :+ knoraXmlImportSchemaNamespaceInfo
// Generate the schema using a Twirl template.
val unformattedSchemaXml =
org.knora.webapi.messages.twirl.xsd.v1.xml
.xmlImport(
targetNamespaceInfo = namespaceInfo,
importedNamespaces = importedNamespaceInfos,
knoraXmlImportNamespacePrefixLabel =
OntologyConstants.KnoraXmlImportV1.KnoraXmlImportNamespacePrefixLabel,
resourceClassInfoMap = entityInfoResponsesMap(
ontologyIri
).resourceClassInfoMap,
propertyInfoMap = propertyInfoMap,
getNamespacePrefixLabel = internalEntityIri =>
getNamespacePrefixLabel(internalEntityIri),
getEntityName =
internalEntityIri => getEntityName(internalEntityIri)
)
.toString()
.trim
// Parse the generated XML schema.
val parsedSchemaXml =
try {
XML.loadString(unformattedSchemaXml)
} catch {
case parseEx: org.xml.sax.SAXParseException =>
throw AssertionException(
s"Generated XML schema for namespace ${namespaceInfo.namespace} is not valid XML. Please report this as a bug.",
parseEx,
log
)
}
// Format the generated XML schema nicely.
val formattedSchemaXml =
xmlPrettyPrinter.format(parsedSchemaXml)
// Wrap it in an XmlImportSchemaV1 object along with its XML namespace information.
val schema = XmlImportSchemaV1(
namespaceInfo = namespaceInfo,
schemaXml = formattedSchemaXml
)
namespaceInfo.namespace -> schema
}
// The schema bundle to be returned contains the generated schemas plus the standard Knora XML import v1 schema.
allSchemasForBundle: Map[IRI, XmlImportSchemaV1] =
generatedSchemas + (OntologyConstants.KnoraXmlImportV1.KnoraXmlImportNamespaceV1 -> knoraXmlImportSchema)
} yield XmlImportSchemaBundleV1(
mainNamespace = schemasToGenerate(internalOntologyIri).namespace,
schemas = allSchemasForBundle
)
}
/**
* Generates a byte array representing a Zip file containing XML schemas for validating XML import data.
*
* @param internalOntologyIri the IRI of the main internal ontology for which data will be imported.
* @param userProfile the profile of the user making the request.
* @return a byte array representing a Zip file containing XML schemas.
*/
def generateSchemaZipFile(internalOntologyIri: IRI, userProfile: UserADM): Future[Array[Byte]] =
for {
// Generate a bundle of XML schemas.
schemaBundle: XmlImportSchemaBundleV1 <- generateSchemasFromOntologies(
internalOntologyIri = internalOntologyIri,
userProfile = userProfile
)
// Generate the contents of the Zip file: a Map of file names to file contents (byte arrays).
zipFileContents: Map[String, Array[Byte]] = schemaBundle.schemas.values.map { schema: XmlImportSchemaV1 =>
val schemaFilename: String =
schema.namespaceInfo.prefixLabel + ".xsd"
val schemaXmlBytes: Array[Byte] =
schema.schemaXml.getBytes(StandardCharsets.UTF_8)
schemaFilename -> schemaXmlBytes
}.toMap
} yield FileUtil.createZipFileBytes(zipFileContents)
/**
* Validates bulk import XML using project-specific XML schemas and the Knora XML import schema v1.
*
* @param xml the XML to be validated.
* @param defaultNamespace the default namespace of the submitted XML. This should be the Knora XML import
* namespace corresponding to the main internal ontology used in the import.
* @param userADM the profile of the user making the request.
* @return a `Future` containing `()` if successful, otherwise a failed future.
*/
def validateImportXml(xml: String, defaultNamespace: IRI, userADM: UserADM): Future[Unit] = {
// Convert the default namespace of the submitted XML to an internal ontology IRI. This should be the
// IRI of the main ontology used in the import.
val mainOntologyIri: SmartIri = stringFormatter.xmlImportNamespaceToInternalOntologyIriV1(
defaultNamespace,
throw BadRequestException(s"Invalid XML import namespace: $defaultNamespace")
)
val validationFuture: Future[Unit] = for {
// Generate a bundle of XML schemas for validating the submitted XML.
schemaBundle: XmlImportSchemaBundleV1 <- generateSchemasFromOntologies(mainOntologyIri.toString, userADM)
// Make a javax.xml.validation.SchemaFactory for instantiating XML schemas.
schemaFactory: SchemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI)
// Tell the SchemaFactory to find additional schemas using our SchemaBundleResolver, which gets them
// from the XmlImportSchemaBundleV1 we generated.
_ = schemaFactory.setResourceResolver(new SchemaBundleResolver(schemaBundle))
// Use the SchemaFactory to instantiate a javax.xml.validation.Schema representing the main schema in
// the bundle.
mainSchemaXml: String = schemaBundle.schemas(schemaBundle.mainNamespace).schemaXml
schemaInstance: Schema = schemaFactory.newSchema(new StreamSource(new StringReader(mainSchemaXml)))
// Validate the submitted XML using a validator based on the main schema.
schemaValidator: Validator = schemaInstance.newValidator()
_ = schemaValidator.validate(new StreamSource(new StringReader(xml)))
} yield ()
// If the XML fails schema validation, return a failed Future containing a BadRequestException.
validationFuture.recover { case e @ (_: IllegalArgumentException | _: SAXException) =>
throw BadRequestException(s"XML import did not pass XML schema validation: $e")
}
}
/**
* Converts parsed import XML into a sequence of [[CreateResourceFromXmlImportRequestV1]] for each resource
* described in the XML.
*
* @param rootElement the root element of an XML document describing multiple resources to be created.
* @return Seq[CreateResourceFromXmlImportRequestV1] a collection of resource creation requests.
*/
def importXmlToCreateResourceRequests(rootElement: Elem): Seq[CreateResourceFromXmlImportRequestV1] = {
rootElement.head.child
.filter(node => node.label != "#PCDATA")
.map { resourceNode =>
// Get the client's unique ID for the resource.
val clientIDForResource: String = (resourceNode \ "@id").toString
// Get the optional resource creation date.
val creationDate: Option[Instant] = resourceNode
.attribute("creationDate")
.map(creationDateNode =>
stringFormatter.xsdDateTimeStampToInstant(
creationDateNode.text,
throw BadRequestException(s"Invalid resource creation date: ${creationDateNode.text}")
)
)
// Convert the XML element's label and namespace to an internal resource class IRI.
val elementNamespace: String = resourceNode.getNamespace(resourceNode.prefix)
val restype_id = stringFormatter.xmlImportElementNameToInternalOntologyIriV1(
namespace = elementNamespace,
elementLabel = resourceNode.label,
errorFun = throw BadRequestException(s"Invalid XML namespace: $elementNamespace")
)
// Get the child elements of the resource element.
val childElements: Seq[Node] = resourceNode.child.filterNot(_.label == "#PCDATA")
// The label must be the first child element of the resource element.
val resourceLabel: String = childElements.headOption match {
case Some(firstChildElem) => firstChildElem.text
case None =>
throw BadRequestException(
s"Resource '$clientIDForResource' contains no ${OntologyConstants.KnoraXmlImportV1.KnoraXmlImportNamespacePrefixLabel}:label element"
)
}
val childElementsAfterLabel = childElements.tail
// Get the name of the resource's file, if any. This represents a file that in Sipi's temporary storage.
// If provided, it must be the second child element of the resource element.
val file: Option[String] = childElementsAfterLabel.headOption match {
case Some(secondChildElem) =>
if (secondChildElem.label == "file") {
Some(secondChildElem.attribute("filename").get.text)
} else {
None
}
case None => None
}
// Any remaining child elements of the resource element represent property values.
val propertyElements = if (file.isDefined) {
childElementsAfterLabel.tail
} else {
childElementsAfterLabel
}
// Traverse the property value elements. This produces a sequence in which the same property IRI
// can occur multiple times, once for each value.
val propertiesWithValues: Seq[(IRI, CreateResourceValueV1)] = propertyElements.map { propertyNode =>
// Is this a property from another ontology (in the form prefixLabel__localName)?
val propertyIri = stringFormatter.toPropertyIriFromOtherOntologyInXmlImport(propertyNode.label) match {
case Some(iri) =>
// Yes. Use the corresponding entity IRI for it.
iri
case None =>
// No. Convert the XML element's label and namespace to an internal property IRI.
val propertyNodeNamespace = propertyNode.getNamespace(propertyNode.prefix)
stringFormatter.xmlImportElementNameToInternalOntologyIriV1(
namespace = propertyNodeNamespace,
elementLabel = propertyNode.label,
errorFun = throw BadRequestException(s"Invalid XML namespace: $propertyNodeNamespace")
)
}
// If the property element has one child element with a knoraType attribute, it's a link
// property, otherwise it's an ordinary value property.
val valueNodes: Seq[Node] = propertyNode.child.filterNot(_.label == "#PCDATA")
if (valueNodes.size == 1 && valueNodes.head.attribute("knoraType").isDefined) {
propertyIri -> knoraDataTypeXml(valueNodes.head)
} else {
propertyIri -> knoraDataTypeXml(propertyNode)
}
}
// Group the values by property IRI.
val groupedPropertiesWithValues: Map[IRI, Seq[CreateResourceValueV1]] = propertiesWithValues.groupBy {
case (propertyIri: IRI, _) => propertyIri
}.map { case (propertyIri: IRI, resultsForProperty: Seq[(IRI, CreateResourceValueV1)]) =>
propertyIri -> resultsForProperty.map { case (_, propertyValue: CreateResourceValueV1) =>
propertyValue
}
}