/
ValuesResponderV2.scala
2258 lines (1960 loc) · 125 KB
/
ValuesResponderV2.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-2019 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.responders.v2
import java.time.Instant
import java.util.UUID
import akka.http.scaladsl.util.FastFuture
import akka.pattern._
import org.knora.webapi._
import org.knora.webapi.exceptions._
import org.knora.webapi.messages.IriConversions._
import org.knora.webapi.messages.admin.responder.permissionsmessages.{PermissionADM, PermissionType}
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.PermissionUtilADM._
import org.knora.webapi.messages.util.search.gravsearch.GravsearchParser
import org.knora.webapi.messages.util.{KnoraSystemInstances, PermissionUtilADM, ResponderData}
import org.knora.webapi.messages.v2.responder.SuccessResponseV2
import org.knora.webapi.messages.v2.responder.ontologymessages._
import org.knora.webapi.messages.v2.responder.resourcemessages._
import org.knora.webapi.messages.v2.responder.searchmessages.GravsearchRequestV2
import org.knora.webapi.messages.v2.responder.valuemessages._
import org.knora.webapi.messages.{OntologyConstants, SmartIri}
import org.knora.webapi.responders.Responder.handleUnexpectedMessage
import org.knora.webapi.responders.{IriLocker, Responder}
import org.knora.webapi.util.ActorUtil
import scala.concurrent.Future
/**
* Handles requests to read and write Knora values.
*/
class ValuesResponderV2(responderData: ResponderData) extends Responder(responderData) {
/**
* The IRI and content of a new value or value version whose existence in the triplestore has been verified.
*
* @param newValueIri the IRI that was assigned to the new value.
* @param value the content of the new value.
* @param permissions the permissions attached to the new value.
*/
private case class VerifiedValueV2(newValueIri: IRI, value: ValueContentV2, permissions: String)
/**
* Receives a message of type [[ValuesResponderRequestV2]], and returns an appropriate response message.
*/
def receive(msg: ValuesResponderRequestV2) = msg match {
case createValueRequest: CreateValueRequestV2 => createValueV2(createValueRequest)
case updateValueRequest: UpdateValueRequestV2 => updateValueV2(updateValueRequest)
case deleteValueRequest: DeleteValueRequestV2 => deleteValueV2(deleteValueRequest)
case createMultipleValuesRequest: GenerateSparqlToCreateMultipleValuesRequestV2 => generateSparqlToCreateMultipleValuesV2(createMultipleValuesRequest)
case other => handleUnexpectedMessage(other, log, this.getClass.getName)
}
/**
* Creates a new value in an existing resource.
*
* @param createValueRequest the request to create the value.
* @return a [[CreateValueResponseV2]].
*/
private def createValueV2(createValueRequest: CreateValueRequestV2): Future[CreateValueResponseV2] = {
def makeTaskFuture: Future[CreateValueResponseV2] = {
for {
// Convert the submitted value to the internal schema.
submittedInternalPropertyIri: SmartIri <- Future(createValueRequest.createValue.propertyIri.toOntologySchema(InternalSchema))
submittedInternalValueContent: ValueContentV2 = createValueRequest.createValue.valueContent.toOntologySchema(InternalSchema)
// Get ontology information about the submitted property.
propertyInfoRequestForSubmittedProperty = PropertiesGetRequestV2(
propertyIris = Set(submittedInternalPropertyIri),
allLanguages = false,
requestingUser = createValueRequest.requestingUser
)
propertyInfoResponseForSubmittedProperty: ReadOntologyV2 <- (responderManager ? propertyInfoRequestForSubmittedProperty).mapTo[ReadOntologyV2]
propertyInfoForSubmittedProperty: ReadPropertyInfoV2 = propertyInfoResponseForSubmittedProperty.properties(submittedInternalPropertyIri)
// Don't accept link properties.
_ = if (propertyInfoForSubmittedProperty.isLinkProp) {
throw BadRequestException(s"Invalid property <${createValueRequest.createValue.propertyIri}>. Use a link value property to submit a link.")
}
// Don't accept knora-api:hasStandoffLinkToValue.
_ = if (createValueRequest.createValue.propertyIri.toString == OntologyConstants.KnoraApiV2Complex.HasStandoffLinkToValue) {
throw BadRequestException(s"Values of <${createValueRequest.createValue.propertyIri}> cannot be created directly")
}
// Make an adjusted version of the submitted property: if it's a link value property, substitute the
// corresponding link property, whose objects we will need to query. Get ontology information about the
// adjusted property.
adjustedInternalPropertyInfo: ReadPropertyInfoV2 <- getAdjustedInternalPropertyInfo(
submittedPropertyIri = createValueRequest.createValue.propertyIri,
maybeSubmittedValueType = Some(createValueRequest.createValue.valueContent.valueType),
propertyInfoForSubmittedProperty = propertyInfoForSubmittedProperty,
requestingUser = createValueRequest.requestingUser
)
adjustedInternalPropertyIri = adjustedInternalPropertyInfo.entityInfoContent.propertyIri
// Get the resource's metadata and relevant property objects, using the adjusted property. Do this as the system user,
// so we can see objects that the user doesn't have permission to see.
resourceInfo: ReadResourceV2 <- getResourceWithPropertyValues(
resourceIri = createValueRequest.createValue.resourceIri,
propertyInfo = adjustedInternalPropertyInfo,
requestingUser = KnoraSystemInstances.Users.SystemUser
)
// Check that the user has permission to modify the resource.
_ = ResourceUtilV2.checkResourcePermission(
resourceInfo = resourceInfo,
permissionNeeded = ModifyPermission,
requestingUser = createValueRequest.requestingUser
)
// Check that the resource has the rdf:type that the client thinks it has.
_ = if (resourceInfo.resourceClassIri != createValueRequest.createValue.resourceClassIri.toOntologySchema(InternalSchema)) {
throw BadRequestException(s"The rdf:type of resource <${createValueRequest.createValue.resourceIri}> is not <${createValueRequest.createValue.resourceClassIri}>")
}
// Get the definition of the resource class.
classInfoRequest = ClassesGetRequestV2(
classIris = Set(resourceInfo.resourceClassIri),
allLanguages = false,
requestingUser = createValueRequest.requestingUser
)
classInfoResponse: ReadOntologyV2 <- (responderManager ? classInfoRequest).mapTo[ReadOntologyV2]
// Check that the resource class has a cardinality for the submitted property.
classInfo: ReadClassInfoV2 = classInfoResponse.classes(resourceInfo.resourceClassIri)
cardinalityInfo: Cardinality.KnoraCardinalityInfo = classInfo.allCardinalities.getOrElse(submittedInternalPropertyIri, throw BadRequestException(s"Resource <${createValueRequest.createValue.resourceIri}> belongs to class <${resourceInfo.resourceClassIri.toOntologySchema(ApiV2Complex)}>, which has no cardinality for property <${createValueRequest.createValue.propertyIri}>"))
// Check that the object of the adjusted property (the value to be created, or the target of the link to be created) will have
// the correct type for the adjusted property's knora-base:objectClassConstraint.
_ <- checkPropertyObjectClassConstraint(
propertyInfo = adjustedInternalPropertyInfo,
valueContent = submittedInternalValueContent,
requestingUser = createValueRequest.requestingUser
)
// If this is a list value, check that it points to a real list node.
_ <- submittedInternalValueContent match {
case listValue: HierarchicalListValueContentV2 => ResourceUtilV2.checkListNodeExists(listValue.valueHasListNode, storeManager)
case _ => FastFuture.successful(())
}
// Check that the resource class's cardinality for the submitted property allows another value to be added
// for that property.
currentValuesForProp: Seq[ReadValueV2] = resourceInfo.values.getOrElse(submittedInternalPropertyIri, Seq.empty[ReadValueV2])
_ = if ((cardinalityInfo.cardinality == Cardinality.MustHaveOne || cardinalityInfo.cardinality == Cardinality.MustHaveSome) && currentValuesForProp.isEmpty) {
throw InconsistentTriplestoreDataException(s"Resource class <${resourceInfo.resourceClassIri.toOntologySchema(ApiV2Complex)}> has a cardinality of ${cardinalityInfo.cardinality} on property <${createValueRequest.createValue.propertyIri}>, but resource <${createValueRequest.createValue.resourceIri}> has no value for that property")
}
_ = if (cardinalityInfo.cardinality == Cardinality.MustHaveOne || (cardinalityInfo.cardinality == Cardinality.MayHaveOne && currentValuesForProp.nonEmpty)) {
throw OntologyConstraintException(s"Resource class <${resourceInfo.resourceClassIri.toOntologySchema(ApiV2Complex)}> has a cardinality of ${cardinalityInfo.cardinality} on property <${createValueRequest.createValue.propertyIri}>, and this does not allow a value to be added for that property to resource <${createValueRequest.createValue.resourceIri}>")
}
// Check that the new value would not duplicate an existing value.
unescapedSubmittedInternalValueContent = submittedInternalValueContent.unescape
_ = if (currentValuesForProp.exists(currentVal => unescapedSubmittedInternalValueContent.wouldDuplicateOtherValue(currentVal.valueContent))) {
throw DuplicateValueException()
}
// If this is a text value, check that the resources pointed to by any standoff link tags exist
// and that the user has permission to see them.
_ <- submittedInternalValueContent match {
case textValueContent: TextValueContentV2 => checkResourceIris(textValueContent.standoffLinkTagTargetResourceIris, createValueRequest.requestingUser)
case _ => FastFuture.successful(())
}
// Get the default permissions for the new value.
defaultValuePermissions: String <- ResourceUtilV2.getDefaultValuePermissions(
projectIri = resourceInfo.projectADM.id,
resourceClassIri = resourceInfo.resourceClassIri,
propertyIri = submittedInternalPropertyIri,
requestingUser = createValueRequest.requestingUser,
responderManager = responderManager
)
// Did the user submit permissions for the new value?
newValuePermissionLiteral <- createValueRequest.createValue.permissions match {
case Some(permissions: String) =>
// Yes. Validate them.
for {
validatedCustomPermissions <- PermissionUtilADM.validatePermissions(permissionLiteral = permissions, responderManager = responderManager)
// Is the requesting user a system admin, or an admin of this project?
_ = if (!(createValueRequest.requestingUser.permissions.isProjectAdmin(createValueRequest.requestingUser.id) || createValueRequest.requestingUser.permissions.isSystemAdmin)) {
// No. Make sure they don't give themselves higher permissions than they would get from the default permissions.
val permissionComparisonResult: PermissionComparisonResult = PermissionUtilADM.comparePermissionsADM(
entityCreator = createValueRequest.requestingUser.id,
entityProject = resourceInfo.projectADM.id,
permissionLiteralA = validatedCustomPermissions,
permissionLiteralB = defaultValuePermissions,
requestingUser = createValueRequest.requestingUser
)
if (permissionComparisonResult == AGreaterThanB) {
throw ForbiddenException(s"The specified value permissions would give a value's creator a higher permission on the value than the default permissions")
}
}
} yield validatedCustomPermissions
case None =>
// No. Use the default permissions.
FastFuture.successful(defaultValuePermissions)
}
dataNamedGraph: IRI = stringFormatter.projectDataNamedGraphV2(resourceInfo.projectADM)
// Create the new value.
unverifiedValue <- createValueV2AfterChecks(
dataNamedGraph = dataNamedGraph,
projectIri = resourceInfo.projectADM.id,
resourceInfo = resourceInfo,
propertyIri = adjustedInternalPropertyIri,
value = submittedInternalValueContent,
valueIri = createValueRequest.createValue.valueIri,
valueUUID = createValueRequest.createValue.valueUUID,
valueCreationDate = createValueRequest.createValue.valueCreationDate,
valueCreator = createValueRequest.requestingUser.id,
valuePermissions = newValuePermissionLiteral,
requestingUser = createValueRequest.requestingUser
)
// Check that the value was written correctly to the triplestore.
verifiedValue: VerifiedValueV2 <- verifyValue(
resourceIri = createValueRequest.createValue.resourceIri,
propertyIri = submittedInternalPropertyIri,
unverifiedValue = unverifiedValue,
requestingUser = createValueRequest.requestingUser
)
} yield CreateValueResponseV2(
valueIri = verifiedValue.newValueIri,
valueType = verifiedValue.value.valueType,
valueUUID = unverifiedValue.newValueUUID,
valueCreationDate = unverifiedValue.creationDate,
projectADM = resourceInfo.projectADM
)
}
val triplestoreUpdateFuture: Future[CreateValueResponseV2] = for {
// Don't allow anonymous users to create values.
_ <- Future {
if (createValueRequest.requestingUser.isAnonymousUser) {
throw ForbiddenException("Anonymous users aren't allowed to create values")
} else {
createValueRequest.requestingUser.id
}
}
// Do the remaining pre-update checks and the update while holding an update lock on the resource.
taskResult <- IriLocker.runWithIriLock(
createValueRequest.apiRequestID,
createValueRequest.createValue.resourceIri,
() => makeTaskFuture
)
} yield taskResult
// Since PR #1230, the cardinalities in knora-base don't allow you to create a file value
// without creating a new resource, but we leave this line here in case it's needed again
// someday:
//
// If we were creating a file value, have Sipi move the file to permanent storage if the update
// was successful, or delete the temporary file if the update failed.
ResourceUtilV2.doSipiPostUpdate(
updateFuture = triplestoreUpdateFuture,
valueContent = createValueRequest.createValue.valueContent,
requestingUser = createValueRequest.requestingUser,
responderManager = responderManager,
storeManager = storeManager,
log = log
)
}
/**
* Creates a new value (either an ordinary value or a link), using an existing transaction, assuming that
* pre-update checks have already been done.
*
* @param dataNamedGraph the named graph in which the value is to be created.
* @param projectIri the IRI of the project in which to create the value.
* @param resourceInfo information about the the resource in which to create the value.
* @param propertyIri the IRI of the property that will point from the resource to the value, or, if
* the value is a link value, the IRI of the link property.
* @param value the value to create.
* @param valueIri the optional custom IRI supplied for the value.
* @param valueUUID the optional custom UUID supplied for the value.
* @param valueCreationDate the optional custom creation date supplied for the value.
* @param valueCreator the IRI of the new value's owner.
* @param valuePermissions the literal that should be used as the object of the new value's
* `knora-base:hasPermissions` predicate.
* @param requestingUser the user making the request.
* @return an [[UnverifiedValueV2]].
*/
private def createValueV2AfterChecks(dataNamedGraph: IRI,
projectIri: IRI,
resourceInfo: ReadResourceV2,
propertyIri: SmartIri,
value: ValueContentV2,
valueIri: Option[SmartIri],
valueUUID: Option[UUID],
valueCreationDate: Option[Instant],
valueCreator: IRI,
valuePermissions: String,
requestingUser: UserADM): Future[UnverifiedValueV2] = {
value match {
case linkValueContent: LinkValueContentV2 =>
createLinkValueV2AfterChecks(
dataNamedGraph = dataNamedGraph,
resourceInfo = resourceInfo,
linkPropertyIri = propertyIri,
linkValueContent = linkValueContent,
maybeValueIri = valueIri,
maybeValueUUID = valueUUID,
maybeCreationDate = valueCreationDate,
valueCreator = valueCreator,
valuePermissions = valuePermissions,
requestingUser = requestingUser
)
case ordinaryValueContent =>
createOrdinaryValueV2AfterChecks(
dataNamedGraph = dataNamedGraph,
resourceInfo = resourceInfo,
propertyIri = propertyIri,
value = ordinaryValueContent,
maybeValueIri = valueIri,
maybeValueUUID = valueUUID,
maybeValueCreationDate = valueCreationDate,
valueCreator = valueCreator,
valuePermissions = valuePermissions,
requestingUser = requestingUser
)
}
}
/**
* Creates an ordinary value (i.e. not a link), using an existing transaction, assuming that pre-update checks have already been done.
*
* @param resourceInfo information about the the resource in which to create the value.
* @param propertyIri the property that should point to the value.
* @param value an [[ValueContentV2]] describing the value.
* @param maybeValueIri the optional custom IRI supplied for the value.
* @param maybeValueUUID the optional custom UUID supplied for the value.
* @param maybeValueCreationDate the optional custom creation date supplied for the value.
* @param valueCreator the IRI of the new value's owner.
* @param valuePermissions the literal that should be used as the object of the new value's `knora-base:hasPermissions` predicate.
* @param requestingUser the user making the request.
* @return an [[UnverifiedValueV2]].
*/
private def createOrdinaryValueV2AfterChecks(dataNamedGraph: IRI,
resourceInfo: ReadResourceV2,
propertyIri: SmartIri,
value: ValueContentV2,
maybeValueIri: Option[SmartIri],
maybeValueUUID: Option[UUID],
maybeValueCreationDate: Option[Instant],
valueCreator: IRI,
valuePermissions: String,
requestingUser: UserADM): Future[UnverifiedValueV2] = {
for {
// Make an IRI for the new value.
newValueIri: IRI <- checkOrCreateEntityIri(maybeValueIri, stringFormatter.makeRandomValueIri(resourceInfo.resourceIri))
// Make a UUID for the new value
newValueUUID: UUID = maybeValueUUID match {
case Some(customValueUUID) => customValueUUID
case None => UUID.randomUUID
}
// Make a creation date for the new value
creationDate: Instant = maybeValueCreationDate match {
case Some(customCreationDate) => customCreationDate
case None => Instant.now
}
// If we're creating a text value, update direct links and LinkValues for any resource references in standoff.
standoffLinkUpdates <- value match {
case textValueContent: TextValueContentV2 =>
// Construct a SparqlTemplateLinkUpdate for each reference that was added.
val linkUpdateFutures: Seq[Future[SparqlTemplateLinkUpdate]] = textValueContent.standoffLinkTagTargetResourceIris.map {
targetResourceIri: IRI =>
incrementLinkValue(
sourceResourceInfo = resourceInfo,
linkPropertyIri = OntologyConstants.KnoraBase.HasStandoffLinkTo.toSmartIri,
targetResourceIri = targetResourceIri,
valueCreator = OntologyConstants.KnoraAdmin.SystemUser,
valuePermissions = standoffLinkValuePermissions,
requestingUser = requestingUser
)
}.toVector
Future.sequence(linkUpdateFutures)
case _ => FastFuture.successful(Vector.empty[SparqlTemplateLinkUpdate])
}
// Generate a SPARQL update string.
sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v2.txt.createValue(
dataNamedGraph = dataNamedGraph,
triplestore = settings.triplestoreType,
resourceIri = resourceInfo.resourceIri,
propertyIri = propertyIri,
newValueIri = newValueIri,
newValueUUID = newValueUUID,
value = value,
linkUpdates = standoffLinkUpdates,
valueCreator = valueCreator,
valuePermissions = valuePermissions,
creationDate = creationDate,
stringFormatter = stringFormatter
).toString()
/*
_ = println("================ Create value ================")
_ = println(sparqlUpdate)
_ = println("==============================================")
*/
// Do the update.
_ <- (storeManager ? SparqlUpdateRequest(sparqlUpdate)).mapTo[SparqlUpdateResponse]
} yield UnverifiedValueV2(
newValueIri = newValueIri,
newValueUUID = newValueUUID,
valueContent = value.unescape,
permissions = valuePermissions,
creationDate = creationDate
)
}
/**
* Creates a link, using an existing transaction, assuming that pre-update checks have already been done.
*
* @param dataNamedGraph the named graph in which the link is to be created.
* @param resourceInfo information about the the resource in which to create the value.
* @param linkPropertyIri the link property.
* @param linkValueContent a [[LinkValueContentV2]] specifying the target resource.
* @param maybeValueIri the optional custom IRI supplied for the value.
* @param maybeValueUUID the optional custom UUID supplied for the value.
* @param valueCreator the IRI of the new link value's owner.
* @param valuePermissions the literal that should be used as the object of the new link value's `knora-base:hasPermissions` predicate.
* @param requestingUser the user making the request.
* @return an [[UnverifiedValueV2]].
*/
private def createLinkValueV2AfterChecks(dataNamedGraph: IRI,
resourceInfo: ReadResourceV2,
linkPropertyIri: SmartIri,
linkValueContent: LinkValueContentV2,
maybeValueIri: Option[SmartIri],
maybeValueUUID: Option[UUID],
maybeCreationDate: Option[Instant],
valueCreator: IRI,
valuePermissions: String,
requestingUser: UserADM): Future[UnverifiedValueV2] = {
val newValueUUID: UUID = maybeValueUUID match {
case Some(customValueUUID) => customValueUUID
case None => UUID.randomUUID
}
for {
sparqlTemplateLinkUpdate <- incrementLinkValue(
sourceResourceInfo = resourceInfo,
linkPropertyIri = linkPropertyIri,
targetResourceIri = linkValueContent.referredResourceIri,
customNewLinkValueIri = maybeValueIri,
valueCreator = valueCreator,
valuePermissions = valuePermissions,
requestingUser = requestingUser
)
creationDate: Instant = maybeCreationDate match {
case Some(customValueCreationDate) => customValueCreationDate
case None => Instant.now
}
// Generate a SPARQL update string.
sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v2.txt.createLink(
dataNamedGraph = dataNamedGraph,
triplestore = settings.triplestoreType,
resourceIri = resourceInfo.resourceIri,
linkUpdate = sparqlTemplateLinkUpdate,
newValueUUID = newValueUUID,
creationDate = creationDate,
maybeComment = linkValueContent.comment,
stringFormatter = stringFormatter
).toString()
/*
_ = println("================ Create link ===============")
_ = println(sparqlUpdate)
_ = println("=============================================")
*/
// Do the update.
_ <- (storeManager ? SparqlUpdateRequest(sparqlUpdate)).mapTo[SparqlUpdateResponse]
} yield UnverifiedValueV2(
newValueIri = sparqlTemplateLinkUpdate.newLinkValueIri,
newValueUUID = newValueUUID,
valueContent = linkValueContent.unescape,
permissions = valuePermissions,
creationDate = creationDate
)
}
/**
* Represents SPARQL generated to create one of multiple values in a new resource.
*
* @param insertSparql the generated SPARQL.
* @param unverifiedValue an [[UnverifiedValueV2]] representing the value that is to be created.
*/
private case class InsertSparqlWithUnverifiedValue(insertSparql: String, unverifiedValue: UnverifiedValueV2)
/**
* Generates SPARQL for creating multiple values.
*
* @param createMultipleValuesRequest the request to create multiple values.
* @return a [[GenerateSparqlToCreateMultipleValuesResponseV2]] containing the generated SPARQL and information
* about the values to be created.
*/
private def generateSparqlToCreateMultipleValuesV2(createMultipleValuesRequest: GenerateSparqlToCreateMultipleValuesRequestV2): Future[GenerateSparqlToCreateMultipleValuesResponseV2] = {
for {
// Generate SPARQL to create links and LinkValues for standoff links in text values.
sparqlForStandoffLinks: Option[String] <- generateInsertSparqlForStandoffLinksInMultipleValues(createMultipleValuesRequest)
// Generate SPARQL for each value.
sparqlForPropertyValueFutures: Map[SmartIri, Seq[Future[InsertSparqlWithUnverifiedValue]]] = createMultipleValuesRequest.values.map {
case (propertyIri: SmartIri, valuesToCreate: Seq[GenerateSparqlForValueInNewResourceV2]) =>
propertyIri -> valuesToCreate.zipWithIndex.map {
case (valueToCreate: GenerateSparqlForValueInNewResourceV2, valueHasOrder: Int) =>
generateInsertSparqlWithUnverifiedValue(
resourceIri = createMultipleValuesRequest.resourceIri,
propertyIri = propertyIri,
valueToCreate = valueToCreate,
valueHasOrder = valueHasOrder,
resourceCreationDate = createMultipleValuesRequest.creationDate,
requestingUser = createMultipleValuesRequest.requestingUser
)
}
}
sparqlForPropertyValues: Map[SmartIri, Seq[InsertSparqlWithUnverifiedValue]] <- ActorUtil.sequenceSeqFuturesInMap(sparqlForPropertyValueFutures)
// Concatenate all the generated SPARQL.
allInsertSparql: String = sparqlForPropertyValues.values.flatten.map(_.insertSparql).mkString("\n\n") + "\n\n" + sparqlForStandoffLinks.getOrElse("")
// Collect all the unverified values.
unverifiedValues: Map[SmartIri, Seq[UnverifiedValueV2]] = sparqlForPropertyValues.map {
case (propertyIri, unverifiedValuesWithSparql) => propertyIri -> unverifiedValuesWithSparql.map(_.unverifiedValue)
}
} yield GenerateSparqlToCreateMultipleValuesResponseV2(
insertSparql = allInsertSparql,
unverifiedValues = unverifiedValues,
hasStandoffLink = sparqlForStandoffLinks.isDefined
)
}
/**
* Generates SPARQL to create one of multiple values in a new resource.
*
* @param resourceIri the IRI of the resource.
* @param propertyIri the IRI of the property that will point to the value.
* @param valueToCreate the value to be created.
* @param valueHasOrder the value's `knora-base:valueHasOrder`.
* @param resourceCreationDate the creation date of the resource.
* @param requestingUser the user making the request.
* @return a [[InsertSparqlWithUnverifiedValue]] containing the generated SPARQL and an [[UnverifiedValueV2]].
*/
private def generateInsertSparqlWithUnverifiedValue(resourceIri: IRI,
propertyIri: SmartIri,
valueToCreate: GenerateSparqlForValueInNewResourceV2,
valueHasOrder: Int,
resourceCreationDate: Instant,
requestingUser: UserADM): Future[InsertSparqlWithUnverifiedValue] = {
for {
newValueIri: IRI <- checkOrCreateEntityIri(valueToCreate.customValueIri, stringFormatter.makeRandomValueIri(resourceIri))
// Make a UUID for the new value.
newValueUUID: UUID = valueToCreate.customValueUUID match {
case Some(customValueUUID) => customValueUUID
case None => UUID.randomUUID
}
// Make a creation date for the value. If a custom creation date is given for a value, consider that otherwise
// use resource creation date for the value.
valueCreationDate: Instant = valueToCreate.customValueCreationDate match {
case Some(customValueCreationDate) => customValueCreationDate
case None => resourceCreationDate
}
// Generate the SPARQL.
insertSparql: String = valueToCreate.valueContent match {
case linkValueContentV2: LinkValueContentV2 =>
// We're creating a link.
// Construct a SparqlTemplateLinkUpdate to tell the SPARQL template how to create
// the link and its LinkValue.
val sparqlTemplateLinkUpdate = SparqlTemplateLinkUpdate(
linkPropertyIri = propertyIri.fromLinkValuePropToLinkProp,
directLinkExists = false,
insertDirectLink = true,
deleteDirectLink = false,
linkValueExists = false,
linkTargetExists = linkValueContentV2.referredResourceExists,
newLinkValueIri = newValueIri,
linkTargetIri = linkValueContentV2.referredResourceIri,
currentReferenceCount = 0,
newReferenceCount = 1,
newLinkValueCreator = requestingUser.id,
newLinkValuePermissions = valueToCreate.permissions
)
// Generate SPARQL for the link.
org.knora.webapi.messages.twirl.queries.sparql.v2.txt.generateInsertStatementsForCreateLink(
resourceIri = resourceIri,
linkUpdate = sparqlTemplateLinkUpdate,
creationDate = valueCreationDate,
newValueUUID = newValueUUID,
maybeComment = valueToCreate.valueContent.comment,
maybeValueHasOrder = Some(valueHasOrder),
stringFormatter = stringFormatter
).toString()
case otherValueContentV2 =>
// We're creating an ordinary value. Generate SPARQL for it.
org.knora.webapi.messages.twirl.queries.sparql.v2.txt.generateInsertStatementsForCreateValue(
resourceIri = resourceIri,
propertyIri = propertyIri,
value = otherValueContentV2,
newValueIri = newValueIri,
newValueUUID = newValueUUID,
linkUpdates = Seq.empty[SparqlTemplateLinkUpdate], // This is empty because we have to generate SPARQL for standoff links separately.
valueCreator = requestingUser.id,
valuePermissions = valueToCreate.permissions,
creationDate = valueCreationDate,
maybeValueHasOrder = Some(valueHasOrder),
stringFormatter = stringFormatter
).toString()
}
} yield InsertSparqlWithUnverifiedValue(
insertSparql = insertSparql,
unverifiedValue = UnverifiedValueV2(
newValueIri = newValueIri,
newValueUUID = newValueUUID,
valueContent = valueToCreate.valueContent.unescape,
permissions = valueToCreate.permissions,
creationDate = valueCreationDate
)
)
}
/**
* When processing a request to create multiple values, generates SPARQL for standoff links in text values.
*
* @param createMultipleValuesRequest the request to create multiple values.
* @return SPARQL INSERT statements.
*/
private def generateInsertSparqlForStandoffLinksInMultipleValues(createMultipleValuesRequest: GenerateSparqlToCreateMultipleValuesRequestV2): Future[Option[String]] = {
// To create LinkValues for the standoff links 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 links to a particular target resource.
// First, get the standoff link targets from all the text values to be created.
val standoffLinkTargetsPerTextValue: Vector[Set[IRI]] = createMultipleValuesRequest.flatValues.foldLeft(Vector.empty[Set[IRI]]) {
case (standoffLinkTargetsAcc: Vector[Set[IRI]], createValueV2: GenerateSparqlForValueInNewResourceV2) =>
createValueV2.valueContent match {
case textValueContentV2: TextValueContentV2 if textValueContentV2.standoffLinkTagTargetResourceIris.nonEmpty =>
standoffLinkTargetsAcc :+ textValueContentV2.standoffLinkTagTargetResourceIris
case _ => standoffLinkTargetsAcc
}
}
if (standoffLinkTargetsPerTextValue.nonEmpty) {
// Combine those resource references into a single list, so if there are n text values with a link to
// some IRI, the list will contain that IRI n times.
val allStandoffLinkTargets: Vector[IRI] = standoffLinkTargetsPerTextValue.flatten
// Now we need to count the number of times each IRI occurs in allStandoffLinkTargets. 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, Vector[IRI]] in which each
// IRI points to a sequence of the same IRI repeated as many times as it occurred in allStandoffLinkTargets.
val allStandoffLinkTargetsGrouped: Map[IRI, Vector[IRI]] = allStandoffLinkTargets.groupBy(identity)
// Replace each Vector[IRI] with its size. That's the number of text values containing
// standoff links to that IRI.
val initialReferenceCounts: Map[IRI, Int] = allStandoffLinkTargetsGrouped.mapValues(_.size)
for {
newValueIri: IRI <- makeUnusedValueIri(createMultipleValuesRequest.resourceIri)
// For each standoff link target IRI, construct a SparqlTemplateLinkUpdate to create a hasStandoffLinkTo property
// and one LinkValue with its initial reference count.
standoffLinkUpdates: Seq[SparqlTemplateLinkUpdate] = initialReferenceCounts.toSeq.map {
case (targetIri, initialReferenceCount) =>
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 = newValueIri,
linkTargetIri = targetIri,
currentReferenceCount = 0,
newReferenceCount = initialReferenceCount,
newLinkValueCreator = OntologyConstants.KnoraAdmin.SystemUser,
newLinkValuePermissions = standoffLinkValuePermissions
)
}
// Generate SPARQL INSERT statements based on those SparqlTemplateLinkUpdates.
sparqlInsert = org.knora.webapi.messages.twirl.queries.sparql.v2.txt.generateInsertStatementsForStandoffLinks(
resourceIri = createMultipleValuesRequest.resourceIri,
linkUpdates = standoffLinkUpdates,
creationDate = createMultipleValuesRequest.creationDate,
stringFormatter = stringFormatter
).toString()
} yield Some(sparqlInsert)
} else {
FastFuture.successful(None)
}
}
/**
* Creates a new version of an existing value.
*
* @param updateValueRequest the request to update the value.
* @return a [[UpdateValueResponseV2]].
*/
private def updateValueV2(updateValueRequest: UpdateValueRequestV2): Future[UpdateValueResponseV2] = {
/**
* Information about a resource, a submitted property, and a value of the property.
*
* @param resource the contents of the resource.
* @param submittedInternalPropertyIri the internal IRI of the submitted property.
* @param adjustedInternalPropertyInfo the internal definition of the submitted property, adjusted
* as follows: an adjusted version of the submitted property:
* if it's a link value property, substitute the
* corresponding link property.
* @param value the requested value.
*/
case class ResourcePropertyValue(resource: ReadResourceV2,
submittedInternalPropertyIri: SmartIri,
adjustedInternalPropertyInfo: ReadPropertyInfoV2,
value: ReadValueV2)
/**
* Gets information about a resource, a submitted property, and a value of the property, and does
* some checks to see if the submitted information is correct.
*
* @param resourceIri the IRI of the resource.
* @param submittedExternalResourceClassIri the submitted external IRI of the resource class.
* @param submittedExternalPropertyIri the submitted external IRI of the property.
* @param valueIri the IRI of the value.
* @param submittedExternalValueType the submitted external IRI of the value type.
* @return a [[ResourcePropertyValue]].
*/
def getResourcePropertyValue(resourceIri: IRI,
submittedExternalResourceClassIri: SmartIri,
submittedExternalPropertyIri: SmartIri,
valueIri: IRI,
submittedExternalValueType: SmartIri): Future[ResourcePropertyValue] = {
for {
submittedInternalPropertyIri: SmartIri <- Future(submittedExternalPropertyIri.toOntologySchema(InternalSchema))
// Get ontology information about the submitted property.
propertyInfoRequestForSubmittedProperty = PropertiesGetRequestV2(
propertyIris = Set(submittedInternalPropertyIri),
allLanguages = false,
requestingUser = updateValueRequest.requestingUser
)
propertyInfoResponseForSubmittedProperty: ReadOntologyV2 <- (responderManager ? propertyInfoRequestForSubmittedProperty).mapTo[ReadOntologyV2]
propertyInfoForSubmittedProperty: ReadPropertyInfoV2 = propertyInfoResponseForSubmittedProperty.properties(submittedInternalPropertyIri)
// Don't accept link properties.
_ = if (propertyInfoForSubmittedProperty.isLinkProp) {
throw BadRequestException(s"Invalid property <${propertyInfoForSubmittedProperty.entityInfoContent.propertyIri.toOntologySchema(ApiV2Complex)}>. Use a link value property to submit a link.")
}
// Don't accept knora-api:hasStandoffLinkToValue.
_ = if (submittedExternalPropertyIri.toString == OntologyConstants.KnoraApiV2Complex.HasStandoffLinkToValue) {
throw BadRequestException(s"Values of <$submittedExternalPropertyIri> cannot be updated directly")
}
// Make an adjusted version of the submitted property: if it's a link value property, substitute the
// corresponding link property, whose objects we will need to query. Get ontology information about the
// adjusted property.
adjustedInternalPropertyInfo: ReadPropertyInfoV2 <- getAdjustedInternalPropertyInfo(
submittedPropertyIri = submittedExternalPropertyIri,
maybeSubmittedValueType = Some(submittedExternalValueType),
propertyInfoForSubmittedProperty = propertyInfoForSubmittedProperty,
requestingUser = updateValueRequest.requestingUser
)
// Get the resource's metadata and relevant property objects, using the adjusted property. Do this as the system user,
// so we can see objects that the user doesn't have permission to see.
resourceInfo: ReadResourceV2 <- getResourceWithPropertyValues(
resourceIri = resourceIri,
propertyInfo = adjustedInternalPropertyInfo,
requestingUser = KnoraSystemInstances.Users.SystemUser
)
_ = if (resourceInfo.resourceClassIri != submittedExternalResourceClassIri.toOntologySchema(InternalSchema)) {
throw BadRequestException(s"The rdf:type of resource <$resourceIri> is not <$submittedExternalResourceClassIri>")
}
// Check that the resource has the value that the user wants to update, as an object of the submitted property.
currentValue: ReadValueV2 = resourceInfo.values.get(submittedInternalPropertyIri).flatMap(_.find(_.valueIri == valueIri)).getOrElse {
throw NotFoundException(s"Resource <$resourceIri> does not have value <$valueIri> as an object of property <$submittedExternalPropertyIri>")
}
// Check that the current value has the submitted value type.
_ = if (currentValue.valueContent.valueType != submittedExternalValueType.toOntologySchema(InternalSchema)) {
throw BadRequestException(s"Value <$valueIri> has type <${currentValue.valueContent.valueType.toOntologySchema(ApiV2Complex)}>, but the submitted type was <$submittedExternalValueType>")
}
// If a custom value creation date was submitted, make sure it's later than the date of the current version.
_ = if (updateValueRequest.updateValue.valueCreationDate.exists(!_.isAfter(currentValue.valueCreationDate))) {
throw BadRequestException("A custom value creation date must be later than the date of the current version")
}
} yield ResourcePropertyValue(
resource = resourceInfo,
submittedInternalPropertyIri = submittedInternalPropertyIri,
adjustedInternalPropertyInfo = adjustedInternalPropertyInfo,
value = currentValue
)
}
/**
* Updates the permissions attached to a value.
*
* @param updateValuePermissionsV2 the update request.
* @return an [[UpdateValueResponseV2]].
*/
def makeTaskFutureToUpdateValuePermissions(updateValuePermissionsV2: UpdateValuePermissionsV2): Future[UpdateValueResponseV2] = {
for {
// Do the initial checks, and get information about the resource, the property, and the value.
resourcePropertyValue: ResourcePropertyValue <- getResourcePropertyValue(
resourceIri = updateValuePermissionsV2.resourceIri,
submittedExternalResourceClassIri = updateValuePermissionsV2.resourceClassIri,
submittedExternalPropertyIri = updateValuePermissionsV2.propertyIri,
valueIri = updateValuePermissionsV2.valueIri,
submittedExternalValueType = updateValuePermissionsV2.valueType
)
resourceInfo: ReadResourceV2 = resourcePropertyValue.resource
submittedInternalPropertyIri: SmartIri = resourcePropertyValue.submittedInternalPropertyIri
currentValue: ReadValueV2 = resourcePropertyValue.value
// Validate and reformat the submitted permissions.
newValuePermissionLiteral: String <- PermissionUtilADM.validatePermissions(permissionLiteral = updateValuePermissionsV2.permissions, responderManager = responderManager)
// Check that the user has ChangeRightsPermission on the value, and that the new permissions are
// different from the current ones.
currentPermissionsParsed: Map[EntityPermission, Set[IRI]] = PermissionUtilADM.parsePermissions(currentValue.permissions)
newPermissionsParsed: Map[EntityPermission, Set[IRI]] = PermissionUtilADM.parsePermissions(updateValuePermissionsV2.permissions, { permissionLiteral: String => throw AssertionException(s"Invalid permission literal: $permissionLiteral") })
_ = if (newPermissionsParsed == currentPermissionsParsed) {
throw BadRequestException(s"The submitted permissions are the same as the current ones")
}
_ = ResourceUtilV2.checkValuePermission(
resourceInfo = resourceInfo,
valueInfo = currentValue,
permissionNeeded = ChangeRightsPermission,
requestingUser = updateValueRequest.requestingUser
)
// Do the update.
dataNamedGraph: IRI = stringFormatter.projectDataNamedGraphV2(resourceInfo.projectADM)
newValueIri: IRI <- checkOrCreateEntityIri(updateValuePermissionsV2.newValueVersionIri, stringFormatter.makeRandomValueIri(resourceInfo.resourceIri))
currentTime: Instant = updateValuePermissionsV2.valueCreationDate.getOrElse(Instant.now)
sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v2.txt.changeValuePermissions(
dataNamedGraph = dataNamedGraph,
triplestore = settings.triplestoreType,
resourceIri = resourceInfo.resourceIri,
propertyIri = submittedInternalPropertyIri,
currentValueIri = currentValue.valueIri,
valueTypeIri = currentValue.valueContent.valueType,
newValueIri = newValueIri,
newPermissions = newValuePermissionLiteral,
currentTime = currentTime
).toString()
_ <- (storeManager ? SparqlUpdateRequest(sparqlUpdate)).mapTo[SparqlUpdateResponse]
// Check that the value was written correctly to the triplestore.
unverifiedValue = UnverifiedValueV2(
newValueIri = newValueIri,
newValueUUID = currentValue.valueHasUUID,
valueContent = currentValue.valueContent,
permissions = newValuePermissionLiteral,
creationDate = currentTime
)
verifiedValue: VerifiedValueV2 <- verifyValue(
resourceIri = resourceInfo.resourceIri,
propertyIri = submittedInternalPropertyIri,
unverifiedValue = unverifiedValue,
requestingUser = updateValueRequest.requestingUser
)
} yield UpdateValueResponseV2(
valueIri = verifiedValue.newValueIri,
valueType = unverifiedValue.valueContent.valueType,
valueUUID = currentValue.valueHasUUID,
projectADM = resourceInfo.projectADM
)
}
/**
* Updates the contents of a value.
*
* @param updateValueContentV2 the update request.
* @return an [[UpdateValueResponseV2]].
*/
def makeTaskFutureToUpdateValueContent(updateValueContentV2: UpdateValueContentV2): Future[UpdateValueResponseV2] = {
for {
// Do the initial checks, and get information about the resource, the property, and the value.
resourcePropertyValue: ResourcePropertyValue <- getResourcePropertyValue(
resourceIri = updateValueContentV2.resourceIri,
submittedExternalResourceClassIri = updateValueContentV2.resourceClassIri,
submittedExternalPropertyIri = updateValueContentV2.propertyIri,
valueIri = updateValueContentV2.valueIri,
submittedExternalValueType = updateValueContentV2.valueContent.valueType
)
resourceInfo: ReadResourceV2 = resourcePropertyValue.resource
submittedInternalPropertyIri: SmartIri = resourcePropertyValue.submittedInternalPropertyIri
adjustedInternalPropertyInfo: ReadPropertyInfoV2 = resourcePropertyValue.adjustedInternalPropertyInfo
currentValue: ReadValueV2 = resourcePropertyValue.value
// Did the user submit permissions for the new value?
newValueVersionPermissionLiteral <- updateValueContentV2.permissions match {
case Some(permissions) =>
// Yes. Validate them.
PermissionUtilADM.validatePermissions(permissionLiteral = permissions, responderManager = responderManager)
case None =>
// No. Use the permissions on the current version of the value.
FastFuture.successful(currentValue.permissions)
}
// Check that the user has permission to do the update. If they want to change the permissions
// on the value, they need ChangeRightsPermission, otherwise they need ModifyPermission.
currentPermissionsParsed: Map[EntityPermission, Set[IRI]] = PermissionUtilADM.parsePermissions(currentValue.permissions)
newPermissionsParsed: Map[EntityPermission, Set[IRI]] = PermissionUtilADM.parsePermissions(newValueVersionPermissionLiteral, { permissionLiteral: String => throw AssertionException(s"Invalid permission literal: $permissionLiteral") })
permissionNeeded = if (newPermissionsParsed != currentPermissionsParsed) {