/
ResourceMessagesV2.scala
1699 lines (1477 loc) · 74.6 KB
/
ResourceMessagesV2.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-2021 the contributors (see Contributors.md).
*
* This file is part of Knora.
*
* Knora is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Knora is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with Knora. If not, see <http://www.gnu.org/licenses/>.
*/
package org.knora.webapi.messages.v2.responder.resourcemessages
import java.time.Instant
import java.util.UUID
import akka.actor.ActorRef
import akka.event.LoggingAdapter
import akka.pattern._
import akka.util.Timeout
import org.knora.webapi._
import org.knora.webapi.exceptions._
import org.knora.webapi.feature.FeatureFactoryConfig
import org.knora.webapi.messages.IriConversions._
import org.knora.webapi.messages.admin.responder.projectsmessages.{
ProjectADM,
ProjectGetRequestADM,
ProjectGetResponseADM,
ProjectIdentifierADM
}
import org.knora.webapi.messages.admin.responder.usersmessages.UserADM
import org.knora.webapi.messages.util.PermissionUtilADM.EntityPermission
import org.knora.webapi.messages.util._
import org.knora.webapi.messages.util.rdf._
import org.knora.webapi.messages.util.standoff.{StandoffTagUtilV2, XMLUtil}
import org.knora.webapi.messages.v2.responder._
import org.knora.webapi.messages.v2.responder.standoffmessages.MappingXMLtoStandoff
import org.knora.webapi.messages.v2.responder.valuemessages._
import org.knora.webapi.messages.{OntologyConstants, SmartIri, StringFormatter}
import org.knora.webapi.settings.KnoraSettingsImpl
import org.knora.webapi.util._
import scala.concurrent.{ExecutionContext, Future}
/**
* An abstract trait for messages that can be sent to `ResourcesResponderV2`.
*/
sealed trait ResourcesResponderRequestV2 extends KnoraRequestV2 {
/**
* The user that made the request.
*/
def requestingUser: UserADM
}
/**
* Requests a description of a resource. A successful response will be a [[ReadResourcesSequenceV2]].
*
* @param resourceIris the IRIs of the resources to be queried.
* @param propertyIri if defined, requests only the values of the specified explicit property.
* @param withDeleted if defined, returns a deleted resource or a deleted value.
* @param valueUuid if defined, requests only the value with the specified UUID.
* @param versionDate if defined, requests the state of the resources at the specified time in the past.
* @param targetSchema the target API schema.
* @param schemaOptions the schema options submitted with the request.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the user making the request.
*/
case class ResourcesGetRequestV2(resourceIris: Seq[IRI],
propertyIri: Option[SmartIri] = None,
valueUuid: Option[UUID] = None,
versionDate: Option[Instant] = None,
withDeleted: Boolean = false,
targetSchema: ApiV2Schema,
schemaOptions: Set[SchemaOption] = Set.empty,
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM)
extends ResourcesResponderRequestV2
/**
* Requests a preview of one or more resources. A successful response will be a [[ReadResourcesSequenceV2]].
*
* @param resourceIris the IRIs of the resources to obtain a preview for.
* @param withDeletedResource indicates if a preview of deleted resource should be returned.
* @param targetSchema the schema of the response.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the user making the request.
*/
case class ResourcesPreviewGetRequestV2(resourceIris: Seq[IRI],
withDeletedResource: Boolean = false,
targetSchema: ApiV2Schema,
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM)
extends ResourcesResponderRequestV2
/**
* Requests a IIIF manifest for the images that are `knora-base:isPartOf` the specified
* resource.
*
* @param resourceIri the resource IRI.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the user making the request.
*/
case class ResourceIIIFManifestGetRequestV2(resourceIri: IRI,
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM)
extends ResourcesResponderRequestV2
/**
* Represents a IIIF manifest for the images that are `knora-base:isPartOf` the specified
* resource.
*
* @param manifest the IIIF manifest.
*/
case class ResourceIIIFManifestGetResponseV2(manifest: JsonLDDocument) extends KnoraJsonLDResponseV2 {
override protected def toJsonLDDocument(targetSchema: ApiV2Schema,
settings: KnoraSettingsImpl,
schemaOptions: Set[SchemaOption]): JsonLDDocument = manifest
}
/**
* Requests the version history of the values of a resource.
*
* @param resourceIri the IRI of the resource.
* @param withDeletedResource indicates if the version history of deleted resources should be returned or not.
* @param startDate the start of the time period to return, inclusive.
* @param endDate the end of the time period to return, exclusive.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the user making the request.
*/
case class ResourceVersionHistoryGetRequestV2(resourceIri: IRI,
withDeletedResource: Boolean = false,
startDate: Option[Instant] = None,
endDate: Option[Instant] = None,
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM)
extends ResourcesResponderRequestV2
/**
* Requests the full version history of a resource and its values as events.
*
* @param resourceIri the IRI of the resource.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the user making the request.
*/
case class ResourceHistoryEventsGetRequestV2(resourceIri: IRI,
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM)
extends ResourcesResponderRequestV2 {
private val stringFormatter = StringFormatter.getInstanceForConstantOntologies
stringFormatter.validateAndEscapeIri(resourceIri, throw BadRequestException(s"Invalid resource IRI: $resourceIri"))
if (!stringFormatter.toSmartIri(resourceIri).isKnoraResourceIri) {
throw BadRequestException(s"Given IRI is not a resource IRI: $resourceIri")
}
}
/**
* Requests the version history of all resources of a project.
*
* @param projectIri the IRI of the project.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the user making the request.
*/
case class ProjectResourcesWithHistoryGetRequestV2(projectIri: IRI,
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM)
extends ResourcesResponderRequestV2 {
private val stringFormatter = StringFormatter.getInstanceForConstantOntologies
stringFormatter.validateAndEscapeIri(projectIri, throw BadRequestException(s"Invalid project IRI: $projectIri"))
if (!stringFormatter.isKnoraProjectIriStr(projectIri)) {
throw BadRequestException("Given IRI is not a project IRI.")
}
}
/**
* Represents an item in the version history of a resource.
*
* @param versionDate the date when the modification occurred.
* @param author the IRI of the user that made the modification.
*/
case class ResourceHistoryEntry(versionDate: Instant, author: IRI)
/**
* Represents the version history of the values of a resource.
*/
case class ResourceVersionHistoryResponseV2(history: Seq[ResourceHistoryEntry]) extends KnoraJsonLDResponseV2 {
/**
* Converts the response to a data structure that can be used to generate JSON-LD.
*
* @param targetSchema the Knora API schema to be used in the JSON-LD document.
* @return a [[JsonLDDocument]] representing the response.
*/
override def toJsonLDDocument(targetSchema: ApiV2Schema,
settings: KnoraSettingsImpl,
schemaOptions: Set[SchemaOption]): JsonLDDocument = {
implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance
if (targetSchema != ApiV2Complex) {
throw AssertionException("Version history can be returned only in the complex schema")
}
// Convert the history entries to an array of JSON-LD objects.
val historyAsJsonLD: Seq[JsonLDObject] = history.map { historyEntry: ResourceHistoryEntry =>
JsonLDObject(
Map(
OntologyConstants.KnoraApiV2Complex.VersionDate -> JsonLDUtil.datatypeValueToJsonLDObject(
value = historyEntry.versionDate.toString,
datatype = OntologyConstants.Xsd.DateTimeStamp.toSmartIri
),
OntologyConstants.KnoraApiV2Complex.Author -> JsonLDUtil.iriToJsonLDObject(historyEntry.author)
)
)
}
// Make the JSON-LD context.
val context = JsonLDUtil.makeContext(
fixedPrefixes = Map(
"rdf" -> OntologyConstants.Rdf.RdfPrefixExpansion,
"rdfs" -> OntologyConstants.Rdfs.RdfsPrefixExpansion,
"xsd" -> OntologyConstants.Xsd.XsdPrefixExpansion,
OntologyConstants.KnoraApi.KnoraApiOntologyLabel -> OntologyConstants.KnoraApiV2Complex.KnoraApiV2PrefixExpansion
)
)
// Make the JSON-LD document.
val body = JsonLDObject(Map(JsonLDKeywords.GRAPH -> JsonLDArray(historyAsJsonLD)))
JsonLDDocument(body = body, context = context)
}
}
/**
* Requests a resource as TEI/XML. A successful response will be a [[ResourceTEIGetResponseV2]].
*
* @param resourceIri the IRI of the resource to be returned in TEI/XML.
* @param textProperty the property representing the text (to be converted to the body of a TEI document).
* @param mappingIri the IRI of the mapping to be used to convert from standoff to TEI/XML, if any. Otherwise the standard mapping is assumed.
* @param gravsearchTemplateIri the gravsearch template to query the metadata for the TEI header, if provided.
* @param headerXSLTIri the IRI of the XSL transformation to convert the resource's metadata to the TEI header.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the user making the request.
*/
case class ResourceTEIGetRequestV2(resourceIri: IRI,
textProperty: SmartIri,
mappingIri: Option[IRI],
gravsearchTemplateIri: Option[IRI],
headerXSLTIri: Option[IRI],
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM)
extends ResourcesResponderRequestV2
/**
* Represents a Knora resource as TEI/XML.
*
* @param header the header of the TEI document, if given.
* @param body the body of the TEI document.
*/
case class ResourceTEIGetResponseV2(header: TEIHeader, body: TEIBody) {
def toXML: String = {
s"""<?xml version="1.0" encoding="UTF-8"?>
|<TEI version="3.3.0" xmlns="http://www.tei-c.org/ns/1.0">
|${header.toXML}
|${body.toXML}
|</TEI>""".stripMargin
}
}
/**
* Represents information that is going to be contained in the header of a TEI/XML document.
*
* @param headerInfo the resource representing the header information.
* @param headerXSLT XSLT to be applied to the resource's metadata in RDF/XML.
*
*/
case class TEIHeader(headerInfo: ReadResourceV2,
headerXSLT: Option[String],
featureFactoryConfig: FeatureFactoryConfig,
settings: KnoraSettingsImpl) {
def toXML: String = {
if (headerXSLT.nonEmpty) {
val rdfFormatUtil: RdfFormatUtil = RdfFeatureFactory.getRdfFormatUtil(featureFactoryConfig)
// Convert the resource to a JsonLDDocument.
val headerJsonLD: JsonLDDocument =
ReadResourcesSequenceV2(Seq(headerInfo)).toJsonLDDocument(ApiV2Complex, settings)
// Convert the JsonLDDocument to an RdfModel.
val rdfModel: RdfModel = headerJsonLD.toRdfModel(rdfFormatUtil.getRdfModelFactory)
// Format the RdfModel as RDF/XML. To ensure that it contains only rdf:Description elements,
// set prettyPrint to false.
val teiXmlHeader: String = rdfFormatUtil.format(
rdfModel = rdfModel,
rdfFormat = RdfXml,
prettyPrint = false
)
// Run an XSL transformation to convert the RDF/XML to a TEI/XML header.
XMLUtil.applyXSLTransformation(xml = teiXmlHeader, xslt = headerXSLT.get)
} else {
s"""
|<teiHeader>
| <fileDesc>
| <titleStmt>
| <title>${headerInfo.label}</title>
| </titleStmt>
| <publicationStmt>
| <p>
| This is the TEI/XML representation of a resource identified by the Iri ${headerInfo.resourceIri}.
| </p>
| </publicationStmt>
| <sourceDesc>
| <p>Representation of the resource's text as TEI/XML</p>
| </sourceDesc>
| </fileDesc>
|</teiHeader>
""".stripMargin
}
}
}
/**
* Represents the actual text that is going to be converted to the body of a TEI document.
*
* @param bodyInfo the content of the text value that will be converted to TEI.
* @param teiMapping the mapping from standoff to TEI/XML.
* @param bodyXSLT the XSLT transformation that completes the generation of TEI/XML.
*/
case class TEIBody(bodyInfo: TextValueContentV2, teiMapping: MappingXMLtoStandoff, bodyXSLT: String) {
def toXML: String = {
if (bodyInfo.standoff.isEmpty) throw BadRequestException(s"text is expected to have standoff markup")
// create XML from standoff (temporary XML) that is going to be converted to TEI/XML
val tmpXml = StandoffTagUtilV2.convertStandoffTagV2ToXML(bodyInfo.valueHasString, bodyInfo.standoff, teiMapping)
XMLUtil.applyXSLTransformation(tmpXml, bodyXSLT)
}
}
/**
* Represents a Knora resource. Any implementation of `ResourceV2` is API operation specific.
*/
sealed trait ResourceV2 {
/**
* The IRI of the resource class.
*/
def resourceClassIri: SmartIri
/**
* The resource's `rdfs:label`.
*/
def label: String
/**
* A map of property IRIs to [[IOValueV2]] objects.
*/
def values: Map[SmartIri, Seq[IOValueV2]]
}
/**
* Represents a Knora resource when being read back from the triplestore.
*
* @param resourceIri the IRI of the resource.
* @param label the resource's label.
* @param resourceClassIri the class the resource belongs to.
* @param attachedToUser the user that created the resource.
* @param projectADM the project that the resource belongs to.
* @param permissions the permissions that the resource grants to user groups.
* @param userPermission the permission the the requesting user has on the resource.
* @param values a map of property IRIs to values.
* @param creationDate the date when this resource was created.
* @param lastModificationDate the date when this resource was last modified.
* @param versionDate if this is a past version of the resource, the date of the version.
* @param deletionInfo if this resource has been marked as deleted, provides the date when it was
* deleted and the reason why it was deleted.
*/
case class ReadResourceV2(resourceIri: IRI,
label: String,
resourceClassIri: SmartIri,
attachedToUser: IRI,
projectADM: ProjectADM,
permissions: String,
userPermission: EntityPermission,
values: Map[SmartIri, Seq[ReadValueV2]],
creationDate: Instant,
lastModificationDate: Option[Instant],
versionDate: Option[Instant],
deletionInfo: Option[DeletionInfo])
extends ResourceV2
with KnoraReadV2[ReadResourceV2] {
override def toOntologySchema(targetSchema: ApiV2Schema): ReadResourceV2 = {
copy(
resourceClassIri = resourceClassIri.toOntologySchema(targetSchema),
values = values.map {
case (propertyIri, readValues) =>
val propertyIriInTargetSchema = propertyIri.toOntologySchema(targetSchema)
// In the simple schema, use link properties instead of link value properties.
val adaptedPropertyIri = if (targetSchema == ApiV2Simple) {
// If all the property's values are link values, it's a link value property.
val isLinkProp = readValues.forall { readValue =>
readValue.valueContent match {
case _: LinkValueContentV2 => true
case _ => false
}
}
// If it's a link value property, use the corresponding link property.
if (isLinkProp) {
propertyIriInTargetSchema.fromLinkValuePropToLinkProp
} else {
propertyIriInTargetSchema
}
} else {
propertyIriInTargetSchema
}
adaptedPropertyIri -> readValues.map(_.toOntologySchema(targetSchema))
}
)
}
def toJsonLD(targetSchema: ApiV2Schema,
settings: KnoraSettingsImpl,
schemaOptions: Set[SchemaOption]): JsonLDObject = {
implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance
if (!resourceClassIri.getOntologySchema.contains(targetSchema)) {
throw DataConversionException(s"ReadClassInfoV2 for resource $resourceIri is not in schema $targetSchema")
}
val propertiesAndValuesAsJsonLD: Map[IRI, JsonLDArray] = values.map {
case (propIri: SmartIri, readValues: Seq[ReadValueV2]) =>
val valuesAsJsonLD: Seq[JsonLDValue] = readValues.map { readValue =>
readValue.toJsonLD(
targetSchema = targetSchema,
projectADM = projectADM,
settings = settings,
schemaOptions = schemaOptions
)
}
propIri.toString -> JsonLDArray(valuesAsJsonLD)
}
val metadataForComplexSchema: Map[IRI, JsonLDValue] = if (targetSchema == ApiV2Complex) {
val requiredMetadataForComplexSchema: Map[IRI, JsonLDValue] = Map(
OntologyConstants.KnoraApiV2Complex.AttachedToUser -> JsonLDUtil.iriToJsonLDObject(attachedToUser),
OntologyConstants.KnoraApiV2Complex.AttachedToProject -> JsonLDUtil.iriToJsonLDObject(projectADM.id),
OntologyConstants.KnoraApiV2Complex.HasPermissions -> JsonLDString(permissions),
OntologyConstants.KnoraApiV2Complex.UserHasPermission -> JsonLDString(userPermission.toString),
OntologyConstants.KnoraApiV2Complex.CreationDate -> JsonLDUtil.datatypeValueToJsonLDObject(
value = creationDate.toString,
datatype = OntologyConstants.Xsd.DateTimeStamp.toSmartIri
)
)
val deletionInfoAsJsonLD: Map[IRI, JsonLDValue] = deletionInfo match {
case Some(definedDeletionInfo) => definedDeletionInfo.toJsonLDFields(ApiV2Complex)
case None => Map.empty[IRI, JsonLDValue]
}
val lastModDateAsJsonLD: Option[(IRI, JsonLDValue)] = lastModificationDate.map { definedLastModDate =>
OntologyConstants.KnoraApiV2Complex.LastModificationDate -> JsonLDUtil.datatypeValueToJsonLDObject(
value = definedLastModDate.toString,
datatype = OntologyConstants.Xsd.DateTimeStamp.toSmartIri
)
}
// If this is a past version of the resource, include knora-api:versionDate.
val versionDateAsJsonLD = versionDate.map { definedVersionDate =>
OntologyConstants.KnoraApiV2Complex.VersionDate -> JsonLDUtil.datatypeValueToJsonLDObject(
value = definedVersionDate.toString,
datatype = OntologyConstants.Xsd.DateTimeStamp.toSmartIri
)
}
requiredMetadataForComplexSchema ++ deletionInfoAsJsonLD ++ lastModDateAsJsonLD ++ versionDateAsJsonLD
} else {
Map.empty[IRI, JsonLDValue]
}
// Make an ARK URL without a version timestamp.
val resourceSmartIri: SmartIri = resourceIri.toSmartIri
val arkUrlProp: IRI = targetSchema match {
case ApiV2Simple => OntologyConstants.KnoraApiV2Simple.ArkUrl
case ApiV2Complex => OntologyConstants.KnoraApiV2Complex.ArkUrl
}
val arkUrlAsJsonLD: (IRI, JsonLDObject) =
arkUrlProp -> JsonLDUtil.datatypeValueToJsonLDObject(
value = resourceSmartIri.fromResourceIriToArkUrl(),
datatype = OntologyConstants.Xsd.Uri.toSmartIri
)
// Make an ARK URL with a version timestamp.
val versionArkUrlProp: IRI = targetSchema match {
case ApiV2Simple => OntologyConstants.KnoraApiV2Simple.VersionArkUrl
case ApiV2Complex => OntologyConstants.KnoraApiV2Complex.VersionArkUrl
}
val arkTimestamp = versionDate.getOrElse(lastModificationDate.getOrElse(creationDate))
val versionArkUrlAsJsonLD: (IRI, JsonLDObject) =
versionArkUrlProp -> JsonLDUtil.datatypeValueToJsonLDObject(
value = resourceSmartIri.fromResourceIriToArkUrl(maybeTimestamp = Some(arkTimestamp)),
datatype = OntologyConstants.Xsd.Uri.toSmartIri
)
JsonLDObject(
Map(
JsonLDKeywords.ID -> JsonLDString(resourceIri),
JsonLDKeywords.TYPE -> JsonLDString(resourceClassIri.toString),
OntologyConstants.Rdfs.Label -> JsonLDString(label)
) ++ propertiesAndValuesAsJsonLD ++ metadataForComplexSchema + arkUrlAsJsonLD + versionArkUrlAsJsonLD
)
}
}
/**
* The value of a Knora property sent to Knora to be created in a new resource.
*
* @param valueContent the content of the new value. If the client wants to create a link, this must be a [[LinkValueContentV2]].
* @param customValueIri the optional custom value IRI.
* @param customValueUUID the optional custom value UUID.
* @param customValueCreationDate the optional custom value creation date.
* @param permissions the permissions to be given to the new value. If not provided, these will be taken from defaults.
*/
case class CreateValueInNewResourceV2(valueContent: ValueContentV2,
customValueIri: Option[SmartIri] = None,
customValueUUID: Option[UUID] = None,
customValueCreationDate: Option[Instant] = None,
permissions: Option[String] = None)
extends IOValueV2
/**
* Represents a Knora resource to be created.
*
* @param resourceIri the IRI that should be given to the resource.
* @param resourceClassIri the class the resource belongs to.
* @param label the resource's label.
* @param values the resource's values.
* @param projectADM the project that the resource should belong to.
* @param permissions the permissions to be given to the new resource. If not provided, these will be taken from defaults.
* @param creationDate the optional creation date of the resource.
*/
case class CreateResourceV2(resourceIri: Option[SmartIri],
resourceClassIri: SmartIri,
label: String,
values: Map[SmartIri, Seq[CreateValueInNewResourceV2]],
projectADM: ProjectADM,
permissions: Option[String] = None,
creationDate: Option[Instant] = None)
extends ResourceV2 {
lazy val flatValues: Iterable[CreateValueInNewResourceV2] = values.values.flatten
/**
* Converts this [[CreateResourceV2]] to the specified ontology schema.
*
* @param targetSchema the target ontology schema.
* @return a copy of this [[CreateResourceV2]] in the specified ontology schema.
*/
def toOntologySchema(targetSchema: OntologySchema): CreateResourceV2 = {
copy(
resourceClassIri = resourceClassIri.toOntologySchema(targetSchema),
values = values.map {
case (propertyIri, valuesToCreate) =>
propertyIri.toOntologySchema(targetSchema) -> valuesToCreate.map { valueToCreate =>
valueToCreate.copy(
valueContent = valueToCreate.valueContent.toOntologySchema(targetSchema)
)
}
}
)
}
}
/**
* Represents a request to create a resource.
*
* @param createResource the resource to be created.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the user making the request.
* @param apiRequestID the API request ID.
*/
case class CreateResourceRequestV2(createResource: CreateResourceV2,
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM,
apiRequestID: UUID)
extends ResourcesResponderRequestV2
object CreateResourceRequestV2 extends KnoraJsonLDRequestReaderV2[CreateResourceRequestV2] {
/**
* Converts JSON-LD input to a [[CreateResourceRequestV2]].
*
* @param jsonLDDocument the JSON-LD input.
* @param apiRequestID the UUID of the API request.
* @param requestingUser the user making the request.
* @param responderManager a reference to the responder manager.
* @param storeManager a reference to the store manager.
* @param featureFactoryConfig the feature factory configuration.
* @param settings the application settings.
* @param log a logging adapter.
* @return a case class instance representing the input.
*/
override def fromJsonLD(jsonLDDocument: JsonLDDocument,
apiRequestID: UUID,
requestingUser: UserADM,
responderManager: ActorRef,
storeManager: ActorRef,
featureFactoryConfig: FeatureFactoryConfig,
settings: KnoraSettingsImpl,
log: LoggingAdapter)(implicit timeout: Timeout,
executionContext: ExecutionContext): Future[CreateResourceRequestV2] = {
implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance
for {
// Get the resource class.
resourceClassIri: SmartIri <- Future(jsonLDDocument.requireTypeAsKnoraTypeIri)
// Get the custom resource IRI if provided.
maybeCustomResourceIri: Option[SmartIri] = jsonLDDocument.maybeIDAsKnoraDataIri
// Get the resource's rdfs:label.
label: String = jsonLDDocument.requireStringWithValidation(OntologyConstants.Rdfs.Label,
stringFormatter.toSparqlEncodedString)
// Get information about the project that the resource should be created in.
projectIri: SmartIri = jsonLDDocument.requireIriInObject(OntologyConstants.KnoraApiV2Complex.AttachedToProject,
stringFormatter.toSmartIriWithErr)
projectInfoResponse: ProjectGetResponseADM <- (responderManager ? ProjectGetRequestADM(
identifier = ProjectIdentifierADM(maybeIri = Some(projectIri.toString)),
featureFactoryConfig = featureFactoryConfig,
requestingUser = requestingUser
)).mapTo[ProjectGetResponseADM]
_ = maybeCustomResourceIri.foreach { definedResourceIri =>
if (!definedResourceIri.isKnoraResourceIri) {
throw BadRequestException(s"<$definedResourceIri> is not a Knora resource IRI")
}
if (!definedResourceIri.getProjectCode.contains(projectInfoResponse.project.shortcode)) {
throw BadRequestException(s"The provided resource IRI does not contain the correct project code")
}
}
// Get the resource's permissions.
permissions: Option[String] = jsonLDDocument.maybeStringWithValidation(
OntologyConstants.KnoraApiV2Complex.HasPermissions,
stringFormatter.toSparqlEncodedString)
// Get the user who should be indicated as the creator of the resource, if specified.
maybeAttachedToUserIri: Option[SmartIri] = jsonLDDocument.maybeIriInObject(
OntologyConstants.KnoraApiV2Complex.AttachedToUser,
stringFormatter.toSmartIriWithErr)
maybeAttachedToUserFuture: Option[Future[UserADM]] = maybeAttachedToUserIri.map { attachedToUserIri =>
UserUtilADM.switchToUser(
requestingUser = requestingUser,
requestedUserIri = attachedToUserIri.toString,
projectIri = projectIri.toString,
featureFactoryConfig = featureFactoryConfig,
responderManager = responderManager
)
}
maybeAttachedToUser: Option[UserADM] <- ActorUtil.optionFuture2FutureOption(maybeAttachedToUserFuture)
// Get the resource's creation date.
creationDate: Option[Instant] = jsonLDDocument.maybeDatatypeValueInObject(
key = OntologyConstants.KnoraApiV2Complex.CreationDate,
expectedDatatype = OntologyConstants.Xsd.DateTimeStamp.toSmartIri,
validationFun = stringFormatter.xsdDateTimeStampToInstant
)
// Get the resource's values.
propertyIriStrs: Set[IRI] = jsonLDDocument.body.value.keySet --
Set(
JsonLDKeywords.ID,
JsonLDKeywords.TYPE,
OntologyConstants.Rdfs.Label,
OntologyConstants.KnoraApiV2Complex.AttachedToProject,
OntologyConstants.KnoraApiV2Complex.AttachedToUser,
OntologyConstants.KnoraApiV2Complex.HasPermissions,
OntologyConstants.KnoraApiV2Complex.CreationDate
)
propertyValueFuturesMap: Map[SmartIri, Seq[Future[CreateValueInNewResourceV2]]] = propertyIriStrs.map {
propertyIriStr =>
val propertyIri: SmartIri =
propertyIriStr.toSmartIriWithErr(throw BadRequestException(s"Invalid property IRI: <$propertyIriStr>"))
val valuesArray: JsonLDArray = jsonLDDocument.requireArray(propertyIriStr)
val valueFuturesSeq: Seq[Future[CreateValueInNewResourceV2]] = valuesArray.value.map { valueJsonLD =>
val valueJsonLDObject = valueJsonLD match {
case jsonLDObject: JsonLDObject => jsonLDObject
case _ => throw BadRequestException(s"Invalid JSON-LD as object of property <$propertyIriStr>")
}
for {
valueContent: ValueContentV2 <- ValueContentV2.fromJsonLDObject(
jsonLDObject = valueJsonLDObject,
requestingUser = requestingUser,
responderManager = responderManager,
storeManager = storeManager,
featureFactoryConfig = featureFactoryConfig,
settings = settings,
log = log
)
maybeCustomValueIri: Option[SmartIri] = valueJsonLDObject.maybeIDAsKnoraDataIri
maybeCustomValueUUID: Option[UUID] = valueJsonLDObject.maybeUUID(
OntologyConstants.KnoraApiV2Complex.ValueHasUUID)
// Get the value's creation date.
// TODO: creationDate for values is a bug, and will not be supported in future. Use valueCreationDate instead.
maybeCustomValueCreationDate: Option[Instant] = valueJsonLDObject
.maybeDatatypeValueInObject(
key = OntologyConstants.KnoraApiV2Complex.ValueCreationDate,
expectedDatatype = OntologyConstants.Xsd.DateTimeStamp.toSmartIri,
validationFun = stringFormatter.xsdDateTimeStampToInstant
)
.orElse(valueJsonLDObject.maybeDatatypeValueInObject(
key = OntologyConstants.KnoraApiV2Complex.CreationDate,
expectedDatatype = OntologyConstants.Xsd.DateTimeStamp.toSmartIri,
validationFun = stringFormatter.xsdDateTimeStampToInstant
))
maybePermissions: Option[String] = valueJsonLDObject.maybeStringWithValidation(
OntologyConstants.KnoraApiV2Complex.HasPermissions,
stringFormatter.toSparqlEncodedString)
} yield
CreateValueInNewResourceV2(
valueContent = valueContent,
customValueIri = maybeCustomValueIri,
customValueUUID = maybeCustomValueUUID,
customValueCreationDate = maybeCustomValueCreationDate,
permissions = maybePermissions
)
}
propertyIri -> valueFuturesSeq
}.toMap
propertyValuesMap: Map[SmartIri, Seq[CreateValueInNewResourceV2]] <- ActorUtil.sequenceSeqFuturesInMap(
propertyValueFuturesMap)
} yield
CreateResourceRequestV2(
createResource = CreateResourceV2(
resourceIri = maybeCustomResourceIri,
resourceClassIri = resourceClassIri,
label = label,
values = propertyValuesMap,
projectADM = projectInfoResponse.project,
permissions = permissions,
creationDate = creationDate
),
featureFactoryConfig = featureFactoryConfig,
requestingUser = maybeAttachedToUser.getOrElse(requestingUser),
apiRequestID = apiRequestID
)
}
}
/**
* Represents a request to update a resource's metadata.
*
* @param resourceIri the IRI of the resource.
* @param resourceClassIri the IRI of the resource class.
* @param maybeLastModificationDate the resource's last modification date, if any.
* @param maybeLabel the resource's new `rdfs:label`, if any.
* @param maybePermissions the resource's new permissions, if any.
* @param maybeNewModificationDate the resource's new last modification date, if any.
* @param featureFactoryConfig the feature factory configuration.
*/
case class UpdateResourceMetadataRequestV2(resourceIri: IRI,
resourceClassIri: SmartIri,
maybeLastModificationDate: Option[Instant] = None,
maybeLabel: Option[String] = None,
maybePermissions: Option[String] = None,
maybeNewModificationDate: Option[Instant] = None,
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM,
apiRequestID: UUID)
extends ResourcesResponderRequestV2
object UpdateResourceMetadataRequestV2 extends KnoraJsonLDRequestReaderV2[UpdateResourceMetadataRequestV2] {
/**
* Converts JSON-LD input into an instance of [[UpdateResourceMetadataRequestV2]].
*
* @param jsonLDDocument the JSON-LD input.
* @param apiRequestID the UUID of the API request.
* @param requestingUser the user making the request.
* @param responderManager a reference to the responder manager.
* @param storeManager a reference to the store manager.
* @param featureFactoryConfig the feature factory configuration.
* @param settings the application settings.
* @param log a logging adapter.
* @return a case class instance representing the input.
*/
override def fromJsonLD(jsonLDDocument: JsonLDDocument,
apiRequestID: UUID,
requestingUser: UserADM,
responderManager: ActorRef,
storeManager: ActorRef,
featureFactoryConfig: FeatureFactoryConfig,
settings: KnoraSettingsImpl,
log: LoggingAdapter)(
implicit timeout: Timeout,
executionContext: ExecutionContext): Future[UpdateResourceMetadataRequestV2] = {
Future {
fromJsonLDSync(
jsonLDDocument = jsonLDDocument,
featureFactoryConfig = featureFactoryConfig,
requestingUser = requestingUser,
apiRequestID = apiRequestID
)
}
}
def fromJsonLDSync(jsonLDDocument: JsonLDDocument,
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM,
apiRequestID: UUID): UpdateResourceMetadataRequestV2 = {
implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance
val resourceIri: SmartIri = jsonLDDocument.requireIDAsKnoraDataIri
if (!resourceIri.isKnoraResourceIri) {
throw BadRequestException(s"Invalid resource IRI: <$resourceIri>")
}
val resourceClassIri: SmartIri = jsonLDDocument.requireTypeAsKnoraTypeIri
val maybeLastModificationDate: Option[Instant] = jsonLDDocument.maybeDatatypeValueInObject(
key = OntologyConstants.KnoraApiV2Complex.LastModificationDate,
expectedDatatype = OntologyConstants.Xsd.DateTimeStamp.toSmartIri,
validationFun = stringFormatter.xsdDateTimeStampToInstant
)
val maybeLabel: Option[String] =
jsonLDDocument.maybeStringWithValidation(OntologyConstants.Rdfs.Label, stringFormatter.toSparqlEncodedString)
val maybePermissions: Option[String] = jsonLDDocument.maybeStringWithValidation(
OntologyConstants.KnoraApiV2Complex.HasPermissions,
stringFormatter.toSparqlEncodedString)
val maybeNewModificationDate: Option[Instant] = jsonLDDocument.maybeDatatypeValueInObject(
key = OntologyConstants.KnoraApiV2Complex.NewModificationDate,
expectedDatatype = OntologyConstants.Xsd.DateTimeStamp.toSmartIri,
validationFun = stringFormatter.xsdDateTimeStampToInstant
)
if (Seq(maybeLabel, maybePermissions, maybeNewModificationDate).forall(_.isEmpty)) {
throw BadRequestException(s"No updated resource metadata provided")
}
UpdateResourceMetadataRequestV2(
resourceIri = resourceIri.toString,
resourceClassIri = resourceClassIri,
maybeLastModificationDate = maybeLastModificationDate,
maybeLabel = maybeLabel,
maybePermissions = maybePermissions,
maybeNewModificationDate = maybeNewModificationDate,
featureFactoryConfig = featureFactoryConfig,
requestingUser = requestingUser,
apiRequestID = apiRequestID
)
}
}
/**
* Represents a response after updating a resource's metadata.
*
* @param resourceIri the IRI of the resource.
* @param resourceClassIri the IRI of the resource class.
* @param lastModificationDate the resource's last modification date.
* @param maybeLabel the resource's new `rdfs:label`, if any.
* @param maybePermissions the resource's new permissions, if any.
* @param featureFactoryConfig the feature factory configuration.
*/
case class UpdateResourceMetadataResponseV2(resourceIri: IRI,
resourceClassIri: SmartIri,
lastModificationDate: Instant,
maybeLabel: Option[String] = None,
maybePermissions: Option[String] = None,
featureFactoryConfig: FeatureFactoryConfig)
extends KnoraJsonLDResponseV2 {
/**
* Converts the response to a data structure that can be used to generate JSON-LD.
*
* @param targetSchema the Knora API schema to be used in the JSON-LD document.
* @return a [[JsonLDDocument]] representing the response.
*/
override protected def toJsonLDDocument(targetSchema: ApiV2Schema,
settings: KnoraSettingsImpl,
schemaOptions: Set[SchemaOption]): JsonLDDocument = {
implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance
// Make the knora-api prefix for the target schema.
val knoraApiPrefixExpansion: IRI = targetSchema match {
case ApiV2Simple => OntologyConstants.KnoraApiV2Simple.KnoraApiV2PrefixExpansion
case ApiV2Complex => OntologyConstants.KnoraApiV2Complex.KnoraApiV2PrefixExpansion
}
// Make the JSON-LD document.
val context: JsonLDObject = JsonLDUtil.makeContext(
fixedPrefixes = Map(
"rdf" -> OntologyConstants.Rdf.RdfPrefixExpansion,
"rdfs" -> OntologyConstants.Rdfs.RdfsPrefixExpansion,
"xsd" -> OntologyConstants.Xsd.XsdPrefixExpansion,
OntologyConstants.KnoraApi.KnoraApiOntologyLabel -> knoraApiPrefixExpansion
)
)
val label_map = maybeLabel match {
case Some(maybeLabel) => Map(OntologyConstants.Rdfs.Label -> JsonLDString(maybeLabel))
case None => Map.empty[String, JsonLDValue]
}
val lastModificationDate_map =
Map(
OntologyConstants.KnoraApiV2Complex.LastModificationDate -> JsonLDUtil.datatypeValueToJsonLDObject(
value = lastModificationDate.toString,
datatype = OntologyConstants.Xsd.DateTimeStamp.toSmartIri
))
val permissions_map = maybePermissions match {
case Some(maybePermissions) =>
Map(OntologyConstants.KnoraApiV2Complex.HasPermissions -> JsonLDString(maybePermissions))
case None => Map.empty[String, JsonLDValue]
}
val resourceIri_resourceClassIri_map =
Map(
OntologyConstants.KnoraApiV2Complex.ResourceIri -> JsonLDString(resourceIri),
OntologyConstants.KnoraApiV2Complex.ResourceClassIri -> JsonLDString(resourceClassIri.toString)
)
val body = JsonLDObject(
resourceIri_resourceClassIri_map ++ label_map ++ lastModificationDate_map ++ permissions_map)
JsonLDDocument(body = body, context = context)
}
}
/**
* Represents a request to mark a resource as deleted or to erase it from the triplestore.
*
* @param resourceIri the IRI of the resource.
* @param resourceClassIri the IRI of the resource class.
* @param maybeDeleteComment a comment explaining why the resource is being marked as deleted.
* @param maybeDeleteDate a timestamp indicating when the resource was marked as deleted. If not supplied,
* the current time will be used.
* @param maybeLastModificationDate the resource's last modification date, if any.
* @param erase if `true`, the resource will be erased from the triplestore, otherwise it will be marked as deleted.
* @param featureFactoryConfig the feature factory configuration.
*/
case class DeleteOrEraseResourceRequestV2(resourceIri: IRI,
resourceClassIri: SmartIri,
maybeDeleteComment: Option[String] = None,
maybeDeleteDate: Option[Instant] = None,
maybeLastModificationDate: Option[Instant] = None,
erase: Boolean = false,
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM,
apiRequestID: UUID)
extends ResourcesResponderRequestV2