/
ProjectsResponderADM.scala
1400 lines (1230 loc) · 59.8 KB
/
ProjectsResponderADM.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.admin
import akka.http.scaladsl.util.FastFuture
import akka.pattern._
import java.io.BufferedInputStream
import java.io.BufferedOutputStream
import java.nio.file.Files
import java.nio.file.Path
import java.util.UUID
import scala.concurrent.Future
import scala.util.Failure
import scala.util.Success
import scala.util.Try
import dsp.errors._
import org.knora.webapi._
import org.knora.webapi.instrumentation.InstrumentationSupport
import org.knora.webapi.messages.IriConversions._
import org.knora.webapi.messages.OntologyConstants
import org.knora.webapi.messages.SmartIri
import org.knora.webapi.messages.admin.responder.permissionsmessages._
import org.knora.webapi.messages.admin.responder.projectsmessages._
import org.knora.webapi.messages.admin.responder.usersmessages.UserADM
import org.knora.webapi.messages.admin.responder.usersmessages.UserGetADM
import org.knora.webapi.messages.admin.responder.usersmessages.UserIdentifierADM
import org.knora.webapi.messages.admin.responder.usersmessages.UserInformationTypeADM
import org.knora.webapi.messages.store.cacheservicemessages.CacheServiceFlushDB
import org.knora.webapi.messages.store.cacheservicemessages.CacheServiceGetProjectADM
import org.knora.webapi.messages.store.cacheservicemessages.CacheServicePutProjectADM
import org.knora.webapi.messages.store.triplestoremessages._
import org.knora.webapi.messages.util.KnoraSystemInstances
import org.knora.webapi.messages.util.ResponderData
import org.knora.webapi.messages.util.rdf._
import org.knora.webapi.messages.v2.responder.ontologymessages.OntologyMetadataGetByProjectRequestV2
import org.knora.webapi.messages.v2.responder.ontologymessages.ReadOntologyMetadataV2
import org.knora.webapi.responders.IriLocker
import org.knora.webapi.responders.Responder
import org.knora.webapi.responders.Responder.handleUnexpectedMessage
/**
* Returns information about Knora projects.
*/
class ProjectsResponderADM(responderData: ResponderData) extends Responder(responderData) with InstrumentationSupport {
// Global lock IRI used for project creation and update
private val PROJECTS_GLOBAL_LOCK_IRI = "http://rdfh.ch/projects"
private val ADMIN_DATA_GRAPH = "http://www.knora.org/data/admin"
private val PERMISSIONS_DATA_GRAPH = "http://www.knora.org/data/permissions"
/**
* Receives a message extending [[ProjectsResponderRequestV1]], and returns an appropriate response message.
*/
def receive(msg: ProjectsResponderRequestADM) = msg match {
case ProjectsGetADM(requestingUser) => projectsGetADM(requestingUser)
case ProjectsGetRequestADM(requestingUser) =>
projectsGetRequestADM(requestingUser)
case ProjectGetADM(identifier, requestingUser) =>
getSingleProjectADM(identifier, requestingUser)
case ProjectGetRequestADM(identifier, requestingUser) =>
getSingleProjectADMRequest(identifier, requestingUser)
case ProjectMembersGetRequestADM(identifier, requestingUser) =>
projectMembersGetRequestADM(identifier, requestingUser)
case ProjectAdminMembersGetRequestADM(identifier, requestingUser) =>
projectAdminMembersGetRequestADM(identifier, requestingUser)
case ProjectsKeywordsGetRequestADM(requestingUser) =>
projectsKeywordsGetRequestADM(requestingUser)
case ProjectKeywordsGetRequestADM(projectIri, requestingUser) =>
projectKeywordsGetRequestADM(projectIri, requestingUser)
case ProjectRestrictedViewSettingsGetADM(identifier, requestingUser) =>
projectRestrictedViewSettingsGetADM(identifier, requestingUser)
case ProjectRestrictedViewSettingsGetRequestADM(identifier, requestingUser) =>
projectRestrictedViewSettingsGetRequestADM(identifier, requestingUser)
case ProjectCreateRequestADM(createRequest, requestingUser, apiRequestID) =>
projectCreateRequestADM(createRequest, requestingUser, apiRequestID)
case ProjectChangeRequestADM(
projectIri,
changeProjectRequest,
requestingUser,
apiRequestID
) =>
changeBasicInformationRequestADM(
projectIri,
changeProjectRequest,
requestingUser,
apiRequestID
)
case ProjectDataGetRequestADM(projectIdentifier, requestingUser) =>
projectDataGetRequestADM(projectIdentifier, requestingUser)
case other => handleUnexpectedMessage(other, log, this.getClass.getName)
}
/**
* Gets all the projects and returns them as a sequence containing [[ProjectADM]].
*
* @param requestingUser the user making the request.
* @return all the projects as a sequence containing [[ProjectADM]].
*/
private def projectsGetADM(
requestingUser: UserADM
): Future[Seq[ProjectADM]] =
for {
sparqlQueryString <- Future(
org.knora.webapi.messages.twirl.queries.sparql.admin.txt
.getProjects(
maybeIri = None,
maybeShortname = None,
maybeShortcode = None
)
.toString()
)
// _ = log.debug(s"getProjectsResponseV1 - query: $sparqlQueryString")
projectsResponse <- appActor
.ask(
SparqlExtendedConstructRequest(
sparql = sparqlQueryString
)
)
.mapTo[SparqlExtendedConstructResponse]
// _ = log.debug(s"projectsGetADM - projectsResponse: $projectsResponse")
statements: List[(SubjectV2, Map[SmartIri, Seq[LiteralV2]])] = projectsResponse.statements.toList
// _ = log.debug(s"projectsGetADM - statements: $statements")
projectIris = statements.map { case (projectIri: SubjectV2, _) =>
projectIri.toString
}.toSet
ontologiesForProjects: Map[IRI, Seq[IRI]] <- getOntologiesForProjects(projectIris, requestingUser)
projects: Seq[ProjectADM] = statements.map {
case (projectIriSubject: SubjectV2, propsMap: Map[SmartIri, Seq[LiteralV2]]) =>
val projectOntologies =
ontologiesForProjects.getOrElse(projectIriSubject.toString, Seq.empty[IRI])
statements2ProjectADM(
statements = (projectIriSubject, propsMap),
ontologies = projectOntologies
)
}
} yield projects.sorted
/**
* Given a set of project IRIs, gets the ontologies that belong to each project.
*
* @param projectIris a set of project IRIs. If empty, returns the ontologies for all projects.
* @param requestingUser the requesting user.
* @return a map of project IRIs to sequences of ontology IRIs.
*/
private def getOntologiesForProjects(projectIris: Set[IRI], requestingUser: UserADM): Future[Map[IRI, Seq[IRI]]] =
for {
ontologyMetadataResponse: ReadOntologyMetadataV2 <- appActor
.ask(
OntologyMetadataGetByProjectRequestV2(
projectIris = projectIris.map(_.toSmartIri),
requestingUser = requestingUser
)
)
.mapTo[ReadOntologyMetadataV2]
} yield ontologyMetadataResponse.ontologies.map { ontology =>
val ontologyIri: IRI = ontology.ontologyIri.toString
val projectIri: IRI = ontology.projectIri
.getOrElse(throw InconsistentRepositoryDataException(s"Ontology $ontologyIri has no project"))
.toString
projectIri -> ontologyIri
}
.groupBy(_._1)
.map { case (projectIri, projectIriAndOntologies: Set[(IRI, IRI)]) =>
projectIri -> projectIriAndOntologies.map(_._2).toSeq
}
/**
* Gets all the projects and returns them as a [[ProjectsResponseV1]].
*
* @param requestingUser the user that is making the request.
* @return all the projects as a [[ProjectsResponseV1]].
* @throws NotFoundException if no projects are found.
*/
private def projectsGetRequestADM(
requestingUser: UserADM
): Future[ProjectsGetResponseADM] =
// log.debug("projectsGetRequestADM")
// ToDo: What permissions should be required, if any?
for {
projects <- projectsGetADM(
requestingUser = requestingUser
)
result =
if (projects.nonEmpty) {
ProjectsGetResponseADM(
projects = projects
)
} else {
throw NotFoundException(s"No projects found")
}
} yield result
/**
* Gets the project with the given project IRI, shortname, or shortcode and returns the information as a [[ProjectADM]].
*
* @param identifier the IRI, shortname, or shortcode of the project.
* @param requestingUser the user making the request.
* @return information about the project as a [[ProjectInfoV1]].
*/
private def getSingleProjectADM(
identifier: ProjectIdentifierADM,
requestingUser: UserADM,
skipCache: Boolean = false
): Future[Option[ProjectADM]] =
tracedFuture("admin-get-project") {
// log.debug("getSingleProjectADM - projectIRI: {}", projectIri)
log.debug(
s"getSingleProjectADM - id: {}, requester: {}, skipCache: {}",
identifier.value,
requestingUser.username,
skipCache
)
for {
maybeProjectADM <-
if (skipCache) {
// getting directly from triplestore
getProjectFromTriplestore(identifier = identifier)
} else {
// getting from cache or triplestore
getProjectFromCacheOrTriplestore(identifier = identifier)
}
_ =
if (maybeProjectADM.nonEmpty) {
log.debug("getSingleProjectADM - successfully retrieved project: {}", identifier.value)
} else {
log.debug("getSingleProjectADM - could not retrieve project: {}", identifier.value)
}
_ = appActor.ask(CacheServiceFlushDB(KnoraSystemInstances.Users.SystemUser))
} yield maybeProjectADM
}
/**
* Gets the project with the given project IRI, shortname, or shortcode and returns the information
* as a [[ProjectGetResponseADM]].
*
* @param identifier the IRI, shortname, or shortcode of the project.
*
* @param requestingUser the user making the request.
* @return information about the project as a [[ProjectInfoResponseV1]].
* @throws NotFoundException when no project for the given IRI can be found
*/
private def getSingleProjectADMRequest(
identifier: ProjectIdentifierADM,
requestingUser: UserADM
): Future[ProjectGetResponseADM] =
// log.debug("getSingleProjectADMRequest - maybeIri: {}, maybeShortname: {}, maybeShortcode: {}", maybeIri, maybeShortname, maybeShortcode)
for {
maybeProject: Option[ProjectADM] <- getSingleProjectADM(
identifier = identifier,
requestingUser = requestingUser
)
project = maybeProject match {
case Some(p) => p
case None => throw NotFoundException(s"Project '${identifier.value}' not found")
}
} yield ProjectGetResponseADM(
project = project
)
/**
* Gets the members of a project with the given IRI, shortname, oder shortcode. Returns an empty list
* if none are found.
*
* @param identifier the IRI, shortname, or shortcode of the project.
* @param requestingUser the user making the request.
* @return the members of a project as a [[ProjectMembersGetResponseADM]]
*/
private def projectMembersGetRequestADM(
identifier: ProjectIdentifierADM,
requestingUser: UserADM
): Future[ProjectMembersGetResponseADM] =
// log.debug("projectMembersGetRequestADM - maybeIri: {}, maybeShortname: {}, maybeShortcode: {}", maybeIri, maybeShortname, maybeShortcode)
for {
/* Get project and verify permissions. */
project <- getSingleProjectADM(
identifier = identifier,
requestingUser = KnoraSystemInstances.Users.SystemUser
)
_ =
if (project.isEmpty) {
throw NotFoundException(s"Project '${identifier.value}' not found.")
} else {
if (
!requestingUser.permissions.isSystemAdmin && !requestingUser.permissions.isProjectAdmin(
project.get.id
) && !requestingUser.isSystemUser
) {
throw ForbiddenException("SystemAdmin or ProjectAdmin permissions are required.")
}
}
sparqlQueryString <- Future(
org.knora.webapi.messages.twirl.queries.sparql.admin.txt
.getProjectMembers(
maybeIri = identifier.toIriOption,
maybeShortname = identifier.toShortnameOption,
maybeShortcode = identifier.toShortcodeOption
)
.toString()
)
// _ = log.debug(s"projectMembersGetRequestADM - query: $sparqlQueryString")
projectMembersResponse <- appActor
.ask(
SparqlExtendedConstructRequest(
sparql = sparqlQueryString
)
)
.mapTo[SparqlExtendedConstructResponse]
statements = projectMembersResponse.statements.toList
// _ = log.debug(s"projectMembersGetRequestADM - statements: {}", MessageUtil.toSource(statements))
// get project member IRI from results rows
userIris: Seq[IRI] =
if (statements.nonEmpty) {
statements.map(_._1.toString)
} else {
Seq.empty[IRI]
}
maybeUserFutures: Seq[Future[Option[UserADM]]] =
userIris.map { userIri =>
appActor
.ask(
UserGetADM(
identifier = UserIdentifierADM(maybeIri = Some(userIri)),
userInformationTypeADM = UserInformationTypeADM.Restricted,
requestingUser = KnoraSystemInstances.Users.SystemUser
)
)
.mapTo[Option[UserADM]]
}
maybeUsers: Seq[Option[UserADM]] <- Future.sequence(maybeUserFutures)
users: Seq[UserADM] = maybeUsers.flatten
// _ = log.debug(s"projectMembersGetRequestADM - users: {}", users)
} yield ProjectMembersGetResponseADM(members = users)
/**
* Gets the admin members of a project with the given IRI, shortname, or shortcode. Returns an empty list
* if none are found
*
* @param identifier the IRI, shortname, or shortcode of the project.
* @param requestingUser the user making the request.
* @return the members of a project as a [[ProjectMembersGetResponseADM]]
*/
private def projectAdminMembersGetRequestADM(
identifier: ProjectIdentifierADM,
requestingUser: UserADM
): Future[ProjectAdminMembersGetResponseADM] =
// log.debug("projectAdminMembersGetRequestADM - maybeIri: {}, maybeShortname: {}, maybeShortcode: {}", maybeIri, maybeShortname, maybeShortcode)
for {
/* Get project and verify permissions. */
project <- getSingleProjectADM(
identifier = identifier,
requestingUser = KnoraSystemInstances.Users.SystemUser
)
_ =
if (project.isEmpty) {
throw NotFoundException(s"Project '${identifier.value}' not found.")
} else {
if (!requestingUser.permissions.isSystemAdmin && !requestingUser.permissions.isProjectAdmin(project.get.id)) {
throw ForbiddenException("SystemAdmin or ProjectAdmin permissions are required.")
}
}
sparqlQueryString <- Future(
org.knora.webapi.messages.twirl.queries.sparql.admin.txt
.getProjectAdminMembers(
maybeIri = identifier.toIriOption,
maybeShortname = identifier.toShortnameOption,
maybeShortcode = identifier.toShortcodeOption
)
.toString()
)
// _ = log.debug(s"projectAdminMembersByIRIGetRequestV1 - query: $sparqlQueryString")
projectAdminMembersResponse <- appActor
.ask(
SparqlExtendedConstructRequest(
sparql = sparqlQueryString
)
)
.mapTo[SparqlExtendedConstructResponse]
// _ = log.debug(s"projectAdminMembersByIRIGetRequestV1 - result: ${MessageUtil.toSource(projectMembersResponse)}")
statements = projectAdminMembersResponse.statements.toList
// get project member IRI from results rows
userIris: Seq[IRI] =
if (statements.nonEmpty) {
statements.map(_._1.toString)
} else {
Seq.empty[IRI]
}
maybeUserFutures: Seq[Future[Option[UserADM]]] = userIris.map { userIri =>
appActor
.ask(
UserGetADM(
identifier = UserIdentifierADM(maybeIri = Some(userIri)),
userInformationTypeADM =
UserInformationTypeADM.Restricted,
requestingUser = KnoraSystemInstances.Users.SystemUser
)
)
.mapTo[Option[UserADM]]
}
maybeUsers: Seq[Option[UserADM]] <- Future.sequence(maybeUserFutures)
users: Seq[UserADM] = maybeUsers.flatten
// _ = log.debug(s"projectMembersGetRequestADM - users: $users")
} yield ProjectAdminMembersGetResponseADM(members = users)
/**
* Gets all unique keywords for all projects and returns them. Returns an empty list if none are found.
*
* @param requestingUser the user making the request.
* @return all keywords for all projects as [[ProjectsKeywordsGetResponseADM]]
*/
private def projectsKeywordsGetRequestADM(
requestingUser: UserADM
): Future[ProjectsKeywordsGetResponseADM] =
for {
projects <- projectsGetADM(
requestingUser = KnoraSystemInstances.Users.SystemUser
)
keywords: Seq[String] = projects.flatMap(_.keywords).distinct.sorted
} yield ProjectsKeywordsGetResponseADM(keywords = keywords)
/**
* Gets all keywords for a single project and returns them. Returns an empty list if none are found.
*
* @param projectIri the IRI of the project.
* @param requestingUser the user making the request.
* @return keywords for a projects as [[ProjectKeywordsGetResponseADM]]
*/
private def projectKeywordsGetRequestADM(
projectIri: IRI,
requestingUser: UserADM
): Future[ProjectKeywordsGetResponseADM] =
for {
maybeProject <- getSingleProjectADM(
identifier = ProjectIdentifierADM(maybeIri = Some(projectIri)),
requestingUser = KnoraSystemInstances.Users.SystemUser
)
keywords: Seq[String] = maybeProject match {
case Some(p) => p.keywords
case None => throw NotFoundException(s"Project '$projectIri' not found.")
}
} yield ProjectKeywordsGetResponseADM(keywords = keywords)
private def projectDataGetRequestADM(
projectIdentifier: ProjectIdentifierADM,
requestingUser: UserADM
): Future[ProjectDataGetResponseADM] = {
/**
* Represents a named graph to be saved to a TriG file.
*
* @param graphIri the IRI of the named graph.
* @param tempDir the directory in which the file is to be saved.
*/
case class NamedGraphTrigFile(graphIri: IRI, tempDir: Path) {
lazy val dataFile: Path = {
val filename = graphIri.replaceAll(":", "_").replaceAll("/", "_").replaceAll("""\.""", "_") +
".trig"
tempDir.resolve(filename)
}
}
/**
* An [[RdfStreamProcessor]] for combining several named graphs into one.
*
* @param formattingStreamProcessor an [[RdfStreamProcessor]] for writing the combined result.
*/
class CombiningRdfProcessor(formattingStreamProcessor: RdfStreamProcessor) extends RdfStreamProcessor {
private var startedStatements = false
// Ignore this, since it will be done before the first file is written.
override def start(): Unit = {}
// Ignore this, since it will be done after the last file is written.
override def finish(): Unit = {}
override def processNamespace(prefix: IRI, namespace: IRI): Unit =
// Only accept namespaces from the first graph, to prevent conflicts.
if (!startedStatements) {
formattingStreamProcessor.processNamespace(prefix, namespace)
}
override def processStatement(statement: Statement): Unit = {
startedStatements = true
formattingStreamProcessor.processStatement(statement)
}
}
/**
* Combines several TriG files into one.
*
* @param namedGraphTrigFiles the TriG files to combine.
* @param resultFile the output file.
*/
def combineGraphs(namedGraphTrigFiles: Seq[NamedGraphTrigFile], resultFile: Path): Unit = {
val rdfFormatUtil: RdfFormatUtil = RdfFeatureFactory.getRdfFormatUtil()
var maybeBufferedFileOutputStream: Option[BufferedOutputStream] = None
val trigFileTry: Try[Unit] = Try {
maybeBufferedFileOutputStream = Some(new BufferedOutputStream(Files.newOutputStream(resultFile)))
val formattingStreamProcessor: RdfStreamProcessor = rdfFormatUtil.makeFormattingStreamProcessor(
outputStream = maybeBufferedFileOutputStream.get,
rdfFormat = TriG
)
val combiningRdfProcessor = new CombiningRdfProcessor(formattingStreamProcessor)
formattingStreamProcessor.start()
for (namedGraphTrigFile: NamedGraphTrigFile <- namedGraphTrigFiles) {
val namedGraphTry: Try[Unit] = Try {
rdfFormatUtil.parseWithStreamProcessor(
rdfSource =
RdfInputStreamSource(new BufferedInputStream(Files.newInputStream(namedGraphTrigFile.dataFile))),
rdfFormat = TriG,
rdfStreamProcessor = combiningRdfProcessor
)
}
Files.delete(namedGraphTrigFile.dataFile)
namedGraphTry match {
case Success(_) => ()
case Failure(ex) => throw ex
}
}
formattingStreamProcessor.finish()
}
maybeBufferedFileOutputStream.foreach(_.close)
trigFileTry match {
case Success(_) => ()
case Failure(ex) => throw ex
}
}
for {
// Get the project info.
maybeProject: Option[ProjectADM] <- getSingleProjectADM(
identifier = projectIdentifier,
requestingUser = requestingUser
)
project: ProjectADM = maybeProject.getOrElse(
throw NotFoundException(s"Project '${projectIdentifier.value}' not found.")
)
// Check that the user has permission to download the data.
_ = if (!(requestingUser.permissions.isSystemAdmin || requestingUser.permissions.isProjectAdmin(project.id))) {
throw ForbiddenException(
s"You are logged in as ${requestingUser.username}, but only a system administrator or project administrator can request a project's data"
)
}
// Make a temporary directory for the downloaded data.
tempDir = Files.createTempDirectory(project.shortname)
_ = log.info("Downloading project data to temporary directory " + tempDir.toAbsolutePath)
// Download the project's named graphs.
projectDataNamedGraph: IRI = stringFormatter.projectDataNamedGraphV2(project)
graphsToDownload: Seq[IRI] = project.ontologies :+ projectDataNamedGraph
projectSpecificNamedGraphTrigFiles: Seq[NamedGraphTrigFile] =
graphsToDownload.map(graphIri => NamedGraphTrigFile(graphIri = graphIri, tempDir = tempDir))
projectSpecificNamedGraphTrigFileWriteFutures: Seq[Future[FileWrittenResponse]] =
projectSpecificNamedGraphTrigFiles.map { trigFile =>
for {
fileWrittenResponse: FileWrittenResponse <-
appActor
.ask(
NamedGraphFileRequest(
graphIri = trigFile.graphIri,
outputFile = trigFile.dataFile,
outputFormat = TriG
)
)
.mapTo[FileWrittenResponse]
} yield fileWrittenResponse
}
_: Seq[FileWrittenResponse] <- Future.sequence(projectSpecificNamedGraphTrigFileWriteFutures)
// Download the project's admin data.
adminDataNamedGraphTrigFile = NamedGraphTrigFile(graphIri = ADMIN_DATA_GRAPH, tempDir = tempDir)
adminDataSparql: String = org.knora.webapi.messages.twirl.queries.sparql.admin.txt
.getProjectAdminData(
projectIri = project.id
)
.toString()
_: FileWrittenResponse <- appActor
.ask(
SparqlConstructFileRequest(
sparql = adminDataSparql,
graphIri = adminDataNamedGraphTrigFile.graphIri,
outputFile = adminDataNamedGraphTrigFile.dataFile,
outputFormat = TriG
)
)
.mapTo[FileWrittenResponse]
// Download the project's permission data.
permissionDataNamedGraphTrigFile = NamedGraphTrigFile(graphIri = PERMISSIONS_DATA_GRAPH, tempDir = tempDir)
permissionDataSparql: String = org.knora.webapi.messages.twirl.queries.sparql.admin.txt
.getProjectPermissions(
projectIri = project.id
)
.toString()
_: FileWrittenResponse <- appActor
.ask(
SparqlConstructFileRequest(
sparql = permissionDataSparql,
graphIri = permissionDataNamedGraphTrigFile.graphIri,
outputFile = permissionDataNamedGraphTrigFile.dataFile,
outputFormat = TriG
)
)
.mapTo[FileWrittenResponse]
// Stream the combined results into the output file.
namedGraphTrigFiles: Seq[NamedGraphTrigFile] =
projectSpecificNamedGraphTrigFiles :+ adminDataNamedGraphTrigFile :+ permissionDataNamedGraphTrigFile
resultFile: Path = tempDir.resolve(project.shortname + ".trig")
_ = combineGraphs(namedGraphTrigFiles = namedGraphTrigFiles, resultFile = resultFile)
} yield ProjectDataGetResponseADM(resultFile)
}
/**
* Get project's restricted view settings.
*
* @param identifier the project's identifier (IRI / shortcode / shortname)
*
* @param requestingUser the user making the request.
* @return [[ProjectRestrictedViewSettingsADM]]
*/
private def projectRestrictedViewSettingsGetADM(
identifier: ProjectIdentifierADM,
requestingUser: UserADM
): Future[Option[ProjectRestrictedViewSettingsADM]] =
// ToDo: We have two possible NotFound scenarios: 1. Project, 2. ProjectRestrictedViewSettings resource. How to send the client the correct NotFound reply?
for {
sparqlQuery <- Future(
org.knora.webapi.messages.twirl.queries.sparql.admin.txt
.getProjects(
maybeIri = identifier.toIriOption,
maybeShortname = identifier.toShortnameOption,
maybeShortcode = identifier.toShortcodeOption
)
.toString()
)
projectResponse <- appActor
.ask(
SparqlExtendedConstructRequest(
sparql = sparqlQuery
)
)
.mapTo[SparqlExtendedConstructResponse]
restrictedViewSettings =
if (projectResponse.statements.nonEmpty) {
val (_, propsMap): (SubjectV2, Map[SmartIri, Seq[LiteralV2]]) = projectResponse.statements.head
val size = propsMap
.get(OntologyConstants.KnoraAdmin.ProjectRestrictedViewSize.toSmartIri)
.map(_.head.asInstanceOf[StringLiteralV2].value)
val watermark = propsMap
.get(OntologyConstants.KnoraAdmin.ProjectRestrictedViewWatermark.toSmartIri)
.map(_.head.asInstanceOf[StringLiteralV2].value)
Some(ProjectRestrictedViewSettingsADM(size, watermark))
} else {
None
}
} yield restrictedViewSettings
/**
* Get project's restricted view settings.
*
* @param identifier the project's identifier (IRI / shortcode / shortname)
*
* @param requestingUser the user making the request.
* @return [[ProjectRestrictedViewSettingsGetResponseADM]]
*/
private def projectRestrictedViewSettingsGetRequestADM(
identifier: ProjectIdentifierADM,
requestingUser: UserADM
): Future[ProjectRestrictedViewSettingsGetResponseADM] = {
val maybeIri = identifier.toIriOption
val maybeShortname = identifier.toShortnameOption
val maybeShortcode = identifier.toShortcodeOption
for {
maybeSettings: Option[ProjectRestrictedViewSettingsADM] <- projectRestrictedViewSettingsGetADM(
identifier = identifier,
requestingUser = requestingUser
)
settings = maybeSettings match {
case Some(s) => s
case None =>
throw NotFoundException(
s"Project '${Seq(maybeIri, maybeShortname, maybeShortcode).flatten.head}' not found."
)
}
} yield ProjectRestrictedViewSettingsGetResponseADM(settings)
}
/**
* Changes project's basic information.
*
* @param projectIri the IRI of the project.
* @param changeProjectRequest the change payload.
*
* @param requestingUser the user making the request.
* @param apiRequestID the unique api request ID.
* @return a [[ProjectOperationResponseADM]].
* @throws ForbiddenException in the case that the user is not allowed to perform the operation.
*/
private def changeBasicInformationRequestADM(
projectIri: IRI,
changeProjectRequest: ChangeProjectApiRequestADM,
requestingUser: UserADM,
apiRequestID: UUID
): Future[ProjectOperationResponseADM] = {
// log.debug(s"changeBasicInformationRequestV1: changeProjectRequest: {}", changeProjectRequest)
/**
* The actual change project task run with an IRI lock.
*/
def changeProjectTask(
projectIri: IRI,
changeProjectRequest: ChangeProjectApiRequestADM,
requestingUser: UserADM
): Future[ProjectOperationResponseADM] =
for {
_ <- Future(
// check if necessary information is present
if (projectIri.isEmpty) throw BadRequestException("Project IRI cannot be empty")
)
// check if the requesting user is allowed to perform updates
_ = if (!requestingUser.permissions.isProjectAdmin(projectIri) && !requestingUser.permissions.isSystemAdmin) {
// not a project admin and not a system admin
throw ForbiddenException("Project's information can only be changed by a project or system admin.")
}
// create the update request
projectUpdatePayload = ProjectUpdatePayloadADM(
longname = changeProjectRequest.longname,
description = changeProjectRequest.description,
keywords = changeProjectRequest.keywords,
logo = changeProjectRequest.logo,
status = changeProjectRequest.status,
selfjoin = changeProjectRequest.selfjoin
)
result <- updateProjectADM(
projectIri = projectIri,
projectUpdatePayload = projectUpdatePayload,
requestingUser = KnoraSystemInstances.Users.SystemUser
)
} yield result
for {
// run the change status task with an IRI lock
taskResult <- IriLocker.runWithIriLock(
apiRequestID,
projectIri,
() => changeProjectTask(projectIri, changeProjectRequest, requestingUser)
)
} yield taskResult
}
/**
* Main project update method.
*
* @param projectIri the IRI of the project.
* @param projectUpdatePayload the data to be updated. Update means exchanging what is in the triplestore with
* this data. If only some parts of the data need to be changed, then this needs to
* be prepared in the step before this one.
*
* @return a [[ProjectOperationResponseADM]].
* @throws NotFoundException in the case that the project's IRI is not found.
*/
private def updateProjectADM(
projectIri: IRI,
projectUpdatePayload: ProjectUpdatePayloadADM,
requestingUser: UserADM
): Future[ProjectOperationResponseADM] = {
// log.debug("updateProjectADM - projectIri: {}, projectUpdatePayload: {}", projectIri, projectUpdatePayload)
val parametersCount = List(
projectUpdatePayload.shortname,
projectUpdatePayload.longname,
projectUpdatePayload.description,
projectUpdatePayload.keywords,
projectUpdatePayload.logo,
projectUpdatePayload.status,
projectUpdatePayload.selfjoin
).flatten.size
if (parametersCount == 0) throw BadRequestException("No data would be changed. Aborting update request.")
for {
maybeCurrentProject: Option[ProjectADM] <- getSingleProjectADM(
identifier = ProjectIdentifierADM(maybeIri = Some(projectIri)),
requestingUser = requestingUser,
skipCache = true
)
_ = if (maybeCurrentProject.isEmpty) {
throw NotFoundException(s"Project '$projectIri' not found. Aborting update request.")
}
// we are changing the project, so lets get rid of the cached copy
_ = appActor.ask(CacheServiceFlushDB(KnoraSystemInstances.Users.SystemUser))
/* Update project */
updateProjectSparqlString <- Future(
org.knora.webapi.messages.twirl.queries.sparql.admin.txt
.updateProject(
adminNamedGraphIri = "http://www.knora.org/data/admin",
projectIri = projectIri,
maybeShortname = projectUpdatePayload.shortname,
maybeLongname = projectUpdatePayload.longname,
maybeDescriptions = projectUpdatePayload.description,
maybeKeywords = projectUpdatePayload.keywords,
maybeLogo = projectUpdatePayload.logo,
maybeStatus = projectUpdatePayload.status,
maybeSelfjoin = projectUpdatePayload.selfjoin
)
.toString
)
// _ = log.debug(s"updateProjectADM - update query: {}", updateProjectSparqlString)
_ <- appActor
.ask(SparqlUpdateRequest(updateProjectSparqlString))
.mapTo[SparqlUpdateResponse]
/* Verify that the project was updated. */
maybeUpdatedProject <- getSingleProjectADM(
identifier = ProjectIdentifierADM(maybeIri = Some(projectIri)),
requestingUser = KnoraSystemInstances.Users.SystemUser,
skipCache = true
)
updatedProject: ProjectADM =
maybeUpdatedProject.getOrElse(
throw UpdateNotPerformedException("Project was not updated. Please report this as a possible bug.")
)
_ = log.debug(
"updateProjectADM - projectUpdatePayload: {} / updatedProject: {}",
projectUpdatePayload,
updatedProject
)
_ = if (projectUpdatePayload.shortname.isDefined) {
val unescapedShortName: String = stringFormatter.fromSparqlEncodedString(projectUpdatePayload.shortname.get)
if (updatedProject.shortname != unescapedShortName)
throw UpdateNotPerformedException(
"Project's 'shortname' was not updated. Please report this as a possible bug."
)
}
_ = if (projectUpdatePayload.longname.isDefined) {
val unescapedLongname: Option[String] =
stringFormatter.unescapeOptionalString(projectUpdatePayload.longname)
if (updatedProject.longname != unescapedLongname)
throw UpdateNotPerformedException(
s"Project's 'longname' was not updated. Please report this as a possible bug."
)
}
_ = if (projectUpdatePayload.description.isDefined) {
val unescapedDescriptions: Seq[StringLiteralV2] = projectUpdatePayload.description.get.map(desc =>
StringLiteralV2(stringFormatter.fromSparqlEncodedString(desc.value), desc.language)
)
if (updatedProject.description.diff(unescapedDescriptions).nonEmpty)
throw UpdateNotPerformedException(
"Project's 'description' was not updated. Please report this as a possible bug."
)
}
_ = if (projectUpdatePayload.keywords.isDefined) {
val unescapedKeywords: Seq[String] =
projectUpdatePayload.keywords.get.map(key => stringFormatter.fromSparqlEncodedString(key))
if (updatedProject.keywords.sorted != unescapedKeywords.sorted)
throw UpdateNotPerformedException(
"Project's 'keywords' was not updated. Please report this as a possible bug."
)
}
_ = if (projectUpdatePayload.logo.isDefined) {
val unescapedLogo: Option[String] = stringFormatter.unescapeOptionalString(projectUpdatePayload.logo)
if (updatedProject.logo != unescapedLogo)
throw UpdateNotPerformedException(
"Project's 'logo' was not updated. Please report this as a possible bug."
)
}
_ = if (projectUpdatePayload.status.isDefined) {
if (updatedProject.status != projectUpdatePayload.status.get)
throw UpdateNotPerformedException(
"Project's 'status' was not updated. Please report this as a possible bug."
)
}
_ = if (projectUpdatePayload.selfjoin.isDefined) {
if (updatedProject.selfjoin != projectUpdatePayload.selfjoin.get)
throw UpdateNotPerformedException(
"Project's 'selfjoin' status was not updated. Please report this as a possible bug."
)
}
} yield ProjectOperationResponseADM(project = updatedProject)
}
/**
* Creates a project.
*
* @param createProjectRequest the new project's information.
*
* @param requestingUser the user that is making the request.
* @param apiRequestID the unique api request ID.
* @return a [[ProjectOperationResponseADM]].
* @throws ForbiddenException in the case that the user is not allowed to perform the operation.
* @throws DuplicateValueException in the case when either the shortname or shortcode are not unique.
* @throws BadRequestException in the case when the shortcode is invalid.
*/
private def projectCreateRequestADM(
createProjectRequest: ProjectCreatePayloadADM,
requestingUser: UserADM,
apiRequestID: UUID
): Future[ProjectOperationResponseADM] = {
/**
* Creates following permissions for the new project
* 1. Permissions for project admins to do all operations on project level and to create, modify, delete, change rights,
* view, and restricted view of all new resources and values that belong to this project.