/
ValuesResponderV1.scala
3159 lines (2825 loc) · 163 KB
/
ValuesResponderV1.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.v1
import akka.pattern._
import java.time.Instant
import scala.annotation.tailrec
import scala.concurrent.Future
import dsp.errors._
import dsp.schema.domain.Cardinality._
import org.knora.webapi._
import org.knora.webapi.messages.IriConversions._
import org.knora.webapi.messages.OntologyConstants
import org.knora.webapi.messages.StringFormatter
import org.knora.webapi.messages.admin.responder.permissionsmessages.DefaultObjectAccessPermissionsStringForPropertyGetADM
import org.knora.webapi.messages.admin.responder.permissionsmessages.DefaultObjectAccessPermissionsStringResponseADM
import org.knora.webapi.messages.admin.responder.permissionsmessages.PermissionADM
import org.knora.webapi.messages.admin.responder.permissionsmessages.PermissionType
import org.knora.webapi.messages.admin.responder.projectsmessages.ProjectADM
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.triplestoremessages._
import org.knora.webapi.messages.twirl.SparqlTemplateLinkUpdate
import org.knora.webapi.messages.util.KnoraSystemInstances
import org.knora.webapi.messages.util.PermissionUtilADM
import org.knora.webapi.messages.util.ResponderData
import org.knora.webapi.messages.util.ValueUtilV1
import org.knora.webapi.messages.util.rdf.SparqlSelectResult
import org.knora.webapi.messages.util.rdf.VariableResultsRow
import org.knora.webapi.messages.v1.responder.ontologymessages.EntityInfoGetRequestV1
import org.knora.webapi.messages.v1.responder.ontologymessages.EntityInfoGetResponseV1
import org.knora.webapi.messages.v1.responder.projectmessages.ProjectInfoByIRIGetV1
import org.knora.webapi.messages.v1.responder.projectmessages.ProjectInfoV1
import org.knora.webapi.messages.v1.responder.resourcemessages._
import org.knora.webapi.messages.v1.responder.usermessages.UserProfileByIRIGetV1
import org.knora.webapi.messages.v1.responder.usermessages.UserProfileTypeV1
import org.knora.webapi.messages.v1.responder.usermessages.UserProfileV1
import org.knora.webapi.messages.v1.responder.valuemessages._
import org.knora.webapi.messages.v2.responder.standoffmessages._
import org.knora.webapi.messages.v2.responder.valuemessages.FileValueContentV2
import org.knora.webapi.responders.IriLocker
import org.knora.webapi.responders.Responder
import org.knora.webapi.responders.v2.ResourceUtilV2
import org.knora.webapi.util._
/**
* Updates Knora values.
*/
class ValuesResponderV1(responderData: ResponderData) extends Responder(responderData.actorDeps) {
// Converts SPARQL query results to ApiValueV1 objects.
val valueUtilV1 = new ValueUtilV1(responderData.appConfig)
/**
* Receives a message of type [[ValuesResponderRequestV1]], and returns an appropriate response message.
*/
def receive(msg: ValuesResponderRequestV1) = msg match {
case ValueGetRequestV1(valueIri, userProfile) =>
getValueResponseV1(valueIri, userProfile)
case LinkValueGetRequestV1(subjectIri, predicateIri, objectIri, userProfile) =>
getLinkValue(subjectIri, predicateIri, objectIri, userProfile)
case versionHistoryRequest: ValueVersionHistoryGetRequestV1 =>
getValueVersionHistoryResponseV1(versionHistoryRequest)
case createValueRequest: CreateValueRequestV1 => createValueV1(createValueRequest)
case changeValueRequest: ChangeValueRequestV1 => changeValueV1(changeValueRequest)
case changeFileValueRequest: ChangeFileValueRequestV1 => changeFileValueV1(changeFileValueRequest)
case changeCommentRequest: ChangeCommentRequestV1 => changeCommentV1(changeCommentRequest)
case deleteValueRequest: DeleteValueRequestV1 => deleteValueV1(deleteValueRequest)
case createMultipleValuesRequest: GenerateSparqlToCreateMultipleValuesRequestV1 =>
createMultipleValuesV1(createMultipleValuesRequest)
case verifyMultipleValueCreationRequest: VerifyMultipleValueCreationRequestV1 =>
verifyMultipleValueCreation(verifyMultipleValueCreationRequest)
case other => handleUnexpectedMessage(other, log, this.getClass.getName)
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods for generating complete API responses.
/**
* Queries a `knora-base:Value` and returns a [[ValueGetResponseV1]] describing it.
*
* @param valueIri the IRI of the value to be queried.
*
* @param userProfile the profile of the user making the request.
* @return a [[ValueGetResponseV1]].
*/
private def getValueResponseV1(
valueIri: IRI,
userProfile: UserADM
): Future[ValueGetResponseV1] =
for {
maybeValueQueryResult <- findValue(
valueIri = valueIri,
userProfile = userProfile
)
response <- maybeValueQueryResult match {
case Some(valueQueryResult) =>
for {
maybeValueCreatorProfile <- appActor
.ask(
UserProfileByIRIGetV1(
userIri = valueQueryResult.creatorIri,
userProfileType = UserProfileTypeV1.RESTRICTED
)
)
.mapTo[Option[UserProfileV1]]
valueCreatorProfile = maybeValueCreatorProfile match {
case Some(up) => up
case None =>
throw NotFoundException(
s"User ${valueQueryResult.creatorIri} not found"
)
}
} yield ValueGetResponseV1(
valuetype = valueQueryResult.value.valueTypeIri,
rights = valueQueryResult.permissionCode,
value = valueQueryResult.value,
valuecreator = valueCreatorProfile.userData.email.get,
valuecreatorname = valueCreatorProfile.userData.fullname.get,
valuecreationdate = valueQueryResult.creationDate,
comment = valueQueryResult.comment
)
case None =>
throw NotFoundException(s"Value $valueIri not found (it may have been deleted)")
}
} yield response
/**
* Creates a new value of a resource property (as opposed to a new version of an existing value).
*
* @param createValueRequest the request message.
* @return a [[CreateValueResponseV1]] if the update was successful.
*/
private def createValueV1(createValueRequest: CreateValueRequestV1): Future[CreateValueResponseV1] = {
/**
* Creates a [[Future]] that does pre-update checks and performs the update. This function will be
* called by [[IriLocker]] once it has acquired an update lock on the resource.
*
* @param userIri the IRI of the user making the request.
* @return a [[Future]] that does pre-update checks and performs the update.
*/
def makeTaskFuture(userIri: IRI): Future[CreateValueResponseV1] =
for {
// Check that the submitted value has the correct type for the property.
entityInfoResponse: EntityInfoGetResponseV1 <- appActor
.ask(
EntityInfoGetRequestV1(
propertyIris = Set(createValueRequest.propertyIri),
userProfile = createValueRequest.userProfile
)
)
.mapTo[EntityInfoGetResponseV1]
propertyInfo = entityInfoResponse.propertyInfoMap(createValueRequest.propertyIri)
propertyObjectClassConstraint = propertyInfo
.getPredicateObject(OntologyConstants.KnoraBase.ObjectClassConstraint)
.getOrElse {
throw InconsistentRepositoryDataException(
s"Property ${createValueRequest.propertyIri} has no knora-base:objectClassConstraint"
)
}
// Check that the object of the property (the value to be created, or the target of the link to be created) will have
// the correct type for the property's knora-base:objectClassConstraint.
_ <- checkPropertyObjectClassConstraintForValue(
propertyIri = createValueRequest.propertyIri,
propertyObjectClassConstraint = propertyObjectClassConstraint,
updateValueV1 = createValueRequest.value,
userProfile = createValueRequest.userProfile
)
// Check that the user has permission to modify the resource. (We do this as late as possible because it's
// slower than the other checks, and there's no point in doing it if the other checks fail.)
resourceFullResponse <- appActor
.ask(
ResourceFullGetRequestV1(
iri = createValueRequest.resourceIri,
userADM = createValueRequest.userProfile,
getIncoming = false
)
)
.mapTo[ResourceFullResponseV1]
resourcePermissionCode: Option[Int] = resourceFullResponse.resdata.flatMap(resdata => resdata.rights)
_ = if (
!PermissionUtilADM.impliesPermissionCodeV1(
userHasPermissionCode = resourcePermissionCode,
userNeedsPermission = OntologyConstants.KnoraBase.ModifyPermission
)
) {
throw ForbiddenException(
s"User $userIri does not have permission to modify resource ${createValueRequest.resourceIri}"
)
}
// Ensure that creating the value would not violate the resource's cardinality restrictions or create a duplicate value.
// This works in API v1 because a ResourceFullResponseV1 contains the resource's current property values (but only the
// ones that the user is allowed to see, otherwise checking for duplicate values would be a security risk), plus empty
// properties for which the resource's class has cardinalities. If the resources responder returns no information about
// the property, this could be because the property isn't allowed for the resource, or because it's allowed, has a
// cardinality of MustHaveOne or MayHaveOne, and already has a value that the user isn't allowed to see. We'll have to
// implement this in a different way in API v2.
cardinalityOK = resourceFullResponse.props.flatMap(
_.properties.find(_.pid == createValueRequest.propertyIri)
) match {
case Some(prop: PropertyV1) =>
if (
prop.values
.exists(apiValueV1 => createValueRequest.value.isDuplicateOfOtherValue(apiValueV1))
) {
throw DuplicateValueException()
}
!((prop.occurrence.get == MayHaveOne.value || prop.occurrence.get == MustHaveOne.value) && prop.values.nonEmpty)
case None =>
false
}
_ = if (!cardinalityOK) {
throw OntologyConstraintException(
s"Cardinality restrictions do not allow a value to be added for property ${createValueRequest.propertyIri} of resource ${createValueRequest.resourceIri}"
)
}
// Get the IRI of project of the containing resource.
projectIri: IRI = resourceFullResponse.resinfo
.getOrElse(
throw InconsistentRepositoryDataException(
s"Did not find resource info for resource ${createValueRequest.resourceIri}"
)
)
.project_id
// Get the resource class of the containing resource
resourceClassIri: IRI = resourceFullResponse.resinfo
.getOrElse(
throw InconsistentRepositoryDataException(
s"Did not find resource info for resource ${createValueRequest.resourceIri}"
)
)
.restype_id
defaultObjectAccessPermissions <- appActor
.ask(
DefaultObjectAccessPermissionsStringForPropertyGetADM(
projectIri = projectIri,
resourceClassIri = resourceClassIri,
propertyIri = createValueRequest.propertyIri,
targetUser = createValueRequest.userProfile,
requestingUser = KnoraSystemInstances.Users.SystemUser
)
)
.mapTo[DefaultObjectAccessPermissionsStringResponseADM]
_ = log.debug(s"createValueV1 - defaultObjectAccessPermissions: $defaultObjectAccessPermissions")
// Get project info
maybeProjectInfo <- appActor
.ask(
ProjectInfoByIRIGetV1(
iri = projectIri,
userProfileV1 = Some(createValueRequest.userProfile.asUserProfileV1)
)
)
.mapTo[Option[ProjectInfoV1]]
projectInfo = maybeProjectInfo match {
case Some(pi) => pi
case None => throw NotFoundException(s"Project '$projectIri' not found.")
}
// Everything seems OK, so create the value.
unverifiedValue <- createValueV1AfterChecks(
dataNamedGraph = StringFormatter.getGeneralInstance.projectDataNamedGraphV1(projectInfo),
projectIri = resourceFullResponse.resinfo.get.project_id,
resourceIri = createValueRequest.resourceIri,
propertyIri = createValueRequest.propertyIri,
value = createValueRequest.value,
comment = createValueRequest.comment,
valueCreator = userIri,
valuePermissions = defaultObjectAccessPermissions.permissionLiteral,
userProfile = createValueRequest.userProfile
)
// Verify that it was created.
apiResponse <- verifyValueCreation(
resourceIri = createValueRequest.resourceIri,
propertyIri = createValueRequest.propertyIri,
unverifiedValue = unverifiedValue,
userProfile = createValueRequest.userProfile
)
} yield apiResponse
for {
// Don't allow anonymous users to create values.
userIri <- Future {
if (createValueRequest.userProfile.isAnonymousUser) {
throw ForbiddenException("Anonymous users aren't allowed to create values")
} else {
createValueRequest.userProfile.id
}
}
// Do the remaining pre-update checks and the update while holding an update lock on the resource.
taskResult <- IriLocker.runWithIriLock(
createValueRequest.apiRequestID,
createValueRequest.resourceIri,
() => makeTaskFuture(userIri)
)
} yield taskResult
}
/**
* Generates SPARQL for creating multiple values in a new, empty resource, using an existing transaction.
* The resource ''must'' be a new, empty resource, i.e. it must have no values. All pre-update checks must already
* have been performed. Specifically, this method assumes that:
*
* - The requesting user has permission to add values to the resource.
* - Each submitted value is consistent with the `knora-base:objectClassConstraint` of the property that is supposed to point to it.
* - The resource has a suitable cardinality for each submitted value.
* - All required values are provided.
*
* @param createMultipleValuesRequest the request message.
* @return a [[GenerateSparqlToCreateMultipleValuesResponseV1]].
*/
private def createMultipleValuesV1(
createMultipleValuesRequest: GenerateSparqlToCreateMultipleValuesRequestV1
): Future[GenerateSparqlToCreateMultipleValuesResponseV1] = {
/**
* Creates a [[Future]] that performs the update. This function will be called by [[IriLocker]] once it
* has acquired an update lock on the resource.
*
* @param userIri the IRI of the user making the request.
* @return a [[Future]] that does pre-update checks and performs the update.
*/
def makeTaskFuture(userIri: IRI): Future[GenerateSparqlToCreateMultipleValuesResponseV1] = {
/**
* Assists in the numbering of values to be created.
*
* @param createValueV1WithComment the value to be created.
* @param valueIndex the index of the value in the sequence of all values to be created. This will be used
* to generate unique SPARQL variable names.
* @param valueHasOrder the index of the value in the sequence of values to be created for a particular property.
* This will be used to generate `knora-base:valueHasOrder`.
*/
case class NumberedValueToCreate(
createValueV1WithComment: CreateValueV1WithComment,
valueIndex: Int,
valueHasOrder: Int
)
/**
* Assists in collecting generated SPARQL as well as other information about values to be created for
* a particular property.
*
* @param insertSparql statements to be included in the SPARQL INSERT clause.
* @param valuesToVerify information about each value to be created.
* @param valueIndexes the value index of each value described by this object (so they can be sorted).
*/
case class SparqlGenerationResultForProperty(
insertSparql: Vector[String] = Vector.empty[String],
valuesToVerify: Vector[UnverifiedValueV1] = Vector.empty[UnverifiedValueV1],
valueIndexes: Vector[Int] = Vector.empty[Int]
)
for {
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Generate SPARQL to create links and LinkValues for standoff resource references in text values
// To create LinkValues for the standoff resource references in the values to be created, we need to compute
// the initial reference count of each LinkValue. This is equal to the number of TextValues in the resource
// that have standoff references to a particular target resource.
// First, make a single list of all the values to be created.
valuesToCreatePerProperty: Map[IRI, Seq[CreateValueV1WithComment]] <- Future(createMultipleValuesRequest.values)
valuesToCreateForAllProperties: Iterable[Seq[CreateValueV1WithComment]] = valuesToCreatePerProperty.values
allValuesToCreate: Iterable[CreateValueV1WithComment] = valuesToCreateForAllProperties.flatten
// Then, get the standoff resource references from all the text values to be created.
// The 'collect' method builds a new list by applying a partial function to all elements of the list
// on which the function is defined.
resourceReferencesForAllTextValues: Iterable[Set[IRI]] =
allValuesToCreate.collect { case CreateValueV1WithComment(textValueV1: TextValueWithStandoffV1, _) =>
// check that resource references are consistent in `resource_reference` and linking standoff tags
checkTextValueResourceRefs(textValueV1)
textValueV1.resource_reference
}
// Combine those resource references into a single list, so if there are n text values with a reference to
// some IRI, the list will contain that IRI n times.
allResourceReferences: Iterable[IRI] = resourceReferencesForAllTextValues.flatten
// Now we need to count the number of times each IRI occurs in allResourceReferences. To do this, first
// use groupBy(identity). The groupBy method takes a function that returns a key for each item in the
// collection, and makes a Map in which items with the same key are grouped together. The identity
// function just returns its argument. So groupBy(identity) makes a Map[IRI, Iterable[IRI]] in which each
// IRI points to a sequence of the same IRI repeated as many times as it occurred in allResourceReferences.
allResourceReferencesGrouped: Map[IRI, Iterable[IRI]] = allResourceReferences.groupBy(identity)
// Finally, replace each Iterable[IRI] with its size. That's the number of text values containing
// standoff references to that IRI.
targetIris: Map[IRI, Int] = allResourceReferencesGrouped.view.mapValues(_.size).toMap
// If we're creating values as part of a bulk import, some standoff links could point to resources
// that already exist in the triplestore, and others could point to resources that are being created
// as part of the import. We need to know here which ones are supposed to exist already and which aren't,
// because if a target resource is supposed to exist already, we have to query the triplestore now to check
// that it really exists.
//
// Therefore, in the GenerateSparqlToCreateMultipleValuesRequestV1 we received, the standoff link targets
// that don't yet exist are represented as client resource IDs, while the targets that really exist are
// represented as ordinary IRIs. StringFormatter.isStandoffLinkReferenceToClientIDForResource() can tell
// us which are which.
//
// So now we can get the set of standoff link targets that are ordinary IRIs, and check that each of
// them exists in the triplestore and is a knora-base:Resource.
targetIrisThatAlreadyExist: Set[IRI] =
targetIris.keySet.filterNot(iri => stringFormatter.isStandoffLinkReferenceToClientIDForResource(iri))
targetIriCheckResult <- checkStandoffResourceReferenceTargets(
targetIris = targetIrisThatAlreadyExist,
userProfile = createMultipleValuesRequest.userProfile
)
// For each target IRI, construct a SparqlTemplateLinkUpdate to create a hasStandoffLinkTo property and one LinkValue,
// with the associated count as the LinkValue's initial reference count.
standoffLinkUpdates: Seq[SparqlTemplateLinkUpdate] = targetIris.toSeq.map {
case (targetIri, initialReferenceCount) =>
// If the target of a standoff link is a client ID for a resource, convert it to the corresponding real resource IRI.
val realTargetIri =
stringFormatter.toRealStandoffLinkTargetResourceIri(
iri = targetIri,
clientResourceIDsToResourceIris =
createMultipleValuesRequest.clientResourceIDsToResourceIris
)
SparqlTemplateLinkUpdate(
linkPropertyIri =
OntologyConstants.KnoraBase.HasStandoffLinkTo.toSmartIri,
directLinkExists = false,
insertDirectLink = true,
deleteDirectLink = false,
linkValueExists = false,
linkTargetExists =
true, // doesn't matter, the generateInsertStatementsForStandoffLinks template doesn't use it
newLinkValueIri = stringFormatter.makeRandomValueIri(
createMultipleValuesRequest.resourceIri
),
linkTargetIri = realTargetIri,
currentReferenceCount = 0,
newReferenceCount = initialReferenceCount,
newLinkValueCreator =
OntologyConstants.KnoraAdmin.SystemUser,
newLinkValuePermissions =
standoffLinkValuePermissions
)
}
// Generate INSERT clause statements based on those SparqlTemplateLinkUpdates.
standoffLinkInsertSparql: String = org.knora.webapi.messages.twirl.queries.sparql.v1.txt
.generateInsertStatementsForStandoffLinks(
resourceIri = createMultipleValuesRequest.resourceIri,
linkUpdates = standoffLinkUpdates,
creationDate = createMultipleValuesRequest.creationDate,
stringFormatter = stringFormatter
)
.toString()
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Number each value to be created, and give it a valueHasOrder
// Ungroup the values to be created so we can number them as a single sequence (to create unique SPARQL variable names for each value).
ungroupedValues: Seq[(IRI, CreateValueV1WithComment)] =
createMultipleValuesRequest.values.toSeq.flatMap { case (propertyIri, values) =>
values.map(value => (propertyIri, value))
}
// Number them all as a single sequence. Give each one a knora-base:valueHasOrder of 0 for now; we'll take care of that in a moment.
numberedValues: Seq[(IRI, NumberedValueToCreate)] =
ungroupedValues.zipWithIndex.map {
case ((propertyIri: IRI, valueWithComment: CreateValueV1WithComment), valueIndex) =>
(propertyIri, NumberedValueToCreate(valueWithComment, valueIndex, 0))
}
// Group them again by property so we generate knora-base:valueHasOrder for the values of each property.
groupedNumberedValues: Map[IRI, Seq[NumberedValueToCreate]] =
numberedValues.groupBy(_._1).map { case (propertyIri, propertyIriAndValueTuples) =>
(propertyIri, propertyIriAndValueTuples.map(_._2))
}
// Generate knora-base:valueHasOrder for the values of each property.
groupedNumberedValuesWithValueHasOrder: Map[IRI, Seq[NumberedValueToCreate]] = groupedNumberedValues.map {
case (propertyIri, values) =>
val valuesWithValueHasOrder =
values.zipWithIndex.map {
case (
numberedValueToCreate,
valueHasOrder
) =>
numberedValueToCreate
.copy(valueHasOrder =
valueHasOrder
)
}
(
propertyIri,
valuesWithValueHasOrder
)
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Generate SPARQL for each value of each property
// Make a SparqlGenerationResultForProperty for each property.
sparqlGenerationResults: Map[IRI, SparqlGenerationResultForProperty] =
groupedNumberedValuesWithValueHasOrder.map {
case (propertyIri: IRI, valuesToCreate: Seq[NumberedValueToCreate]) =>
val defaultPropertyAccessPermissions: String =
createMultipleValuesRequest.defaultPropertyAccessPermissions(propertyIri)
// log.debug(s"createValueV1 - defaultPropertyAccessPermissions: $defaultPropertyAccessPermissions")
// For each property, construct a SparqlGenerationResultForProperty containing WHERE clause statements, INSERT clause statements, and UnverifiedValueV1s.
val sparqlGenerationResultForProperty: SparqlGenerationResultForProperty =
valuesToCreate.foldLeft(SparqlGenerationResultForProperty()) {
case (propertyAcc: SparqlGenerationResultForProperty, valueToCreate: NumberedValueToCreate) =>
val updateValueV1 = valueToCreate.createValueV1WithComment.updateValueV1
val newValueIri = stringFormatter.makeRandomValueIri(createMultipleValuesRequest.resourceIri)
// How we generate the SPARQL depends on whether we're creating a link or an ordinary value.
val insertSparql: String = valueToCreate.createValueV1WithComment.updateValueV1 match {
case linkUpdateV1: LinkUpdateV1 =>
// We're creating a link.
// Construct a SparqlTemplateLinkUpdate to tell the SPARQL templates how to create
// the link and its LinkValue.
val sparqlTemplateLinkUpdate = SparqlTemplateLinkUpdate(
linkPropertyIri = propertyIri.toSmartIri,
directLinkExists = false,
insertDirectLink = true,
deleteDirectLink = false,
linkValueExists = false,
linkTargetExists = linkUpdateV1.targetExists,
newLinkValueIri = newValueIri,
linkTargetIri = linkUpdateV1.targetResourceIri,
currentReferenceCount = 0,
newReferenceCount = 1,
newLinkValueCreator = userIri,
newLinkValuePermissions = defaultPropertyAccessPermissions
)
// Generate INSERT DATA clause statements for the link.
org.knora.webapi.messages.twirl.queries.sparql.v1.txt
.generateInsertStatementsForCreateLink(
resourceIri = createMultipleValuesRequest.resourceIri,
linkUpdate = sparqlTemplateLinkUpdate,
creationDate = createMultipleValuesRequest.creationDate,
maybeComment = valueToCreate.createValueV1WithComment.comment,
maybeValueHasOrder = Some(valueToCreate.valueHasOrder),
stringFormatter = stringFormatter
)
.toString()
case _ =>
// We're creating an ordinary value.
// If this is a text value and we're creating values as part of a bulk import, some of the target IRIs of
// standoff link tags in the text value might be client IDs for resources rather than real resource IRIs.
// Replace those IDs with the real IRIs of the target resources, so the generateInsertStatementsForCreateValue
// template can use the real IRIs.
val valueWithRealStandoffLinkIris = updateValueV1 match {
case textValueWithStandoff: TextValueWithStandoffV1 =>
val standoffWithRealStandoffLinkIris = textValueWithStandoff.standoff.map {
standoffTag: StandoffTagV2 =>
standoffTag.copy(
attributes = standoffTag.attributes.map {
case iriAttribute: StandoffTagIriAttributeV2 =>
iriAttribute.copy(
value = stringFormatter.toRealStandoffLinkTargetResourceIri(
iri = iriAttribute.value,
clientResourceIDsToResourceIris =
createMultipleValuesRequest.clientResourceIDsToResourceIris
)
)
case otherAttribute => otherAttribute
}
)
}
textValueWithStandoff.copy(
standoff = standoffWithRealStandoffLinkIris
)
case otherValue => otherValue
}
// Generate INSERT DATA clause statements for the value.
org.knora.webapi.messages.twirl.queries.sparql.v1.txt
.generateInsertStatementsForCreateValue(
resourceIri = createMultipleValuesRequest.resourceIri,
propertyIri = propertyIri,
value = valueWithRealStandoffLinkIris,
newValueIri = newValueIri,
linkUpdates = Seq.empty[
SparqlTemplateLinkUpdate
], // This is empty because we have to generate SPARQL for standoff links separately.
maybeComment = valueToCreate.createValueV1WithComment.comment,
valueCreator = userIri,
valuePermissions = defaultPropertyAccessPermissions,
creationDate = createMultipleValuesRequest.creationDate,
maybeValueHasOrder = Some(valueToCreate.valueHasOrder),
stringFormatter = stringFormatter
)
.toString()
}
// For each value of the property, accumulate the generated SPARQL and an UnverifiedValueV1
// in the SparqlGenerationResultForProperty.
propertyAcc.copy(
insertSparql = propertyAcc.insertSparql :+ insertSparql,
valuesToVerify = propertyAcc.valuesToVerify :+ UnverifiedValueV1(
newValueIri = newValueIri,
value = updateValueV1
),
valueIndexes = propertyAcc.valueIndexes :+ valueToCreate.valueIndex
)
}
(propertyIri, sparqlGenerationResultForProperty)
}
// Concatenate all the generated SPARQL into one string for the WHERE clause and one string for the INSERT clause, sorting
// the values by their indexes.
resultsForAllProperties: Iterable[SparqlGenerationResultForProperty] = sparqlGenerationResults.values
// The SPARQL for the INSERT clause also contains the SPARQL that was generated to insert standoff links.
allInsertSparql: String = resultsForAllProperties
.flatMap(result => result.insertSparql.zip(result.valueIndexes))
.toSeq
.sortBy(_._2)
.map(_._1)
.mkString("\n\n") + standoffLinkInsertSparql
// Collect all the UnverifiedValueV1s for each property.
allUnverifiedValues: Map[IRI, Seq[UnverifiedValueV1]] =
sparqlGenerationResults.map { case (propertyIri, results) =>
propertyIri -> results.valuesToVerify
}
} yield GenerateSparqlToCreateMultipleValuesResponseV1(
insertSparql = allInsertSparql,
unverifiedValues = allUnverifiedValues
)
}
for {
// Don't allow anonymous users to create resources.
userIri <- Future {
if (createMultipleValuesRequest.userProfile.isAnonymousUser) {
throw ForbiddenException("Anonymous users aren't allowed to create resources")
} else {
createMultipleValuesRequest.userProfile.id
}
}
// Do the remaining pre-update checks and the update while holding an update lock on the resource.
taskResult <- IriLocker.runWithIriLock(
createMultipleValuesRequest.apiRequestID,
createMultipleValuesRequest.resourceIri,
() => makeTaskFuture(userIri)
)
} yield taskResult
}
/**
* Verifies the creation of multiple values.
*
* @param verifyRequest a [[VerifyMultipleValueCreationRequestV1]].
* @return a [[VerifyMultipleValueCreationResponseV1]] if all values were created successfully, or a failed
* future if any values were not created.
*/
private def verifyMultipleValueCreation(
verifyRequest: VerifyMultipleValueCreationRequestV1
): Future[VerifyMultipleValueCreationResponseV1] = {
// We have a Map of property IRIs to sequences of UnverifiedCreateValueResponseV1s. Query each value and
// build a Map with the same structure, except that instead of UnverifiedCreateValueResponseV1s, it contains Futures
// providing the results of querying the values.
val valueVerificationFutures: Map[IRI, Future[Seq[CreateValueResponseV1]]] = verifyRequest.unverifiedValues.map {
case (propertyIri: IRI, unverifiedValues: Seq[UnverifiedValueV1]) =>
val valueVerificationResponsesForProperty = unverifiedValues.map { unverifiedValue =>
verifyValueCreation(
resourceIri = verifyRequest.resourceIri,
propertyIri = propertyIri,
unverifiedValue = unverifiedValue,
userProfile = verifyRequest.userProfile
)
}
propertyIri -> Future.sequence(valueVerificationResponsesForProperty)
}
// Convert our Map full of Futures into one Future, which will provide a Map of all the results
// when they're available.
for {
valueVerificationResponses: Map[IRI, Seq[CreateValueResponseV1]] <- ActorUtil.sequenceFutureSeqsInMap(
valueVerificationFutures
)
} yield VerifyMultipleValueCreationResponseV1(verifiedValues = valueVerificationResponses)
}
/**
* Adds a new version of an existing file value.
*
* @param changeFileValueRequest a [[ChangeFileValueRequestV1]] sent by the values route.
* @return a [[ChangeFileValueResponseV1]] representing all the changed file values.
*/
private def changeFileValueV1(changeFileValueRequest: ChangeFileValueRequestV1): Future[ChangeFileValueResponseV1] = {
/**
* Temporary structure to represent existing file values of a resource.
*
* @param property the property IRI (e.g., hasStillImageFileValueRepresentation)
* @param valueObjectIri the IRI of the value object.
* @param quality the quality of the file value
*/
case class CurrentFileValue(property: IRI, valueObjectIri: IRI, quality: Option[Int])
/**
* Changes a file value in the triplestore.
*
* @param changeFileValueRequest a [[ChangeFileValueRequestV1]] sent by the values route.
* @param projectADM the project in which the value is being updated.
* @return a [[ChangeFileValueResponseV1]] representing all the changed file values.
*/
def makeTaskFuture(
changeFileValueRequest: ChangeFileValueRequestV1,
projectADM: ProjectADM
): Future[ChangeFileValueResponseV1] = {
val fileValueContent: FileValueContentV2 = changeFileValueRequest.file.toFileValueContentV2
// get the Iris of the current file value(s)
val triplestoreUpdateFuture = for {
resourceIri <- Future(changeFileValueRequest.resourceIri)
getFileValuesSparql = org.knora.webapi.messages.twirl.queries.sparql.v1.txt
.getFileValuesForResource(
resourceIri = resourceIri
)
.toString()
// _ = print(getFileValuesSparql)
getFileValuesResponse: SparqlSelectResult <- appActor
.ask(SparqlSelectRequest(getFileValuesSparql))
.mapTo[SparqlSelectResult]
// _ <- Future(println(getFileValuesResponse))
// check that the resource to be updated exists and it is a subclass of knora-base:Representation
_ =
if (getFileValuesResponse.results.bindings.isEmpty)
throw NotFoundException(
s"Value ${changeFileValueRequest.resourceIri} not found (it may have been deleted) or it is not a knora-base:Representation"
)
// get the property Iris, file value Iris and qualities attached to the resource
fileValues: Seq[CurrentFileValue] = getFileValuesResponse.results.bindings.map { row: VariableResultsRow =>
CurrentFileValue(
property = row.rowMap("p"),
valueObjectIri = row.rowMap("fileValueIri"),
quality = row.rowMap.get("quality") match {
case Some(quality: String) => Some(quality.toInt)
case None => None
}
)
}
// TODO: check if the file type returned by Sipi corresponds to the already existing file value type
response: ChangeValueResponseV1 <- changeValueV1(
ChangeValueRequestV1(
valueIri = fileValues.head.valueObjectIri,
value = changeFileValueRequest.file,
userProfile = changeFileValueRequest.userProfile,
apiRequestID = changeFileValueRequest.apiRequestID // re-use the same id
)
)
changedLocation = response.value match {
case fileValueV1: FileValueV1 => valueUtilV1.fileValueV12LocationV1(fileValueV1)
case other =>
throw AssertionException(
s"Expected Sipi to change a file value, but it changed one of these: ${other.valueTypeIri}"
)
}
} yield ChangeFileValueResponseV1(
locations = Vector(changedLocation),
projectADM = projectADM
)
ResourceUtilV2.doSipiPostUpdate(
updateFuture = triplestoreUpdateFuture,
valueContent = fileValueContent,
requestingUser = changeFileValueRequest.userProfile,
appActor = appActor,
log = log
)
}
for {
resourceInfoResponse <- appActor
.ask(
ResourceInfoGetRequestV1(
iri = changeFileValueRequest.resourceIri,
userProfile = changeFileValueRequest.userProfile
)
)
.mapTo[ResourceInfoResponseV1]
// Get project info
projectResponse <-
appActor
.ask(
ProjectGetRequestADM(identifier =
IriIdentifier
.fromString(resourceInfoResponse.resource_info.get.project_id)
.getOrElseWith(e => throw BadRequestException(e.head.getMessage))
)
)
.mapTo[ProjectGetResponseADM]
// Do the preparations of a file value change while already holding an update lock on the resource.
// This is necessary because in `makeTaskFuture` the current file value Iris for the given resource IRI have to been retrieved.
// Using the lock, we make sure that these are still up to date when `changeValueV1` is being called.
//
// The method `changeValueV1` will be called using the same lock.
taskResult <- IriLocker.runWithIriLock(
changeFileValueRequest.apiRequestID,
changeFileValueRequest.resourceIri,
() => makeTaskFuture(changeFileValueRequest, projectResponse.project)
)
} yield taskResult
}
/**
* Adds a new version of an existing value.
*
* @param changeValueRequest the request message.
* @return an [[ChangeValueResponseV1]] if the update was successful.
*/
private def changeValueV1(changeValueRequest: ChangeValueRequestV1): Future[ChangeValueResponseV1] = {
/**
* Creates a [[Future]] that does pre-update checks and performs the update. This function will be
* called by [[IriLocker]] once it has acquired an update lock on the resource.
*
* @param userIri the IRI of the user making the request.
* @param findResourceWithValueResult a [[FindResourceWithValueResult]] indicating which resource contains the value
* to be updated.
* @return a [[Future]] that does pre-update checks and performs the update.
*/
def makeTaskFuture(
userIri: IRI,
findResourceWithValueResult: FindResourceWithValueResult
): Future[ChangeValueResponseV1] = {
// If we're updating a link, findResourceWithValueResult will contain the IRI of the property that points to the
// knora-base:LinkValue, but we'll need the IRI of the corresponding link property.
val propertyIri = changeValueRequest.value match {
case _: LinkUpdateV1 =>
stringFormatter.linkValuePropertyIriToLinkPropertyIri(findResourceWithValueResult.propertyIri)
case _ => findResourceWithValueResult.propertyIri
}
if (propertyIri == OntologyConstants.KnoraBase.HasStandoffLinkTo) {
throw BadRequestException("Standoff links can be changed only by submitting a new text value")
}
for {
// Ensure that the user has permission to modify the value.
maybeCurrentValueQueryResult: Option[ValueQueryResult] <-
changeValueRequest.value match {
case _: LinkUpdateV1 =>
// We're being asked to update a link. We expect the current value version IRI to point to a
// knora-base:LinkValue. Get all necessary information about the LinkValue and the corresponding
// direct link.
findLinkValueByIri(
subjectIri = findResourceWithValueResult.resourceIri,
predicateIri = propertyIri,
objectIri = None,
linkValueIri = changeValueRequest.valueIri,
userProfile = changeValueRequest.userProfile
)
case _ =>
// We're being asked to update an ordinary value.
findValue(
valueIri = changeValueRequest.valueIri,
userProfile = changeValueRequest.userProfile
)
}
currentValueQueryResult =
maybeCurrentValueQueryResult.getOrElse(
throw NotFoundException(s"Value ${changeValueRequest.valueIri} not found (it may have been deleted)")
)
_ = if (
!PermissionUtilADM.impliesPermissionCodeV1(
userHasPermissionCode = Some(currentValueQueryResult.permissionCode),
userNeedsPermission = OntologyConstants.KnoraBase.ModifyPermission
)
) {
throw ForbiddenException(
s"User $userIri does not have permission to add a new version to value ${changeValueRequest.valueIri}"
)
}
// Check that the submitted value has the correct type for the property.
entityInfoResponse <- appActor
.ask(
EntityInfoGetRequestV1(
propertyIris = Set(propertyIri),
userProfile = changeValueRequest.userProfile
)
)
.mapTo[EntityInfoGetResponseV1]
propertyInfo = entityInfoResponse.propertyInfoMap(propertyIri)
propertyObjectClassConstraint = propertyInfo
.getPredicateObject(OntologyConstants.KnoraBase.ObjectClassConstraint)
.getOrElse {
throw InconsistentRepositoryDataException(
s"Property $propertyIri has no knora-base:objectClassConstraint"
)
}
// Check that the object of the property (the value to be updated, or the target of the link to be updated) will have
// the correct type for the property's knora-base:objectClassConstraint.
_ <- checkPropertyObjectClassConstraintForValue(
propertyIri = propertyIri,
propertyObjectClassConstraint = propertyObjectClassConstraint,
updateValueV1 = changeValueRequest.value,
userProfile = changeValueRequest.userProfile
)
// Check that the current value and the submitted value have the same type.
_ = if (currentValueQueryResult.value.valueTypeIri != changeValueRequest.value.valueTypeIri) {
throw BadRequestException(
s"Value ${changeValueRequest.valueIri} has type ${currentValueQueryResult.value.valueTypeIri}, but the submitted new version has type ${changeValueRequest.value.valueTypeIri}"
)
}
// Make sure the new version would not be redundant, given the current version.
_ = if (changeValueRequest.value.isRedundant(currentValueQueryResult.value)) {
throw DuplicateValueException("The submitted value is the same as the current version")
}
// Get details of the resource. (We do this as late as possible because it's slower than the other checks,
// and there's no point in doing it if the other checks fail.)
resourceFullResponse <- appActor
.ask(
ResourceFullGetRequestV1(
iri = findResourceWithValueResult.resourceIri,
userADM = changeValueRequest.userProfile,
getIncoming = false
)
)
.mapTo[ResourceFullResponseV1]
_ = changeValueRequest.value match {
case _: FileValueV1 => () // It is a file value, do not check for duplicates.
case _ => // It is not a file value.
// Ensure that adding the new value version would not create a duplicate value. This works in API v1 because a
// ResourceFullResponseV1 contains only the values that the user is allowed to see, otherwise checking for
// duplicate values would be a security risk. We'll have to implement this in a different way in API v2.
resourceFullResponse.props.flatMap(_.properties.find(_.pid == propertyIri)) match {
case Some(prop: PropertyV1) =>
// Don't consider the current value version when looking for duplicates.
val filteredValues =
prop.value_ids.zip(prop.values).filter(_._1 != changeValueRequest.valueIri).map(_._2)
if (