/
ListsResponderADM.scala
2359 lines (2067 loc) · 98.7 KB
/
ListsResponderADM.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.responders.admin
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.feature.FeatureFactoryConfig
import org.knora.webapi.messages.IriConversions._
import org.knora.webapi.messages.admin.responder.listsmessages.ListsMessagesUtilADM._
import org.knora.webapi.messages.admin.responder.listsmessages._
import org.knora.webapi.messages.admin.responder.projectsmessages.{ProjectADM, ProjectGetADM, ProjectIdentifierADM}
import org.knora.webapi.messages.admin.responder.usersmessages._
import org.knora.webapi.messages.store.triplestoremessages._
import org.knora.webapi.messages.util.rdf.SparqlSelectResult
import org.knora.webapi.messages.util.{KnoraSystemInstances, ResponderData}
import org.knora.webapi.messages.{OntologyConstants, SmartIri}
import org.knora.webapi.responders.Responder.handleUnexpectedMessage
import org.knora.webapi.responders.{IriLocker, Responder}
import scala.annotation.tailrec
import scala.collection.breakOut
import scala.concurrent.Future
/**
* A responder that returns information about hierarchical lists.
*/
class ListsResponderADM(responderData: ResponderData) extends Responder(responderData) {
// The IRI used to lock user creation and update
private val LISTS_GLOBAL_LOCK_IRI = "http://rdfh.ch/lists"
/**
* Receives a message of type [[ListsResponderRequestADM]], and returns an appropriate response message.
*/
def receive(msg: ListsResponderRequestADM) = msg match {
case ListsGetRequestADM(projectIri, featureFactoryConfig, requestingUser) =>
listsGetRequestADM(projectIri, featureFactoryConfig, requestingUser)
case ListGetRequestADM(listIri, featureFactoryConfig, requestingUser) =>
listGetRequestADM(listIri, featureFactoryConfig, requestingUser)
case ListNodeInfoGetRequestADM(listIri, featureFactoryConfig, requestingUser) =>
listNodeInfoGetRequestADM(listIri, featureFactoryConfig, requestingUser)
case NodePathGetRequestADM(iri, featureFactoryConfig, requestingUser) =>
nodePathGetAdminRequest(iri, requestingUser)
case ListCreateRequestADM(createRootNode, featureFactoryConfig, requestingUser, apiRequestID) =>
listCreateRequestADM(createRootNode, featureFactoryConfig, apiRequestID)
case ListChildNodeCreateRequestADM(createChildNodeRequest, featureFactoryConfig, requestingUser, apiRequestID) =>
listChildNodeCreateRequestADM(createChildNodeRequest, featureFactoryConfig, apiRequestID)
case NodeInfoChangeRequestADM(nodeIri, changeNodeRequest, featureFactoryConfig, requestingUser, apiRequestID) =>
nodeInfoChangeRequest(nodeIri, changeNodeRequest, featureFactoryConfig, apiRequestID)
case NodeNameChangeRequestADM(nodeIri, changeNodeNameRequest, featureFactoryConfig, requestingUser, apiRequestID) =>
nodeNameChangeRequest(nodeIri, changeNodeNameRequest, featureFactoryConfig, requestingUser, apiRequestID)
case NodeLabelsChangeRequestADM(nodeIri,
changeNodeLabelsRequest,
featureFactoryConfig,
requestingUser,
apiRequestID) =>
nodeLabelsChangeRequest(nodeIri, changeNodeLabelsRequest, featureFactoryConfig, requestingUser, apiRequestID)
case NodeCommentsChangeRequestADM(nodeIri,
changeNodeCommentsRequest,
featureFactoryConfig,
requestingUser,
apiRequestID) =>
nodeCommentsChangeRequest(nodeIri, changeNodeCommentsRequest, featureFactoryConfig, requestingUser, apiRequestID)
case NodePositionChangeRequestADM(nodeIri,
changeNodePositionRequest,
featureFactoryConfig,
requestingUser,
apiRequestID) =>
nodePositionChangeRequest(nodeIri, changeNodePositionRequest, featureFactoryConfig, requestingUser, apiRequestID)
case ListItemDeleteRequestADM(nodeIri, featureFactoryConfig, requestingUser, apiRequestID) =>
deleteListItemRequestADM(nodeIri, featureFactoryConfig, requestingUser, apiRequestID)
case other => handleUnexpectedMessage(other, log, this.getClass.getName)
}
/**
* Gets all lists and returns them as a [[ListsGetResponseADM]]. For performance reasons
* (as lists can be very large), we only return the head of the list, i.e. the root node without
* any children.
*
* @param projectIri the IRI of the project the list belongs to.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the user making the request.
* @return a [[ListsGetResponseADM]].
*/
private def listsGetRequestADM(projectIri: Option[IRI],
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM): Future[ListsGetResponseADM] = {
// log.debug("listsGetRequestV2")
for {
sparqlQuery <- Future(
org.knora.webapi.messages.twirl.queries.sparql.admin.txt
.getLists(
triplestore = settings.triplestoreType,
maybeProjectIri = projectIri
)
.toString()
)
listsResponse <- (storeManager ? SparqlExtendedConstructRequest(
sparql = sparqlQuery,
featureFactoryConfig = featureFactoryConfig
)).mapTo[SparqlExtendedConstructResponse]
// _ = log.debug("listsGetAdminRequest - listsResponse: {}", listsResponse )
// Seq(subjectIri, (objectIri -> Seq(stringWithOptionalLand))
statements = listsResponse.statements.toList
lists: Seq[ListNodeInfoADM] = statements.map {
case (listIri: SubjectV2, propsMap: Map[SmartIri, Seq[LiteralV2]]) =>
val name: Option[String] = propsMap
.get(OntologyConstants.KnoraBase.ListNodeName.toSmartIri)
.map(_.head.asInstanceOf[StringLiteralV2].value)
val labels: Seq[StringLiteralV2] = propsMap
.getOrElse(OntologyConstants.Rdfs.Label.toSmartIri, Seq.empty[StringLiteralV2])
.map(_.asInstanceOf[StringLiteralV2])
val comments: Seq[StringLiteralV2] = propsMap
.getOrElse(OntologyConstants.Rdfs.Comment.toSmartIri, Seq.empty[StringLiteralV2])
.map(_.asInstanceOf[StringLiteralV2])
ListRootNodeInfoADM(
id = listIri.toString,
projectIri = propsMap
.getOrElse(
OntologyConstants.KnoraBase.AttachedToProject.toSmartIri,
throw InconsistentRepositoryDataException("The required property 'attachedToProject' not found.")
)
.head
.asInstanceOf[IriLiteralV2]
.value,
name = name,
labels = StringLiteralSequenceV2(labels.toVector.sortBy(_.language)),
comments = StringLiteralSequenceV2(comments.toVector.sortBy(_.language))
)
}
// _ = log.debug("listsGetAdminRequest - items: {}", items)
} yield ListsGetResponseADM(lists = lists)
}
/**
* Retrieves a complete list (root and all children) from the triplestore and returns it as a optional [[ListADM]].
*
* @param rootNodeIri the Iri if the root node of the list to be queried.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the user making the request.
* @return a optional [[ListADM]].
*/
private def listGetADM(rootNodeIri: IRI,
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM): Future[Option[ListADM]] = {
for {
// this query will give us only the information about the root node.
exists <- rootNodeByIriExists(rootNodeIri)
// _ = log.debug(s"listGetADM - exists: {}", exists)
maybeList: Option[ListADM] <- if (exists) {
for {
// here we know that the list exists and it is fine if children is an empty list
children: Seq[ListChildNodeADM] <- getChildren(
ofNodeIri = rootNodeIri,
shallow = false,
featureFactoryConfig = featureFactoryConfig,
KnoraSystemInstances.Users.SystemUser
)
maybeRootNodeInfo <- listNodeInfoGetADM(
nodeIri = rootNodeIri,
featureFactoryConfig = featureFactoryConfig,
requestingUser = KnoraSystemInstances.Users.SystemUser
)
// _ = log.debug(s"listGetADM - maybeRootNodeInfo: {}", maybeRootNodeInfo)
rootNodeInfo = maybeRootNodeInfo match {
case Some(info: ListRootNodeInfoADM) => info.asInstanceOf[ListRootNodeInfoADM]
case Some(info: ListChildNodeInfoADM) =>
throw InconsistentRepositoryDataException(
"A child node info was found, although we are expecting a root node info. Please report this as a possible bug.")
case Some(_) | None =>
throw InconsistentRepositoryDataException(
"No info about list node found, although list node should exist. Please report this as a possible bug.")
}
list = ListADM(listinfo = rootNodeInfo, children = children)
} yield Some(list)
} else {
FastFuture.successful(None)
}
} yield maybeList
}
/**
* Retrieves a complete node (root or child) with all children from the triplestore and returns it as a [[ListItemGetResponseADM]].
* If an IRI of a root node is given, the response is a list with root node info and all chilren of the list.
* If an IRI of a child node is given, the response is a node with its information and all children of the sublist.
*
* @param nodeIri the Iri if the required node.
* @param requestingUser the user making the request.
* @return a [[ListItemGetResponseADM]].
*/
private def listGetRequestADM(nodeIri: IRI,
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM): Future[ListItemGetResponseADM] = {
def getNodeADM(childNode: ListChildNodeADM,
featureFactoryConfig: FeatureFactoryConfig): Future[ListNodeGetResponseADM] = {
for {
maybeNodeInfo <- listNodeInfoGetADM(
nodeIri = nodeIri,
featureFactoryConfig = featureFactoryConfig,
requestingUser = requestingUser
)
nodeinfo = maybeNodeInfo match {
case Some(childNodeInfo: ListChildNodeInfoADM) => childNodeInfo
case _ => throw NotFoundException(s"Information not found for node '$nodeIri'")
}
// make a NodeADM instance
entirenode = ListNodeGetResponseADM(
node = NodeADM(
nodeinfo = nodeinfo,
children = childNode.children
)
)
} yield entirenode
}
for {
exists <- rootNodeByIriExists(nodeIri)
// Is root node IRI given?
result <- if (exists) {
for {
// Yes. Get the entire list
maybeList <- listGetADM(
rootNodeIri = nodeIri,
featureFactoryConfig = featureFactoryConfig,
requestingUser = requestingUser
)
entireList = maybeList match {
case Some(list) => ListGetResponseADM(list = list)
case None => throw NotFoundException(s"List '$nodeIri' not found")
}
} yield entireList
} else {
for {
// No. Get the node and all its sublist children.
// First, get node itself and all children.
maybeNode <- listNodeGetADM(
nodeIri = nodeIri,
shallow = true,
featureFactoryConfig = featureFactoryConfig,
requestingUser = requestingUser
)
entireNode <- maybeNode match {
// make sure that it is a child node
case Some(childNode: ListChildNodeADM) =>
// get the info of the child node
getNodeADM(childNode, featureFactoryConfig)
case _ => throw NotFoundException(s"Node '$nodeIri' not found")
}
} yield entireNode
}
} yield result
}
/**
* Retrieves information about a single node (without information about children). The single node can be the
* lists root node or child node
*
* @param nodeIri the Iri if the list node to be queried.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the user making the request.
* @return a optional [[ListNodeInfoADM]].
*/
private def listNodeInfoGetADM(nodeIri: IRI,
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM): Future[Option[ListNodeInfoADM]] = {
for {
sparqlQuery <- Future(
org.knora.webapi.messages.twirl.queries.sparql.admin.txt
.getListNode(
triplestore = settings.triplestoreType,
nodeIri = nodeIri
)
.toString()
)
// _ = log.debug("listNodeInfoGetADM - sparqlQuery: {}", sparqlQuery)
listNodeResponse <- (storeManager ? SparqlExtendedConstructRequest(
sparql = sparqlQuery,
featureFactoryConfig = featureFactoryConfig
)).mapTo[SparqlExtendedConstructResponse]
statements: Map[SubjectV2, Map[SmartIri, Seq[LiteralV2]]] = listNodeResponse.statements
// _ = log.debug(s"listNodeInfoGetADM - statements: {}", statements)
maybeListNodeInfo = if (statements.nonEmpty) {
val nodeInfo: ListNodeInfoADM = statements.head match {
case (nodeIri: SubjectV2, propsMap: Map[SmartIri, Seq[LiteralV2]]) =>
val labels: Seq[StringLiteralV2] = propsMap
.getOrElse(OntologyConstants.Rdfs.Label.toSmartIri, Seq.empty[StringLiteralV2])
.map(_.asInstanceOf[StringLiteralV2])
val comments: Seq[StringLiteralV2] = propsMap
.getOrElse(OntologyConstants.Rdfs.Comment.toSmartIri, Seq.empty[StringLiteralV2])
.map(_.asInstanceOf[StringLiteralV2])
val attachedToProjectOption: Option[IRI] =
propsMap.get(OntologyConstants.KnoraBase.AttachedToProject.toSmartIri) match {
case Some(iris: Seq[LiteralV2]) =>
iris.headOption match {
case Some(iri: IriLiteralV2) => Some(iri.value)
case other =>
throw InconsistentRepositoryDataException(
s"Expected attached to project Iri as an IriLiteralV2 for list node $nodeIri, but got $other")
}
case None => None
}
val hasRootNodeOption: Option[IRI] =
propsMap.get(OntologyConstants.KnoraBase.HasRootNode.toSmartIri) match {
case Some(iris: Seq[LiteralV2]) =>
iris.headOption match {
case Some(iri: IriLiteralV2) => Some(iri.value)
case other =>
throw InconsistentRepositoryDataException(
s"Expected root node Iri as an IriLiteralV2 for list node $nodeIri, but got $other")
}
case None => None
}
val isRootNode: Boolean = propsMap.get(OntologyConstants.KnoraBase.IsRootNode.toSmartIri) match {
case Some(values: Seq[LiteralV2]) =>
values.headOption match {
case Some(value: BooleanLiteralV2) => value.value
case Some(other) =>
throw InconsistentRepositoryDataException(
s"Expected isRootNode as an BooleanLiteralV2 for list node $nodeIri, but got $other")
case None => false
}
case None => false
}
val positionOption: Option[Int] = propsMap
.get(OntologyConstants.KnoraBase.ListNodePosition.toSmartIri)
.map(_.head.asInstanceOf[IntLiteralV2].value)
if (isRootNode) {
ListRootNodeInfoADM(
id = nodeIri.toString,
projectIri = attachedToProjectOption.getOrElse(
throw InconsistentRepositoryDataException(
s"Required attachedToProject property missing for list node $nodeIri.")),
name = propsMap
.get(OntologyConstants.KnoraBase.ListNodeName.toSmartIri)
.map(_.head.asInstanceOf[StringLiteralV2].value),
labels = StringLiteralSequenceV2(labels.toVector.sortBy(_.language)),
comments = StringLiteralSequenceV2(comments.toVector.sortBy(_.language))
)
} else {
ListChildNodeInfoADM(
id = nodeIri.toString,
name = propsMap
.get(OntologyConstants.KnoraBase.ListNodeName.toSmartIri)
.map(_.head.asInstanceOf[StringLiteralV2].value),
labels = StringLiteralSequenceV2(labels.toVector.sortBy(_.language)),
comments = StringLiteralSequenceV2(comments.toVector.sortBy(_.language)),
position = positionOption.getOrElse(
throw InconsistentRepositoryDataException(
s"Required position property missing for list node $nodeIri.")),
hasRootNode = hasRootNodeOption.getOrElse(
throw InconsistentRepositoryDataException(
s"Required hasRootNode property missing for list node $nodeIri."))
)
}
}
Some(nodeInfo)
} else {
None
}
// _ = log.debug(s"listNodeInfoGetADM - maybeListNodeInfo: {}", maybeListNodeInfo)
} yield maybeListNodeInfo
}
/**
* Retrieves information about a single node (without information about children). The single node can be a
* root node or child node
*
* @param nodeIri the IRI of the list node to be queried.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the user making the request.
* @return a [[ChildNodeInfoGetResponseADM]].
*/
private def listNodeInfoGetRequestADM(nodeIri: IRI,
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM): Future[NodeInfoGetResponseADM] = {
for {
maybeListNodeInfoADM <- listNodeInfoGetADM(
nodeIri = nodeIri,
featureFactoryConfig = featureFactoryConfig,
requestingUser = requestingUser
)
result = maybeListNodeInfoADM match {
case Some(childInfo: ListChildNodeInfoADM) => ChildNodeInfoGetResponseADM(childInfo)
case Some(rootInfo: ListRootNodeInfoADM) => RootNodeInfoGetResponseADM(rootInfo)
case _ => throw NotFoundException(s"List node '$nodeIri' not found")
}
} yield result
}
/**
* Retrieves a complete node including children. The node can be the lists root node or child node.
*
* @param nodeIri the IRI of the list node to be queried.
* @param shallow denotes if all children or only the immediate children will be returned.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the user making the request.
* @return a optional [[ListNodeADM]]
*/
private def listNodeGetADM(nodeIri: IRI,
shallow: Boolean,
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM): Future[Option[ListNodeADM]] = {
for {
// this query will give us only the information about the root node.
sparqlQuery <- Future(
org.knora.webapi.messages.twirl.queries.sparql.admin.txt
.getListNode(
triplestore = settings.triplestoreType,
nodeIri = nodeIri
)
.toString()
)
listInfoResponse <- (storeManager ? SparqlExtendedConstructRequest(
sparql = sparqlQuery,
featureFactoryConfig = featureFactoryConfig,
)).mapTo[SparqlExtendedConstructResponse]
// _ = log.debug(s"listGetADM - statements: {}", MessageUtil.toSource(listInfoResponse.statements))
maybeListNode: Option[ListNodeADM] <- if (listInfoResponse.statements.nonEmpty) {
for {
// here we know that the list exists and it is fine if children is an empty list
children: Seq[ListChildNodeADM] <- getChildren(
ofNodeIri = nodeIri,
shallow = shallow,
featureFactoryConfig = featureFactoryConfig,
requestingUser = requestingUser
)
// _ = log.debug(s"listGetADM - children count: {}", children.size)
// Map(subjectIri -> (objectIri -> Seq(stringWithOptionalLand))
statements = listInfoResponse.statements
node: ListNodeADM = statements.head match {
case (nodeIri: SubjectV2, propsMap: Map[SmartIri, Seq[LiteralV2]]) =>
val labels: Seq[StringLiteralV2] = propsMap
.getOrElse(OntologyConstants.Rdfs.Label.toSmartIri, Seq.empty[StringLiteralV2])
.map(_.asInstanceOf[StringLiteralV2])
val comments: Seq[StringLiteralV2] = propsMap
.getOrElse(OntologyConstants.Rdfs.Comment.toSmartIri, Seq.empty[StringLiteralV2])
.map(_.asInstanceOf[StringLiteralV2])
val attachedToProjectOption: Option[IRI] =
propsMap.get(OntologyConstants.KnoraBase.AttachedToProject.toSmartIri) match {
case Some(iris: Seq[LiteralV2]) =>
iris.headOption match {
case Some(iri: IriLiteralV2) => Some(iri.value)
case other =>
throw InconsistentRepositoryDataException(
s"Expected attached to project Iri as an IriLiteralV2 for list node $nodeIri, but got $other")
}
case None => None
}
val hasRootNodeOption: Option[IRI] =
propsMap.get(OntologyConstants.KnoraBase.HasRootNode.toSmartIri) match {
case Some(iris: Seq[LiteralV2]) =>
iris.headOption match {
case Some(iri: IriLiteralV2) => Some(iri.value)
case other =>
throw InconsistentRepositoryDataException(
s"Expected root node Iri as an IriLiteralV2 for list node $nodeIri, but got $other")
}
case None => None
}
val isRootNode: Boolean = propsMap.get(OntologyConstants.KnoraBase.IsRootNode.toSmartIri) match {
case Some(values: Seq[LiteralV2]) =>
values.headOption match {
case Some(value: BooleanLiteralV2) => value.value
case Some(other) =>
throw InconsistentRepositoryDataException(
s"Expected isRootNode as an BooleanLiteralV2 for list node $nodeIri, but got $other")
case None => false
}
case None => false
}
val positionOption: Option[Int] = propsMap
.get(OntologyConstants.KnoraBase.ListNodePosition.toSmartIri)
.map(_.head.asInstanceOf[IntLiteralV2].value)
if (isRootNode) {
ListRootNodeADM(
id = nodeIri.toString,
projectIri = attachedToProjectOption.getOrElse(
throw InconsistentRepositoryDataException(
s"Required attachedToProject property missing for list node $nodeIri.")),
name = propsMap
.get(OntologyConstants.KnoraBase.ListNodeName.toSmartIri)
.map(_.head.asInstanceOf[StringLiteralV2].value),
labels = StringLiteralSequenceV2(labels.toVector.sortBy(_.language)),
comments = StringLiteralSequenceV2(comments.toVector.sortBy(_.language)),
children = children
)
} else {
ListChildNodeADM(
id = nodeIri.toString,
name = propsMap
.get(OntologyConstants.KnoraBase.ListNodeName.toSmartIri)
.map(_.head.asInstanceOf[StringLiteralV2].value),
labels = StringLiteralSequenceV2(labels.toVector.sortBy(_.language)),
comments = StringLiteralSequenceV2(comments.toVector.sortBy(_.language)),
position = positionOption.getOrElse(
throw InconsistentRepositoryDataException(
s"Required position property missing for list node $nodeIri.")),
hasRootNode = hasRootNodeOption.getOrElse(
throw InconsistentRepositoryDataException(
s"Required hasRootNode property missing for list node $nodeIri.")),
children = children
)
}
}
// _ = log.debug(s"listGetADM - list: {}", MessageUtil.toSource(list))
} yield Some(node)
} else {
FastFuture.successful(None)
}
} yield maybeListNode
}
/**
* Retrieves the child nodes from the triplestore. If shallow is true, then only the immediate children will be
* returned, otherwise all children and their children's children will be returned.
*
* @param ofNodeIri the IRI of the node for which children are to be returned.
* @param shallow denotes if all children or only the immediate children will be returned.
* @param featureFactoryConfig the feature factory configuration.
* @param requestingUser the user making the request.
* @return a sequence of [[ListChildNodeADM]].
*/
private def getChildren(ofNodeIri: IRI,
shallow: Boolean,
featureFactoryConfig: FeatureFactoryConfig,
requestingUser: UserADM): Future[Seq[ListChildNodeADM]] = {
/**
* This function recursively transforms SPARQL query results representing a hierarchical list into a [[ListChildNodeADM]].
*
* @param nodeIri the IRI of the node to be created.
* @param statements a [[Map]] in which each key is the IRI of a node in the hierarchical list, and each value is a [[Seq]]
* of SPARQL query results representing that node's children.
* @return a [[ListChildNodeADM]].
*/
def createChildNode(nodeIri: IRI, statements: Seq[(SubjectV2, Map[SmartIri, Seq[LiteralV2]])]): ListChildNodeADM = {
val propsMap: Map[SmartIri, Seq[LiteralV2]] = statements.filter(_._1 == IriSubjectV2(nodeIri)).head._2
val hasRootNode: IRI = propsMap
.getOrElse(
OntologyConstants.KnoraBase.HasRootNode.toSmartIri,
throw InconsistentRepositoryDataException(s"Required hasRootNode property missing for list node $nodeIri.")
)
.head
.toString
val nameOption = propsMap
.get(OntologyConstants.KnoraBase.ListNodeName.toSmartIri)
.map(_.head.asInstanceOf[StringLiteralV2].value)
val labels: Seq[StringLiteralV2] = propsMap
.getOrElse(OntologyConstants.Rdfs.Label.toSmartIri, Seq.empty[StringLiteralV2])
.map(_.asInstanceOf[StringLiteralV2])
val comments: Seq[StringLiteralV2] = propsMap
.getOrElse(OntologyConstants.Rdfs.Comment.toSmartIri, Seq.empty[StringLiteralV2])
.map(_.asInstanceOf[StringLiteralV2])
val positionOption: Option[Int] = propsMap
.get(OntologyConstants.KnoraBase.ListNodePosition.toSmartIri)
.map(_.head.asInstanceOf[IntLiteralV2].value)
val position = positionOption.getOrElse(
throw InconsistentRepositoryDataException(s"Required position property missing for list node $nodeIri."))
val children: Seq[ListChildNodeADM] = propsMap.get(OntologyConstants.KnoraBase.HasSubListNode.toSmartIri) match {
case Some(iris: Seq[LiteralV2]) =>
if (!shallow) {
// if not shallow then get the children of this node
iris.map { iri =>
createChildNode(iri.toString, statements)
}
} else {
// if shallow, then we don't need the children
Seq.empty[ListChildNodeADM]
}
case None => Seq.empty[ListChildNodeADM]
}
ListChildNodeADM(
id = nodeIri,
name = nameOption,
labels = StringLiteralSequenceV2(labels.toVector.sortBy(_.language)),
comments = StringLiteralSequenceV2(comments.toVector.sortBy(_.language)),
children = children.map(_.sorted),
position = position,
hasRootNode = hasRootNode
)
}
for {
nodeChildrenQuery <- Future {
org.knora.webapi.messages.twirl.queries.sparql.admin.txt
.getListNodeWithChildren(
triplestore = settings.triplestoreType,
startNodeIri = ofNodeIri
)
.toString()
}
nodeWithChildrenResponse <- (storeManager ? SparqlExtendedConstructRequest(
sparql = nodeChildrenQuery,
featureFactoryConfig = featureFactoryConfig,
)).mapTo[SparqlExtendedConstructResponse]
statements: Seq[(SubjectV2, Map[SmartIri, Seq[LiteralV2]])] = nodeWithChildrenResponse.statements.toList
startNodePropsMap: Map[SmartIri, Seq[LiteralV2]] = statements.filter(_._1 == IriSubjectV2(ofNodeIri)).head._2
children: Seq[ListChildNodeADM] = startNodePropsMap.get(OntologyConstants.KnoraBase.HasSubListNode.toSmartIri) match {
case Some(iris: Seq[LiteralV2]) =>
iris.map { iri =>
createChildNode(iri.toString, statements)
}
case None => Seq.empty[ListChildNodeADM]
}
sortedChildren = children.sortBy(_.position) map (_.sorted)
} yield sortedChildren
}
/**
* Provides the path to a particular hierarchical list node.
*
* @param queryNodeIri the IRI of the node whose path is to be queried.
* @param requestingUser the user making the request.
*/
private def nodePathGetAdminRequest(queryNodeIri: IRI, requestingUser: UserADM): Future[NodePathGetResponseADM] = {
/**
* Recursively constructs the path to a node.
*
* @param node the IRI of the node whose path is to be constructed.
* @param nodeMap a [[Map]] of node IRIs to query result row data, in the format described below.
* @param parentMap a [[Map]] of child node IRIs to parent node IRIs.
* @param path the path constructed so far.
* @return the complete path to `node`.
*/
@tailrec
def makePath(node: IRI,
nodeMap: Map[IRI, Map[String, String]],
parentMap: Map[IRI, IRI],
path: Seq[NodePathElementADM]): Seq[NodePathElementADM] = {
// Get the details of the node.
val nodeData = nodeMap(node)
// Construct a NodePathElementV2 containing those details.
val pathElement = NodePathElementADM(
id = nodeData("node"),
name = nodeData.get("nodeName"),
labels = if (nodeData.contains("label")) {
StringLiteralSequenceV2(Vector(StringLiteralV2(nodeData("label"))))
} else {
StringLiteralSequenceV2(Vector.empty[StringLiteralV2])
},
comments = StringLiteralSequenceV2(Vector.empty[StringLiteralV2])
)
// Add it to the path.
val newPath = pathElement +: path
// Does this node have a parent?
parentMap.get(pathElement.id) match {
case Some(parentIri) =>
// Yes: recurse.
makePath(parentIri, nodeMap, parentMap, newPath)
case None =>
// No: the path is complete.
newPath
}
}
// TODO: Rewrite using a construct sparql query
for {
nodePathQuery <- Future {
org.knora.webapi.messages.twirl.queries.sparql.admin.txt
.getNodePath(
triplestore = settings.triplestoreType,
queryNodeIri = queryNodeIri,
preferredLanguage = requestingUser.lang,
fallbackLanguage = settings.fallbackLanguage
)
.toString()
}
nodePathResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(nodePathQuery))
.mapTo[SparqlSelectResult]
/*
If we request the path to the node <http://rdfh.ch/lists/c7f07a3fc1> ("Heidi Film"), the response has the following format:
node nodeName label child
<http://rdfh.ch/lists/c7f07a3fc1> 1 Heidi Film
<http://rdfh.ch/lists/2ebd2706c1> 7 FILM UND FOTO <http://rdfh.ch/lists/c7f07a3fc1>
<http://rdfh.ch/lists/691eee1cbe> 4KUN ART <http://rdfh.ch/lists/2ebd2706c1>
The order of the rows is arbitrary. Now we need to reconstruct the path based on the parent-child relationships between
nodes.
*/
// A Map of node IRIs to query result rows.
nodeMap: Map[IRI, Map[String, String]] = nodePathResponse.results.bindings.map { row =>
row.rowMap("node") -> row.rowMap
}(breakOut)
// A Map of child node IRIs to parent node IRIs.
parentMap: Map[IRI, IRI] = nodePathResponse.results.bindings.foldLeft(Map.empty[IRI, IRI]) {
case (acc, row) =>
row.rowMap.get("child") match {
case Some(child) => acc + (child -> row.rowMap("node"))
case None => acc
}
}
} yield NodePathGetResponseADM(elements = makePath(queryNodeIri, nodeMap, parentMap, Nil))
}
/**
* Creates a node (root or child).
*
* @param createNodeRequest the new node's information.
* @param featureFactoryConfig the feature factory configuration.
* @return a [newListNodeIri]
*/
private def createNode(createNodeRequest: CreateNodeApiRequestADM,
featureFactoryConfig: FeatureFactoryConfig): Future[IRI] = {
def getPositionOfNewChild(children: Seq[ListChildNodeADM]): Int = {
if (createNodeRequest.position.exists(_ > children.size)) {
val givenPosition = createNodeRequest.position.get
throw BadRequestException(
s"Invalid position given $givenPosition, maximum allowed position is = ${children.size}.")
}
val position = if (createNodeRequest.position.isEmpty || createNodeRequest.position.exists(_.equals(-1))) {
children.size
} else {
createNodeRequest.position.get
}
position
}
def getRootNodeIri(parentListNode: ListNodeADM): IRI = {
parentListNode match {
case root: ListRootNodeADM => root.id
case child: ListChildNodeADM => child.hasRootNode
}
}
def getRootNodeAndPositionOfNewChild(parentNodeIri: IRI,
dataNamedGraph: IRI,
featureFactoryConfig: FeatureFactoryConfig): Future[(Some[Int], Some[IRI])] = {
for {
/* Verify that the list node exists by retrieving the whole node including children one level deep (need for position calculation) */
maybeParentListNode <- listNodeGetADM(
nodeIri = parentNodeIri,
shallow = true,
featureFactoryConfig = featureFactoryConfig,
requestingUser = KnoraSystemInstances.Users.SystemUser
)
(parentListNode: ListNodeADM, children: Seq[ListChildNodeADM]) = maybeParentListNode match {
case Some(node: ListRootNodeADM) => (node.asInstanceOf[ListRootNodeADM], node.children)
case Some(node: ListChildNodeADM) => (node.asInstanceOf[ListChildNodeADM], node.children)
case Some(_) | None => throw BadRequestException(s"List node '$parentNodeIri' not found.")
}
// get position of the new child
position = getPositionOfNewChild(children)
// Is the node supposed to be inserted in a specific position in array of children?
_ <- if (position != children.size) {
// Yes. Shift the siblings after the given position to right in order to free the position.
for {
// shift siblings that are after given position to right
updatedSiblings <- shiftNodes(
startPos = position,
endPos = children.size - 1,
nodes = children,
shiftToLeft = false,
dataNamedGraph = dataNamedGraph,
featureFactoryConfig = featureFactoryConfig
)
} yield updatedSiblings
} else {
// No. new node will be appended to the end, no shifting is necessary.
Future.successful(children)
}
/* get the root node, depending on the type of the parent */
rootNodeIri = getRootNodeIri(parentListNode)
} yield (Some(position), Some(rootNodeIri))
}
for {
/* Verify that the project exists by retrieving it. We need the project information so that we can calculate the data graph and IRI for the new node. */
maybeProject <- (responderManager ? ProjectGetADM(
identifier = ProjectIdentifierADM(maybeIri = Some(createNodeRequest.projectIri)),
featureFactoryConfig = featureFactoryConfig,
KnoraSystemInstances.Users.SystemUser
)).mapTo[Option[ProjectADM]]
project: ProjectADM = maybeProject match {
case Some(project: ProjectADM) => project
case None => throw BadRequestException(s"Project '${createNodeRequest.projectIri}' not found.")
}
/* verify that the list node name is unique for the project */
projectUniqueNodeName <- listNodeNameIsProjectUnique(createNodeRequest.projectIri, createNodeRequest.name)
_ = if (!projectUniqueNodeName) {
throw BadRequestException(
s"The node name ${createNodeRequest.name.get} is already used by a list inside the project ${createNodeRequest.projectIri}.")
}
// calculate the data named graph
dataNamedGraph: IRI = stringFormatter.projectDataNamedGraphV2(project)
// if parent node is known, find the root node of the list and the position of the new child node
(position: Option[Int], rootNodeIri: Option[IRI]) <- if (createNodeRequest.parentNodeIri.nonEmpty) {
getRootNodeAndPositionOfNewChild(parentNodeIri = createNodeRequest.parentNodeIri.get,
dataNamedGraph = dataNamedGraph,
featureFactoryConfig = featureFactoryConfig)
} else {
Future(None, None)
}
// check the custom IRI; if not given, create an unused IRI
customListIri: Option[SmartIri] = createNodeRequest.id.map(iri => iri.toSmartIri)
maybeShortcode: String = project.shortcode
newListNodeIri: IRI <- checkOrCreateEntityIri(customListIri, stringFormatter.makeRandomListIri(maybeShortcode))
// Create the new list node
createNewListSparqlString = org.knora.webapi.messages.twirl.queries.sparql.admin.txt
.createNewListNode(
dataNamedGraph = dataNamedGraph,
triplestore = settings.triplestoreType,
listClassIri = OntologyConstants.KnoraBase.ListNode,
projectIri = createNodeRequest.projectIri,
nodeIri = newListNodeIri,
parentNodeIri = createNodeRequest.parentNodeIri,
rootNodeIri = rootNodeIri,
position = position,
maybeName = createNodeRequest.name,
maybeLabels = createNodeRequest.labels,
maybeComments = createNodeRequest.comments
)
.toString
_ <- (storeManager ? SparqlUpdateRequest(createNewListSparqlString)).mapTo[SparqlUpdateResponse]
} yield newListNodeIri
}
/**
* Creates a list.
*
* @param createRootRequest the new list's information.
* @param featureFactoryConfig the feature factory configuration.
* @param apiRequestID the unique api request ID.
* @return a [[RootNodeInfoGetResponseADM]]
*/
private def listCreateRequestADM(createRootRequest: CreateNodeApiRequestADM,
featureFactoryConfig: FeatureFactoryConfig,
apiRequestID: UUID): Future[ListGetResponseADM] = {
/**
* The actual task run with an IRI lock.
*/
def listCreateTask(createRootRequest: CreateNodeApiRequestADM,
featureFactoryConfig: FeatureFactoryConfig,
apiRequestID: UUID): Future[ListGetResponseADM] =
for {
listRootIri <- createNode(createRootRequest, featureFactoryConfig)
// Verify that the list was created.
maybeNewListADM <- listGetADM(
rootNodeIri = listRootIri,
featureFactoryConfig = featureFactoryConfig,
requestingUser = KnoraSystemInstances.Users.SystemUser
)
newListADM = maybeNewListADM.getOrElse(
throw UpdateNotPerformedException(
s"List $listRootIri was not created. Please report this as a possible bug."))
// _ = log.debug(s"listCreateRequestADM - newListADM: $newListADM")
} yield ListGetResponseADM(newListADM)
for {
// run list creation with an global IRI lock
taskResult <- IriLocker.runWithIriLock(
apiRequestID,
LISTS_GLOBAL_LOCK_IRI,
() => listCreateTask(createRootRequest, featureFactoryConfig, apiRequestID)
)
} yield taskResult
}
/**
* Changes basic node information stored (root or child)
*
* @param nodeIri the list's IRI.
* @param changeNodeRequest the new node information.
* @param featureFactoryConfig the feature factory configuration.
* @param apiRequestID the unique api request ID.
* @return a [[NodeInfoGetResponseADM]]
* @throws ForbiddenException in the case that the user is not allowed to perform the operation.
* @throws BadRequestException in the case when the list IRI given in the path does not match with the one given in the payload.
* @throws UpdateNotPerformedException in the case something else went wrong, and the change could not be performed.
*/
private def nodeInfoChangeRequest(nodeIri: IRI,
changeNodeRequest: ChangeNodeInfoApiRequestADM,
featureFactoryConfig: FeatureFactoryConfig,
apiRequestID: UUID): Future[NodeInfoGetResponseADM] = {
def verifyUpdatedNode(updatedNode: ListNodeInfoADM): Unit = {