/
ResourcesResponderV1.scala
executable file
·3624 lines (3223 loc) · 182 KB
/
ResourcesResponderV1.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright © 2021 - 2022 Swiss National Data and Service Center for the Humanities and/or DaSCH Service Platform contributors.
* SPDX-License-Identifier: Apache-2.0
*/
package org.knora.webapi.responders.v1
import akka.http.scaladsl.util.FastFuture
import akka.pattern._
import java.time.Instant
import java.util.UUID
import scala.concurrent.Future
import scala.util.Failure
import scala.util.Success
import scala.util.Try
import dsp.constants.SalsahGui
import dsp.errors._
import dsp.schema.domain.Cardinality._
import org.knora.webapi._
import org.knora.webapi.messages.IriConversions._
import org.knora.webapi.messages.OntologyConstants
import org.knora.webapi.messages.SmartIri
import org.knora.webapi.messages.StringFormatter
import org.knora.webapi.messages.admin.responder.permissionsmessages.DefaultObjectAccessPermissionsStringForPropertyGetADM
import org.knora.webapi.messages.admin.responder.permissionsmessages.DefaultObjectAccessPermissionsStringForResourceClassGetADM
import org.knora.webapi.messages.admin.responder.permissionsmessages.DefaultObjectAccessPermissionsStringResponseADM
import org.knora.webapi.messages.admin.responder.permissionsmessages.ResourceCreateOperation
import org.knora.webapi.messages.admin.responder.projectsmessages.ProjectADM
import org.knora.webapi.messages.admin.responder.projectsmessages.ProjectGetRequestADM
import org.knora.webapi.messages.admin.responder.projectsmessages.ProjectGetResponseADM
import org.knora.webapi.messages.admin.responder.projectsmessages.ProjectIdentifierADM._
import org.knora.webapi.messages.admin.responder.usersmessages.UserADM
import org.knora.webapi.messages.store.triplestoremessages._
import org.knora.webapi.messages.twirl.SparqlTemplateResourceToCreate
import org.knora.webapi.messages.util.GroupedProps._
import org.knora.webapi.messages.util._
import org.knora.webapi.messages.util.rdf.SparqlSelectResult
import org.knora.webapi.messages.util.rdf.VariableResultsRow
import org.knora.webapi.messages.v1.responder.ontologymessages._
import org.knora.webapi.messages.v1.responder.projectmessages._
import org.knora.webapi.messages.v1.responder.resourcemessages._
import org.knora.webapi.messages.v1.responder.valuemessages._
import org.knora.webapi.messages.v2.responder.UpdateResultInProject
import org.knora.webapi.messages.v2.responder.ontologymessages.OntologyMetadataGetByIriRequestV2
import org.knora.webapi.messages.v2.responder.ontologymessages.OntologyMetadataV2
import org.knora.webapi.messages.v2.responder.ontologymessages.OwlCardinality.KnoraCardinalityInfo
import org.knora.webapi.messages.v2.responder.ontologymessages.ReadOntologyMetadataV2
import org.knora.webapi.messages.v2.responder.valuemessages.FileValueContentV2
import org.knora.webapi.responders.IriLocker
import org.knora.webapi.responders.Responder
import org.knora.webapi.responders.v2.ResourceUtilV2
import org.knora.webapi.util.ActorUtil
import org.knora.webapi.util.ApacheLuceneSupport.MatchStringWhileTyping
/**
* Responds to requests for information about resources, and returns responses in Knora API v1 format.
*/
class ResourcesResponderV1(responderData: ResponderData) extends Responder(responderData.actorDeps) {
// Converts SPARQL query results to ApiValueV1 objects.
private val valueUtilV1 = new ValueUtilV1(responderData.appConfig)
/**
* Receives a message extending [[ResourcesResponderRequestV1]], and returns an appropriate response message.
*/
def receive(msg: ResourcesResponderRequestV1) = msg match {
case ResourceInfoGetRequestV1(resourceIri, userProfile) =>
getResourceInfoResponseV1(resourceIri, userProfile)
case ResourceFullGetRequestV1(resourceIri, userProfile, getIncoming) =>
getFullResponseV1(resourceIri, userProfile, getIncoming)
case ResourceContextGetRequestV1(resourceIri, userProfile, resinfo) =>
getContextResponseV1(resourceIri, userProfile, resinfo)
case ResourceRightsGetRequestV1(resourceIri, userProfile) =>
getRightsResponseV1(resourceIri, userProfile)
case graphDataGetRequest: GraphDataGetRequestV1 => getGraphDataResponseV1(graphDataGetRequest)
case ResourceSearchGetRequestV1(
searchString: String,
resourceIri: Option[IRI],
numberOfProps: Int,
limitOfResults: Int,
userProfile: UserADM
) =>
getResourceSearchResponseV1(searchString, resourceIri, numberOfProps, limitOfResults, userProfile)
case ResourceCreateRequestV1(
resourceTypeIri,
label,
values,
file,
projectIri,
userProfile,
apiRequestID
) =>
createNewResource(
resourceTypeIri,
label,
values,
file,
projectIri,
userProfile,
apiRequestID
)
case MultipleResourceCreateRequestV1(
resourcesToCreate,
projectIri,
userProfile,
apiRequestID
) =>
createMultipleNewResources(resourcesToCreate, projectIri, userProfile, apiRequestID)
case ResourceCheckClassRequestV1(resourceIri: IRI, owlClass: IRI, userProfile: UserADM) =>
checkResourceClass(resourceIri, owlClass, userProfile)
case PropertiesGetRequestV1(resourceIri: IRI, userProfile: UserADM) =>
getPropertiesV1(resourceIri = resourceIri, userProfile = userProfile)
case resourceDeleteRequest: ResourceDeleteRequestV1 => deleteResourceV1(resourceDeleteRequest)
case ChangeResourceLabelRequestV1(resourceIri, label, userProfile, apiRequestID) =>
changeResourceLabelV1(resourceIri, label, apiRequestID, userProfile)
case UnexpectedMessageRequest() => makeFutureOfUnit
case InternalServerExceptionMessageRequest() => makeInternalServerException
case other => handleUnexpectedMessage(other, log, this.getClass.getName)
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Methods for generating complete API responses.
// TODO: move this to a test responder in the test package.
private def makeInternalServerException: Future[String] =
Future.failed(UpdateNotPerformedException("thrown inside the ResourcesResponder"))
// TODO: move this to a test responder in the test package.
private def makeFutureOfUnit: Future[Unit] =
Future(())
/**
* Gets a graph of resources that are reachable via links to or from a given resource.
*
* @param graphDataGetRequest a [[GraphDataGetRequestV1]] specifying the characteristics of the graph.
* @return a [[GraphDataGetResponseV1]] representing the requested graph.
*/
private def getGraphDataResponseV1(graphDataGetRequest: GraphDataGetRequestV1): Future[GraphDataGetResponseV1] = {
val userProfileV1 = graphDataGetRequest.userADM.asUserProfileV1
/**
* The internal representation of a node returned by a SPARQL query generated by the `getGraphData` template.
*
* @param nodeIri the IRI of the node.
* @param nodeClass the IRI of the node's class.
* @param nodeLabel the node's label.
* @param nodeCreator the node's creator.
* @param nodeProject the node's project.
* @param nodePermissions the node's permissions.
*/
case class QueryResultNode(
nodeIri: IRI,
nodeClass: IRI,
nodeLabel: String,
nodeCreator: IRI,
nodeProject: IRI,
nodePermissions: String
)
/**
* The internal representation of an edge returned by a SPARQL query generated by the `getGraphData` template.
*
* @param linkValueIri the IRI of the link value.
* @param sourceNodeIri the IRI of the source node.
* @param targetNodeIri the IRI of the target node.
* @param linkProp the IRI of the link property.
* @param linkValueCreator the link value's creator.
* @param sourceNodeProject the project of the source node.
* @param linkValuePermissions the link value's permissions.
*/
case class QueryResultEdge(
linkValueIri: IRI,
sourceNodeIri: IRI,
targetNodeIri: IRI,
linkProp: IRI,
linkValueCreator: IRI,
sourceNodeProject: IRI,
linkValuePermissions: String
)
/**
* Represents results returned by a SPARQL query generated by the `getGraphData` template.
*
* @param nodes the nodes that were returned by the query.
* @param edges the edges that were returned by the query.
*/
case class GraphQueryResults(
nodes: Set[QueryResultNode] = Set.empty[QueryResultNode],
edges: Set[QueryResultEdge] = Set.empty[QueryResultEdge]
)
/**
* Recursively queries outbound or inbound links from/to a resource.
*
* @param startNode the node to use as the starting point of the query. The user is assumed to have permission
* to see this node.
* @param outbound `true` to get outbound links, `false` to get inbound links.
* @param depth the maximum depth of the query.
* @param traversedEdges edges that have already been traversed.
* @return a [[GraphQueryResults]].
*/
def traverseGraph(
startNode: QueryResultNode,
outbound: Boolean,
depth: Int,
traversedEdges: Set[QueryResultEdge] = Set.empty[QueryResultEdge]
): Future[GraphQueryResults] = {
if (depth < 1) Future.failed(AssertionException("Depth must be at least 1"))
for {
// Get the direct links from/to the start node.
sparql <- Future(
org.knora.webapi.messages.twirl.queries.sparql.v1.txt
.getGraphData(
startNodeIri = startNode.nodeIri,
startNodeOnly = false,
outbound = outbound // true to query outbound edges, false to query inbound edges
)
.toString()
)
// _ = println(sparql)
response: SparqlSelectResult <- appActor.ask(SparqlSelectRequest(sparql)).mapTo[SparqlSelectResult]
rows = response.results.bindings
// Did we get any results?
recursiveResults: GraphQueryResults <-
if (rows.isEmpty) {
// No. Return nothing.
Future(GraphQueryResults())
} else {
// Yes. Get the nodes from the query results.
val otherNodes: Seq[QueryResultNode] = rows.map { row =>
val rowMap = row.rowMap
QueryResultNode(
nodeIri = rowMap("node"),
nodeClass = rowMap("nodeClass"),
nodeLabel = rowMap("nodeLabel"),
nodeCreator = rowMap("nodeCreator"),
nodeProject = rowMap("nodeProject"),
nodePermissions = rowMap("nodePermissions")
)
}.filter { node =>
// Filter out the nodes that the user doesn't have permission to see.
PermissionUtilADM
.getUserPermissionV1(
entityIri = node.nodeIri,
entityCreator = node.nodeCreator,
entityProject = node.nodeProject,
entityPermissionLiteral = node.nodePermissions,
userProfile = userProfileV1
)
.nonEmpty
}
// Collect the IRIs of the nodes that the user has permission to see, including the start node.
val visibleNodeIris = otherNodes.map(_.nodeIri).toSet + startNode.nodeIri
// Get the edges from the query results.
val edges: Set[QueryResultEdge] = rows.map { row =>
val rowMap = row.rowMap
val nodeIri = rowMap("node")
// The SPARQL query takes a start node and returns the other node in the edge.
//
// If we're querying outbound edges, the start node is the source node, and the other
// node is the target node.
//
// If we're querying inbound edges, the start node is the target node, and the other
// node is the source node.
QueryResultEdge(
linkValueIri = rowMap("linkValue"),
sourceNodeIri = if (outbound) startNode.nodeIri else nodeIri,
targetNodeIri = if (outbound) nodeIri else startNode.nodeIri,
linkProp = rowMap("linkProp"),
linkValueCreator = rowMap("linkValueCreator"),
sourceNodeProject = if (outbound) startNode.nodeProject else rowMap("nodeProject"),
linkValuePermissions = rowMap("linkValuePermissions")
)
}.filter { edge =>
// Filter out the edges that the user doesn't have permission to see. To see an edge,
// the user must have some permission on the link value and on the source and target
// nodes.
val hasPermission =
visibleNodeIris.contains(edge.sourceNodeIri) && visibleNodeIris.contains(edge.targetNodeIri) &&
PermissionUtilADM
.getUserPermissionV1(
entityIri = edge.linkValueIri,
entityCreator = edge.linkValueCreator,
entityProject = edge.sourceNodeProject,
entityPermissionLiteral = edge.linkValuePermissions,
userProfile = userProfileV1
)
.nonEmpty
// Filter out edges we've already traversed.
val isRedundant = traversedEdges.contains(edge)
// if (isRedundant) println(s"filtering out edge from ${edge.sourceNodeIri} to ${edge.targetNodeIri}")
hasPermission && !isRedundant
}.toSet
// Include only nodes that are reachable via edges that we're going to traverse (i.e. the user
// has permission to see those edges, and we haven't already traversed them).
val visibleNodeIrisFromEdges = edges.map(_.sourceNodeIri) ++ edges.map(_.targetNodeIri)
val filteredOtherNodes = otherNodes.filter(node => visibleNodeIrisFromEdges.contains(node.nodeIri))
// Make a GraphQueryResults containing the resulting nodes and edges, including the start
// node.
val results = GraphQueryResults(nodes = filteredOtherNodes.toSet + startNode, edges = edges)
// Have we reached the maximum depth?
if (depth == 1) {
// Yes. Just return the results we have.
Future(results)
} else {
// No. Recursively get results for each of the nodes we found.
val lowerResultFutures: Seq[Future[GraphQueryResults]] = filteredOtherNodes.map { node =>
traverseGraph(
startNode = node,
outbound = outbound,
depth = depth - 1,
traversedEdges = traversedEdges ++ edges
)
}
val lowerResultsFuture: Future[Seq[GraphQueryResults]] = Future.sequence(lowerResultFutures)
// Return those results plus the ones we found.
for {
lowerResultsSeq <- lowerResultsFuture
} yield lowerResultsSeq.foldLeft(results) { case (acc, lowerResults) =>
GraphQueryResults(
nodes = acc.nodes ++ lowerResults.nodes,
edges = acc.edges ++ lowerResults.edges
)
}
}
}
} yield recursiveResults
}
for {
// Get the start node.
sparql <- Future(
org.knora.webapi.messages.twirl.queries.sparql.v1.txt
.getGraphData(
startNodeIri = graphDataGetRequest.resourceIri,
startNodeOnly = true
)
.toString()
)
// _ = println(sparql)
response: SparqlSelectResult <- appActor.ask(SparqlSelectRequest(sparql)).mapTo[SparqlSelectResult]
rows = response.results.bindings
_ = if (rows.isEmpty) {
throw NotFoundException(s"Resource ${graphDataGetRequest.resourceIri} not found (it may have been deleted)")
}
firstRowMap = rows.head.rowMap
startNode: QueryResultNode = QueryResultNode(
nodeIri = firstRowMap("node"),
nodeClass = firstRowMap("nodeClass"),
nodeLabel = firstRowMap("nodeLabel"),
nodeCreator = firstRowMap("nodeCreator"),
nodeProject = firstRowMap("nodeProject"),
nodePermissions = firstRowMap("nodePermissions")
)
// Make sure the user has permission to see the start node.
_ = if (
PermissionUtilADM
.getUserPermissionV1(
entityIri = startNode.nodeIri,
entityCreator = startNode.nodeCreator,
entityProject = startNode.nodeProject,
entityPermissionLiteral = startNode.nodePermissions,
userProfile = userProfileV1
)
.isEmpty
) {
throw ForbiddenException(
s"User ${graphDataGetRequest.userADM.id} does not have permission to view resource ${graphDataGetRequest.resourceIri}"
)
}
// Recursively get the graph containing outbound links.
outboundQueryResults: GraphQueryResults <- traverseGraph(
startNode = startNode,
outbound = true,
depth = graphDataGetRequest.depth
)
// Recursively get the graph containing inbound links.
inboundQueryResults: GraphQueryResults <- traverseGraph(
startNode = startNode,
outbound = false,
depth = graphDataGetRequest.depth
)
// Combine the outbound and inbound graphs into a single graph.
nodes: Set[QueryResultNode] = outboundQueryResults.nodes ++ inboundQueryResults.nodes + startNode
edges: Set[QueryResultEdge] = outboundQueryResults.edges ++ inboundQueryResults.edges
// Get the labels of the resource classes and properties from the ontology responder.
resourceClassIris = nodes.map(_.nodeClass)
propertyIris = edges.map(_.linkProp)
entityInfoRequest = EntityInfoGetRequestV1(
resourceClassIris = resourceClassIris,
propertyIris = propertyIris,
userProfile = graphDataGetRequest.userADM
)
entityInfoResponse: EntityInfoGetResponseV1 <- appActor
.ask(entityInfoRequest)
.mapTo[EntityInfoGetResponseV1]
// Convert each node to a GraphNodeV1 for the API response message.
resultNodes: Vector[GraphNodeV1] = nodes.map { node =>
// Get the resource class's label from the ontology information.
val resourceClassLabel = entityInfoResponse
.resourceClassInfoMap(node.nodeClass)
.getPredicateObject(
predicateIri = OntologyConstants.Rdfs.Label,
preferredLangs = Some(
graphDataGetRequest.userADM.lang,
responderData.appConfig.fallbackLanguage
)
)
.getOrElse(
throw InconsistentRepositoryDataException(
s"Resource class ${node.nodeClass} has no rdfs:label"
)
)
GraphNodeV1(
resourceIri = node.nodeIri,
resourceLabel = node.nodeLabel,
resourceClassIri = node.nodeClass,
resourceClassLabel = resourceClassLabel
)
}.toVector
// Convert each edge to a GraphEdgeV1 for the API response message.
resultEdges: Vector[GraphEdgeV1] = edges.map { edge =>
// Get the link property's label from the ontology information.
val propertyLabel = entityInfoResponse
.propertyInfoMap(edge.linkProp)
.getPredicateObject(
predicateIri = OntologyConstants.Rdfs.Label,
preferredLangs = Some(
graphDataGetRequest.userADM.lang,
responderData.appConfig.fallbackLanguage
)
)
.getOrElse(
throw InconsistentRepositoryDataException(
s"Property ${edge.linkProp} has no rdfs:label"
)
)
GraphEdgeV1(
source = edge.sourceNodeIri,
target = edge.targetNodeIri,
propertyIri = edge.linkProp,
propertyLabel = propertyLabel
)
}.toVector
} yield GraphDataGetResponseV1(nodes = resultNodes, edges = resultEdges)
}
/**
* Returns an instance of [[ResourceInfoResponseV1]] describing a resource, in Knora API v1 format.
*
* @param resourceIri the IRI of the resource to be queried.
* @param userProfile the profile of the user making the request.
* @return a [[ResourceInfoResponseV1]] containing a representation of the resource.
*/
private def getResourceInfoResponseV1(
resourceIri: IRI,
userProfile: UserADM
): Future[ResourceInfoResponseV1] =
for {
(userPermissions, resInfo) <- getResourceInfoV1(
resourceIri = resourceIri,
userProfile = userProfile,
queryOntology = true
)
} yield userPermissions match {
case Some(_) =>
ResourceInfoResponseV1(
resource_info = Some(resInfo),
rights = userPermissions
)
case None =>
throw ForbiddenException(s"User ${userProfile.id} does not have permission to view resource $resourceIri")
}
/**
* Returns an instance of [[ResourceFullResponseV1]] representing a Knora resource
* with its properties and their values, in Knora API v1 format.
*
* @param resourceIri the IRI of the resource to be queried.
* @param userProfile the profile of the user making the request.
* @param getIncoming if `true` (the default), queries the resource's inconing references.
* @return a [[ResourceFullResponseV1]].
*/
private def getFullResponseV1(
resourceIri: IRI,
userProfile: UserADM,
getIncoming: Boolean = true
): Future[ResourceFullResponseV1] = {
val userProfileV1 = userProfile.asUserProfileV1
// Query resource info, resource properties, and incoming references in parallel.
// See http://buransky.com/scala/scala-for-comprehension-with-concurrently-running-futures/
// Get information about the properties that have values for this resource.
val groupedPropsByTypeFuture: Future[GroupedPropertiesByType] = getGroupedProperties(resourceIri)
// Get a resource info containing basic information about the resource. Do not query the ontology here, because we will query it below.
val resourceInfoFuture = getResourceInfoV1(
resourceIri = resourceIri,
userProfile = userProfile,
queryOntology = false
)
// Get information about the references pointing from other resources to this resource.
val maybeIncomingRefsFuture: Future[Option[SparqlSelectResult]] = if (getIncoming) {
for {
incomingRefsSparql <- Future(
org.knora.webapi.messages.twirl.queries.sparql.v1.txt
.getIncomingReferences(
resourceIri = resourceIri
)
.toString()
)
response <- appActor.ask(SparqlSelectRequest(incomingRefsSparql)).mapTo[SparqlSelectResult]
} yield Some(response)
} else {
Future(None)
}
for {
// Get the resource info (minus ontology-based information) and the user's permissions on it.
(permissions, resInfoWithoutQueryingOntology: ResourceInfoV1) <- resourceInfoFuture
groupedPropsByType: GroupedPropertiesByType <- groupedPropsByTypeFuture
// Get the types of all the resources that this resource links to.
linkedResourceTypes = groupedPropsByType.groupedLinkProperties.groupedProperties.foldLeft(Set.empty[IRI]) {
case (acc, (_, propMap)) =>
val targetResourceTypes = propMap.valueObjects.foldLeft(Set.empty[IRI]) {
case (resTypeAcc, (obj: IRI, objMap: ValueProps)) =>
val resType = objMap.literalData.get(OntologyConstants.Rdf.Type) match {
case Some(value: ValueLiterals) => value.literals
case None => throw InconsistentRepositoryDataException(s"$obj has no rdf:type")
}
resTypeAcc ++ resType
}
acc ++ targetResourceTypes
}
// Group incoming reference rows by the IRI of the referring resource, and construct an IncomingV1 for each one.
maybeIncomingRefsResponse: Option[SparqlSelectResult] <- maybeIncomingRefsFuture
incomingRefFutures: Vector[Future[Vector[IncomingV1]]] =
maybeIncomingRefsResponse match {
case Some(incomingRefsResponse) =>
val incomingRefsResponseRows =
incomingRefsResponse.results.bindings
// Group the incoming reference query results by the IRI of the referring resource.
val groupedByIncomingIri: Map[IRI, Seq[VariableResultsRow]] =
incomingRefsResponseRows.groupBy(
_.rowMap("referringResource")
)
groupedByIncomingIri.map {
case (
incomingIri: IRI,
rows: Seq[VariableResultsRow]
) =>
// Make a resource info for each referring resource, and check the permissions on the referring resource.
val rowsForResInfo = rows.filterNot(row =>
stringFormatter.optionStringToBoolean(
row.rowMap.get("isLinkValue"),
throw InconsistentRepositoryDataException(
s"Invalid boolean for isLinkValue: ${row.rowMap
.get("isLinkValue")}"
)
)
)
for {
(incomingResPermission, incomingResInfo) <-
makeResourceInfoV1(
resourceIri = incomingIri,
resInfoResponseRows = rowsForResInfo,
userProfile = userProfile,
queryOntology = false
)
// Does the user have permission to see the referring resource?
incomingV1s: Vector[IncomingV1] <-
incomingResPermission match {
case Some(_) =>
// Yes. For each link from the referring resource, check whether the user has permission to see the link. If so, make an IncomingV1 for the link.
// Filter to get only the rows representing LinkValues.
val rowsWithLinkValues = rows.filter(row =>
stringFormatter.optionStringToBoolean(
row.rowMap.get("isLinkValue"),
throw InconsistentRepositoryDataException(
s"Invalid boolean for isLinkValue: ${row.rowMap
.get("isLinkValue")}"
)
)
)
// Group them by LinkValue IRI.
val groupedByLinkValue: Map[String, Seq[
VariableResultsRow
]] =
rowsWithLinkValues.groupBy(
_.rowMap("obj")
)
// For each LinkValue, check whether the user has permission to see the link, and if so, make an IncomingV1.
val maybeIncomingV1sWithFuture: Iterable[
Future[Option[IncomingV1]]
] = groupedByLinkValue.map {
case (
linkValueIri: IRI,
linkValueRows: Seq[
VariableResultsRow
]
) =>
// Convert the rows representing the LinkValue to a ValueProps.
val linkValueProps =
valueUtilV1.createValueProps(
valueIri = linkValueIri,
objRows = linkValueRows
)
// Convert the resulting ValueProps into a LinkValueV1 so we can check its rdf:predicate.
for {
apiValueV1 <-
valueUtilV1.makeValueV1(
valueProps = linkValueProps,
projectShortcode = resInfoWithoutQueryingOntology.project_shortcode,
appActor = appActor,
userProfile = userProfile
)
linkValueV1: LinkValueV1 =
apiValueV1 match {
case linkValueV1: LinkValueV1 =>
linkValueV1
case _ =>
throw InconsistentRepositoryDataException(
s"Expected $linkValueIri to be a knora-base:LinkValue, but its type is ${apiValueV1.valueTypeIri}"
)
}
// Check the permissions on the LinkValue.
linkValuePermission =
PermissionUtilADM
.getUserPermissionWithValuePropsV1(
valueIri = linkValueIri,
valueProps = linkValueProps,
entityProject = Some(
incomingResInfo.project_id
),
userProfile = userProfileV1
)
} yield linkValuePermission match {
// Does the user have permission to see this link?
case Some(_) =>
// Yes. Make a Some containing an IncomingV1 for the link.
Some(
IncomingV1(
ext_res_id = ExternalResourceIDV1(
id = incomingIri,
pid = linkValueV1.predicateIri
),
resinfo = incomingResInfo,
value = incomingResInfo.firstproperty
)
)
case None =>
// No. Make a None.
None
}
}
for {
// turn the Iterable of Futures into a Future of an Iterable
maybeIncomingV1s: Iterable[
Option[IncomingV1]
] <- Future.sequence(
maybeIncomingV1sWithFuture
)
// Filter out the Nones, which represent incoming links that the user doesn't have permission to see.
} yield maybeIncomingV1s.flatten.toVector
case None =>
// The user doesn't have permission to see the referring resource.
Future(Vector.empty[IncomingV1])
}
} yield incomingV1s
}.toVector
case None => Vector.empty[Future[Vector[IncomingV1]]]
}
incomingRefsWithoutQueryingOntology <- Future.sequence(incomingRefFutures).map(_.flatten)
// Get the resource types of the incoming resources.
incomingTypes: Set[IRI] = incomingRefsWithoutQueryingOntology.map(_.resinfo.restype_id).toSet
// Ask the ontology responder for information about the ontology entities that we need information about.
entityInfoResponse: EntityInfoGetResponseV1 <- appActor
.ask(
EntityInfoGetRequestV1(
resourceClassIris =
incomingTypes ++ linkedResourceTypes + resInfoWithoutQueryingOntology.restype_id,
propertyIris =
groupedPropsByType.groupedOrdinaryValueProperties.groupedProperties.keySet ++ groupedPropsByType.groupedLinkProperties.groupedProperties.keySet,
userProfile = userProfile
)
)
.mapTo[EntityInfoGetResponseV1]
// Add ontology-based information to the resource info.
resourceTypeIri = resInfoWithoutQueryingOntology.restype_id
resourceTypeEntityInfo = entityInfoResponse.resourceClassInfoMap(resourceTypeIri)
maybeResourceTypeIconSrc = resourceTypeEntityInfo.getPredicateObject(
OntologyConstants.KnoraBase.ResourceIcon
) match {
case Some(resClassIcon) =>
Some(valueUtilV1.makeResourceClassIconURL(resourceTypeIri, resClassIcon))
case _ => None
}
resourceClassLabel = resourceTypeEntityInfo.getPredicateObject(
predicateIri = OntologyConstants.Rdfs.Label,
preferredLangs = Some(userProfile.lang, responderData.appConfig.fallbackLanguage)
)
resInfo: ResourceInfoV1 = resInfoWithoutQueryingOntology.copy(
restype_label = resourceClassLabel,
restype_description = resourceTypeEntityInfo.getPredicateObject(
predicateIri = OntologyConstants.Rdfs.Comment,
preferredLangs = Some(userProfile.lang, responderData.appConfig.fallbackLanguage)
),
restype_iconsrc = maybeResourceTypeIconSrc
)
// Construct a ResourceDataV1.
resData = ResourceDataV1(
rights = permissions,
restype_label = resourceClassLabel,
restype_name = resInfo.restype_id,
res_id = resourceIri,
iconsrc = maybeResourceTypeIconSrc
)
// Add ontology-based information to incoming references.
incomingRefs = incomingRefsWithoutQueryingOntology.map { incoming =>
val incomingResourceTypeEntityInfo =
entityInfoResponse.resourceClassInfoMap(incoming.resinfo.restype_id)
incoming.copy(
resinfo = incoming.resinfo.copy(
restype_label = incomingResourceTypeEntityInfo.getPredicateObject(
predicateIri = OntologyConstants.Rdfs.Label,
preferredLangs = Some(userProfile.lang, responderData.appConfig.fallbackLanguage)
),
restype_description = incomingResourceTypeEntityInfo.getPredicateObject(
predicateIri = OntologyConstants.Rdfs.Comment,
preferredLangs = Some(userProfile.lang, responderData.appConfig.fallbackLanguage)
),
restype_iconsrc = incomingResourceTypeEntityInfo.getPredicateObject(
OntologyConstants.KnoraBase.ResourceIcon
) match {
case Some(resClassIcon) =>
Some(valueUtilV1.makeResourceClassIconURL(incoming.resinfo.restype_id, resClassIcon))
case _ => None
}
)
)
}
// Collect all property IRIs and their cardinalities for the queried resource's type, except the ones that point to LinkValue objects or FileValue objects,
// which are not relevant in this API operation.
propsAndCardinalities: Map[IRI, KnoraCardinalityInfo] =
resourceTypeEntityInfo.knoraResourceCardinalities.filterNot { case (propertyIri, _) =>
resourceTypeEntityInfo.linkValueProperties(propertyIri) || resourceTypeEntityInfo.fileValueProperties(
propertyIri
)
}
// Construct PropertyV1 objects for the properties that have data for this resource.
propertiesWithData <- queryResults2PropertyV1s(
containingResourceIri = resourceIri,
projectShortcode = resInfoWithoutQueryingOntology.project_shortcode,
groupedPropertiesByType = groupedPropsByType,
propertyInfoMap = entityInfoResponse.propertyInfoMap,
resourceEntityInfoMap = entityInfoResponse.resourceClassInfoMap,
propsAndCardinalities = propsAndCardinalities,
userProfile = userProfile
)
// Construct PropertyV1 objects representing properties that have no data for this resource, but are possible properties for the resource type.
// To find out which properties are possible but have no data for this resource, subtract the set of properties with data from the set of possible properties.
emptyPropsIris =
propsAndCardinalities.keySet -- (groupedPropsByType.groupedOrdinaryValueProperties.groupedProperties.keySet ++ groupedPropsByType.groupedLinkProperties.groupedProperties.keySet)
// Get information from the ontology about the properties that have no data for this resource.
emptyPropsInfoResponse: EntityInfoGetResponseV1 <- appActor
.ask(
EntityInfoGetRequestV1(
propertyIris = emptyPropsIris,
userProfile = userProfile
)
)
.mapTo[EntityInfoGetResponseV1]
// Create a PropertyV1 for each of those properties.
emptyProps: Set[PropertyV1] = emptyPropsIris.map { propertyIri =>
val propertyEntityInfo: PropertyInfoV1 =
emptyPropsInfoResponse.propertyInfoMap(propertyIri)
val guiOrder =
resourceTypeEntityInfo.knoraResourceCardinalities(propertyIri).guiOrder
if (propertyEntityInfo.isLinkProp) {
// It is a linking prop: its valuetype_id is knora-base:LinkValue.
// It is restricted to the resource class that is given for knora-base:objectClassConstraint
// for the given property which goes in the attributes that will be read by the GUI.
PropertyV1(
pid = propertyIri,
valuetype_id = Some(OntologyConstants.KnoraBase.LinkValue),
guiorder = guiOrder,
guielement = propertyEntityInfo
.getPredicateObject(SalsahGui.GuiElementProp)
.map(guiElementIri =>
SalsahGuiConversions.iri2SalsahGuiElement(guiElementIri)
),
label = propertyEntityInfo.getPredicateObject(
predicateIri = OntologyConstants.Rdfs.Label,
preferredLangs =
Some(userProfile.lang, responderData.appConfig.fallbackLanguage)
),
occurrence = Some(propsAndCardinalities(propertyIri).cardinality.value),
attributes = (propertyEntityInfo.getPredicateStringObjectsWithoutLang(
SalsahGui.GuiAttribute
) + valueUtilV1.makeAttributeRestype(
propertyEntityInfo
.getPredicateObject(OntologyConstants.KnoraBase.ObjectClassConstraint)
.getOrElse(
throw InconsistentRepositoryDataException(
s"Property $propertyIri has no knora-base:objectClassConstraint"
)
)
)).mkString(";"),
value_rights = Nil
)
} else {
PropertyV1(
pid = propertyIri,
valuetype_id = propertyEntityInfo.getPredicateObject(
OntologyConstants.KnoraBase.ObjectClassConstraint
),
guiorder = guiOrder,
guielement = propertyEntityInfo
.getPredicateObject(SalsahGui.GuiElementProp)
.map(guiElementIri =>
SalsahGuiConversions.iri2SalsahGuiElement(guiElementIri)
),
label = propertyEntityInfo.getPredicateObject(
predicateIri = OntologyConstants.Rdfs.Label,
preferredLangs =
Some(userProfile.lang, responderData.appConfig.fallbackLanguage)
),
occurrence = Some(propsAndCardinalities(propertyIri).cardinality.value),
attributes = propertyEntityInfo
.getPredicateStringObjectsWithoutLang(
SalsahGui.GuiAttribute
)
.mkString(";"),
value_rights = Nil
)
}
}
// Add a fake property `__location__` if the resource has FileValues.
properties: Seq[PropertyV1] =
if (resInfo.locations.nonEmpty) {
PropertyV1(
pid = "__location__",
valuetype_id = Some("-1"),
guiorder = Some(Int.MaxValue),
guielement = Some(SalsahGuiConversions.iri2SalsahGuiElement(SalsahGui.Fileupload)),
values = Vector(IntegerValueV1(0)),
value_ids = Vector("0"),
comments = Vector(None),
locations = resInfo.locations match {
case Some(locations: Seq[LocationV1]) => locations
case None => Nil
},
value_rights = Nil
) +: (propertiesWithData ++ emptyProps)
} else {
propertiesWithData ++ emptyProps
}
// Construct the API response. Return no data if the user has no view permissions on the queried resource.
resFullResponse =
if (resData.rights.nonEmpty) {
ResourceFullResponseV1(
resinfo = Some(resInfo),
resdata = Some(resData),
props = Some(PropsV1(properties)),
incoming = incomingRefs,
access = "OK"
)
} else {
throw ForbiddenException(s"User ${userProfile.id} does not have permission to query resource $resourceIri")
}
} yield resFullResponse
}
/**
* Returns an instance of [[ResourceContextResponseV1]] describing the context of a resource, in Knora API v1 format.
*
* @param resourceIri the IRI of the resource to be queried.
*
* @param userProfile the profile of the user making the request.
* @param resinfo a flag if resinfo should be retrieved or not.
* @return a [[ResourceContextResponseV1]] describing the context of the resource.
*/
private def getContextResponseV1(
resourceIri: IRI,
userProfile: UserADM,
resinfo: Boolean
): Future[ResourceContextResponseV1] = {
val userProfileV1 = userProfile.asUserProfileV1
/**
* Represents a source object (e.g. a page of a book).
*
* @param id IRI of the source Object.
* @param firstprop first property of the source object.
* @param seqnum sequence number of the source object.
* @param permissionCode the current user's permissions on the source object.
* @param fileValue the file value, if any, belonging to the source object.
*/
case class SourceObject(
id: IRI,
firstprop: Option[String],
seqnum: Option[Int],
permissionCode: Option[Int],
projectShortcode: String,
fileValue: Option[StillImageFileValue]
)
/**
* Represents a still image file value belonging to a source object (e.g., an image representation of a page).
*
* @param id the file value IRI
* @param permissionCode the current user's permission code on the file value.
* @param image a [[StillImageFileValueV1]]