From 5e4e91499347f4b118b84fa06cb7b0499e4cfecf Mon Sep 17 00:00:00 2001 From: Balduin Landolt <33053745+BalduinLandolt@users.noreply.github.com> Date: Tue, 26 Apr 2022 17:50:02 +0200 Subject: [PATCH] refactor(formatting-logging): reformat scala code and change logging policy (DEV-839) (#2051) * refactor: reduce logging noise * refactor(scalafmt): align.preset most instead of some --- .scalafmt.conf | 2 +- build.sbt | 2 +- .../src/main/scala/dsp/api/main/MainApp.scala | 6 +- project/plugins.sbt | 27 +- .../org/knora/webapi/config/AppConfig.scala | 1 - .../GenerateContributorsFile.scala | 6 +- .../knora/webapi/exceptions/Exceptions.scala | 2 +- .../knora/webapi/feature/FeatureFactory.scala | 6 +- .../http/handler/KnoraExceptionHandler.scala | 2 +- .../webapi/http/status/ApiStatusCodesV1.scala | 40 +- .../webapi/http/version/ServerVersion.scala | 4 +- .../webapi/messages/OntologyConstants.scala | 1074 +++---- .../webapi/messages/StringFormatter.scala | 52 +- .../GroupsErrorMessagesADM.scala | 8 +- .../groupsmessages/GroupsMessagesADM.scala | 2 +- .../listsmessages/ListsErrorMessagesADM.scala | 28 +- .../listsmessages/ListsMessagesADM.scala | 60 +- .../PermissionsMessagesADM.scala | 2 +- .../PermissionsMessagesUtilADM.scala | 8 +- .../ProjectsErrorMessagesADM.scala | 24 +- .../usersmessages/UsersErrorMessagesADM.scala | 24 +- .../TriplestoreMessages.scala | 8 +- .../messages/twirl/ResourceHtmlView.scala | 4 +- .../messages/util/CalendarDateUtilV2.scala | 10 +- .../util/ConstructResponseUtilV2.scala | 99 +- .../webapi/messages/util/DateUtilV1.scala | 22 +- .../messages/util/FakeTriplestore.scala | 2 +- .../webapi/messages/util/MessageUtil.scala | 10 +- .../messages/util/PermissionUtilADM.scala | 40 +- .../webapi/messages/util/UserUtilADM.scala | 10 +- .../webapi/messages/util/ValueUtilV1.scala | 88 +- .../webapi/messages/util/rdf/JsonLDUtil.scala | 22 +- .../messages/util/rdf/RdfFeatureFactory.scala | 12 +- .../util/rdf/jenaimpl/JenaFormatUtil.scala | 2 +- .../util/rdf/jenaimpl/JenaModel.scala | 6 +- .../util/rdf/rdf4jimpl/RDF4JFormatUtil.scala | 2 +- .../util/rdf/rdf4jimpl/RDF4JModel.scala | 6 +- .../rdf/rdf4jimpl/RDF4JShaclValidator.scala | 2 +- .../search/gravsearch/GravsearchParser.scala | 16 +- .../prequery/AbstractPrequeryGenerator.scala | 26 +- .../GravsearchQueryOptimisationFactory.scala | 4 +- .../prequery/TopologicalSortUtil.scala | 2 +- ...tationReadingGravsearchTypeInspector.scala | 85 +- .../GravsearchTypeInspectionRunner.scala | 20 +- .../types/GravsearchTypeInspectionUtil.scala | 4 +- .../types/GravsearchTypeInspector.scala | 2 +- .../InferringGravsearchTypeInspector.scala | 136 +- .../util/standoff/StandoffTagUtilV2.scala | 286 +- .../util/standoff/XMLToStandoffUtil.scala | 16 +- .../messages/util/standoff/XMLUtil.scala | 2 +- .../ckanmessages/CkanMessagesV1.scala | 6 +- .../listmessages/ListMessagesV1.scala | 4 +- .../ontologymessages/OntologyMessagesV1.scala | 6 +- .../resourcemessages/ResourceMessagesV1.scala | 110 +- .../searchmessages/SearchMessagesV1.scala | 24 +- .../usermessages/UserMessagesV1.scala | 20 +- .../valuemessages/ValueMessagesV1.scala | 40 +- .../v2/responder/KnoraResponseV2.scala | 4 +- .../listsmessages/ListsMessagesV2.scala | 12 +- ...aseToApiV2ComplexTransformationRules.scala | 104 +- ...BaseToApiV2SimpleTransformationRules.scala | 4 +- .../ontologymessages/OntologyMessagesV2.scala | 122 +- .../resourcemessages/ResourceMessagesV2.scala | 227 +- .../resourceAndValueEventsUtil.scala | 12 +- .../standoffmessages/StandoffMessagesV2.scala | 20 +- .../valuemessages/ValueMessagesV2.scala | 1059 +++---- .../knora/webapi/responders/Responder.scala | 52 +- .../responders/admin/GroupsResponderADM.scala | 711 ++--- .../responders/admin/ListsResponderADM.scala | 1700 ++++++----- .../admin/PermissionsResponderADM.scala | 1432 ++++----- .../admin/ProjectsResponderADM.scala | 749 ++--- .../responders/admin/SipiResponderADM.scala | 98 +- .../responders/admin/StoresResponderADM.scala | 18 +- .../responders/v1/CkanResponderV1.scala | 182 +- .../responders/v1/ListsResponderV1.scala | 65 +- .../responders/v1/OntologyResponderV1.scala | 472 +-- .../responders/v1/ProjectsResponderV1.scala | 252 +- .../responders/v1/ResourcesResponderV1.scala | 2582 ++++++++-------- .../responders/v1/SearchResponderV1.scala | 628 ++-- .../responders/v1/StandoffResponderV1.scala | 16 +- .../responders/v1/UsersResponderV1.scala | 277 +- .../responders/v1/ValuesResponderV1.scala | 2551 ++++++++-------- .../responders/v2/ListsResponderV2.scala | 16 +- .../responders/v2/OntologyResponderV2.scala | 2638 +++++++++-------- .../webapi/responders/v2/ResourceUtilV2.scala | 12 +- .../responders/v2/ResourcesResponderV2.scala | 1772 +++++------ .../v2/ResponderWithStandoffV2.scala | 16 +- .../responders/v2/SearchResponderV2.scala | 613 ++-- .../responders/v2/StandoffResponderV2.scala | 1004 ++++--- .../responders/v2/ValuesResponderV2.scala | 1871 ++++++------ .../webapi/responders/v2/ontology/Cache.scala | 134 +- .../v2/ontology/Cardinalities.scala | 330 +-- .../v2/ontology/OntologyHelpers.scala | 406 +-- .../knora/webapi/routing/Authenticator.scala | 392 +-- .../knora/webapi/routing/HealthRoute.scala | 56 +- .../org/knora/webapi/routing/KnoraRoute.scala | 25 +- .../knora/webapi/routing/RouteUtilADM.scala | 22 +- .../knora/webapi/routing/RouteUtilV1.scala | 77 +- .../knora/webapi/routing/RouteUtilV2.scala | 62 +- .../webapi/routing/SwaggerApiDocsRoute.scala | 10 +- .../knora/webapi/routing/VersionRoute.scala | 14 +- .../webapi/routing/admin/GroupsRouteADM.scala | 46 +- .../webapi/routing/admin/ListsRouteADM.scala | 2 +- .../routing/admin/PermissionsRouteADM.scala | 2 +- .../routing/admin/ProjectsRouteADM.scala | 178 +- .../webapi/routing/admin/SipiRouteADM.scala | 18 +- .../webapi/routing/admin/UsersRouteADM.scala | 130 +- .../admin/lists/OldListsRouteADMFeature.scala | 86 +- .../CreatePermissionRouteADM.scala | 12 +- .../DeletePermissionRouteADM.scala | 6 +- .../permissions/GetPermissionsRouteADM.scala | 24 +- .../UpdatePermissionRouteADM.scala | 24 +- .../webapi/routing/v1/AssetsRouteV1.scala | 2 +- .../knora/webapi/routing/v1/CkanRouteV1.scala | 12 +- .../webapi/routing/v1/ListsRouteV1.scala | 40 +- .../webapi/routing/v1/ProjectsRouteV1.scala | 18 +- .../routing/v1/ResourceTypesRouteV1.scala | 76 +- .../webapi/routing/v1/ResourcesRouteV1.scala | 638 ++-- .../webapi/routing/v1/SearchRouteV1.scala | 12 +- .../webapi/routing/v1/StandoffRouteV1.scala | 21 +- .../webapi/routing/v1/UsersRouteV1.scala | 62 +- .../webapi/routing/v1/ValuesRouteV1.scala | 778 +++-- .../webapi/routing/v2/ListsRouteV2.scala | 24 +- .../webapi/routing/v2/OntologiesRouteV2.scala | 381 +-- .../webapi/routing/v2/ResourcesRouteV2.scala | 180 +- .../webapi/routing/v2/SearchRouteV2.scala | 72 +- .../webapi/routing/v2/StandoffRouteV2.scala | 60 +- .../webapi/routing/v2/ValuesRouteV2.scala | 80 +- .../knora/webapi/settings/KnoraSettings.scala | 74 +- .../org/knora/webapi/store/StoreManager.scala | 7 +- .../impl/CacheServiceInMemImpl.scala | 16 +- .../impl/CacheServiceRedisImpl.scala | 12 +- .../settings/CacheServiceSettings.scala | 4 +- .../webapi/store/iiif/SipiConnector.scala | 16 +- .../http/HttpTriplestoreConnector.scala | 95 +- .../upgrade/RepositoryUpdater.scala | 32 +- .../upgrade/plugins/UpgradePluginPR1307.scala | 6 +- .../upgrade/plugins/UpgradePluginPR1322.scala | 6 +- .../upgrade/plugins/UpgradePluginPR1367.scala | 2 +- .../upgrade/plugins/UpgradePluginPR1372.scala | 4 +- .../upgrade/plugins/UpgradePluginPR1746.scala | 2 +- .../upgrade/plugins/UpgradePluginPR1921.scala | 2 +- .../upgrade/plugins/UpgradePluginPR2018.scala | 4 +- .../org/knora/webapi/util/ActorUtil.scala | 2 +- .../org/knora/webapi/util/FileUtil.scala | 2 +- .../knora/webapi/util/cache/CacheUtil.scala | 6 +- .../org/knora/webapi/AsyncCoreSpec.scala | 4 +- .../scala/org/knora/webapi/CoreSpec.scala | 6 +- .../test/scala/org/knora/webapi/E2ESpec.scala | 8 +- .../org/knora/webapi/ITKnoraFakeSpec.scala | 10 +- .../org/knora/webapi/ITKnoraLiveSpec.scala | 8 +- .../org/knora/webapi/IntegrationSpec.scala | 12 +- .../knora/webapi/ManagersWithMockedSipi.scala | 1 - .../test/scala/org/knora/webapi/R2RSpec.scala | 4 +- .../knora/webapi/TestContainerFuseki.scala | 2 +- .../org/knora/webapi/TestContainerRedis.scala | 2 +- .../org/knora/webapi/TestContainersAll.scala | 10 +- .../knora/webapi/e2e/CORSSupportE2ESpec.scala | 2 +- .../knora/webapi/e2e/HealthRouteE2ESpec.scala | 14 +- .../knora/webapi/e2e/InstanceChecker.scala | 16 +- .../webapi/e2e/RejectingRouteE2ESpec.scala | 8 +- .../webapi/e2e/admin/GroupsADME2ESpec.scala | 6 +- .../e2e/admin/PermissionsADME2ESpec.scala | 28 +- .../webapi/e2e/admin/ProjectsADME2ESpec.scala | 16 +- .../webapi/e2e/admin/SipiADME2ESpec.scala | 10 +- .../webapi/e2e/admin/UsersADME2ESpec.scala | 24 +- .../DeleteListItemsRouteADME2ESpec.scala | 10 +- .../OldListsRouteADMFeatureE2ESpec.scala | 32 +- .../UpdateListItemsRouteADME2ESpec.scala | 24 +- .../e2e/http/ServerVersionE2ESpec.scala | 2 +- .../e2e/v1/AuthenticationV1E2ESpec.scala | 50 +- .../knora/webapi/e2e/v1/ErrorV1E2ESpec.scala | 4 +- .../knora/webapi/e2e/v1/ListsV1E2ESpec.scala | 10 +- .../e2e/v1/PermissionsHandlingV1E2ESpec.scala | 6 +- .../webapi/e2e/v1/ProjectsV1E2ESpec.scala | 14 +- .../webapi/e2e/v1/ResourcesV1R2RSpec.scala | 82 +- .../knora/webapi/e2e/v1/SipiV1R2RSpec.scala | 4 +- .../webapi/e2e/v1/StandoffV1R2RSpec.scala | 30 +- .../knora/webapi/e2e/v1/UsersV1E2ESpec.scala | 10 +- .../knora/webapi/e2e/v1/ValuesV1R2RSpec.scala | 30 +- .../e2e/v2/AuthenticationV2E2ESpec.scala | 68 +- .../knora/webapi/e2e/v2/MarkupHeader.scala | 8 +- .../webapi/e2e/v2/OntologyV2R2RSpec.scala | 66 +- .../knora/webapi/e2e/v2/ProjectHeader.scala | 8 +- .../e2e/v2/ResourcesRouteV2E2ESpec.scala | 250 +- .../webapi/e2e/v2/ResponseCheckerV2Spec.scala | 7 +- .../knora/webapi/e2e/v2/SchemaHeader.scala | 8 +- .../webapi/e2e/v2/SearchRouteV2R2RSpec.scala | 12 +- .../e2e/v2/StandoffRouteV2E2ESpec.scala | 54 +- .../webapi/e2e/v2/ValuesRouteV2E2ESpec.scala | 708 ++--- .../knora/webapi/e2e/v2/ValuesV2R2RSpec.scala | 2 +- .../knora/webapi/it/VersionRouteITSpec.scala | 15 +- .../webapi/it/v1/DrawingsGodsV1ITSpec.scala | 8 +- .../knora/webapi/it/v1/ErrorV1ITSpec.scala | 2 +- .../it/v1/KnoraSipiIntegrationV1ITSpec.scala | 120 +- .../it/v2/KnoraSipiIntegrationV2ITSpec.scala | 118 +- .../webapi/messages/StringFormatterSpec.scala | 38 +- .../PermissionsMessagesADMSpec.scala | 36 +- .../usersmessages/UsersMessagesADMSpec.scala | 32 +- .../GroupsValueObjectsADMSpec.scala | 4 +- .../ListsValueObjectsADMSpec.scala | 6 +- .../ProjectsValueObjectsADMSpec.scala | 6 +- .../UsersValueObjectsADMSpec.scala | 6 +- .../TriplestoreMessagesSpec.scala | 4 +- .../util/ConstructResponseUtilV2Spec.scala | 21 +- .../messages/util/PermissionUtilADMSpec.scala | 8 +- .../messages/util/rdf/JsonLDUtilSpec.scala | 59 +- .../util/rdf/KnoraResponseV2Spec.scala | 32 +- .../messages/util/rdf/RdfFormatUtilSpec.scala | 55 +- .../messages/util/rdf/RdfModelSpec.scala | 28 +- .../util/rdf/ShaclValidatorSpec.scala | 6 +- .../types/GravsearchTypeInspectorSpec.scala | 54 +- .../util/standoff/StandoffTagUtilV2Spec.scala | 92 +- .../util/standoff/XMLToStandoffUtilSpec.scala | 6 +- .../messages/util/standoff/XMLUtilSpec.scala | 2 +- .../PermissionMessagesV1Spec.scala | 18 +- .../usermessages/UserMessagesV1Spec.scala | 24 +- ...hangePropertyGuiElementRequestV2Spec.scala | 20 +- .../knora/webapi/models/OntologyModels.scala | 16 +- .../models/filemodels/FileModelUtil.scala | 30 +- .../webapi/models/filemodels/FileModels.scala | 8 +- .../models/filemodels/FileModelsSpec.scala | 164 +- .../standoffmodels/StandoffModels.scala | 2 +- .../standoffmodels/StandoffModelsSpec.scala | 10 +- .../other/v1/DrawingsGodsV1E2ESpec.scala | 10 +- .../webapi/other/v1/DrawingsGodsV1Spec.scala | 20 +- .../other/v2/LumieresLausanneV2E2ESpec.scala | 2 +- .../admin/GroupsResponderADMSpec.scala | 10 +- .../admin/ListsResponderADMSpec.scala | 74 +- .../admin/PermissionsResponderADMSpec.scala | 28 +- .../admin/ProjectsResponderADMSpec.scala | 18 +- .../responders/v1/ListsResponderV1Spec.scala | 2 +- .../v1/OntologyResponderV1Spec.scala | 2 +- .../v1/ResourcesResponderV1Spec.scala | 38 +- .../responders/v1/UsersResponderV1Spec.scala | 10 +- .../responders/v1/ValuesResponderV1Spec.scala | 42 +- .../responders/v2/ListsResponderV2Spec.scala | 2 +- .../v2/OntologyResponderV2Spec.scala | 126 +- .../v2/ResourcesResponderV2Spec.scala | 50 +- .../v2/ResourcesResponseCheckerV2Spec.scala | 2 +- .../responders/v2/SearchResponderV2Spec.scala | 2 +- .../v2/SearchResponderV2SpecFullData.scala | 6 +- .../v2/StandoffResponderV2Spec.scala | 2 +- .../responders/v2/ValuesResponderV2Spec.scala | 542 ++-- .../responders/v2/ontology/CacheSpec.scala | 26 +- .../DeleteCardinalitiesFromClassSpec.scala | 10 +- .../webapi/routing/AuthenticatorSpec.scala | 6 +- .../SharedOntologyTestDataADM.scala | 54 +- .../sharedtestdata/SharedTestDataADM.scala | 8 +- .../webapi/store/iiif/MockSipiConnector.scala | 2 +- .../triplestore/AllTriplestoreSpec.scala | 6 +- .../plugins/UpgradePluginPR1307Spec.scala | 32 +- .../plugins/UpgradePluginPR2018Spec.scala | 2 +- .../upgrade/plugins/UpgradePluginSpec.scala | 2 +- .../webapi/util/ApacheLuceneSupportSpec.scala | 14 +- .../webapi/util/Base64UrlCheckDigitSpec.scala | 4 +- .../knora/webapi/util/MutableTestIri.scala | 2 +- .../org/knora/webapi/util/StartupUtils.scala | 2 +- 258 files changed, 16816 insertions(+), 15711 deletions(-) diff --git a/.scalafmt.conf b/.scalafmt.conf index bf360eab5b..e94dd85083 100644 --- a/.scalafmt.conf +++ b/.scalafmt.conf @@ -1,6 +1,6 @@ version = "2.7.5" maxColumn = 120 -align.preset = some +align.preset = most align.multiline = false continuationIndent.defnSite = 2 assumeStandardLibraryStripMargin = true diff --git a/build.sbt b/build.sbt index db95f32dbf..1fd333488f 100644 --- a/build.sbt +++ b/build.sbt @@ -138,7 +138,7 @@ lazy val webapi: Project = Project(id = "webapi", base = file("webapi")) }, // allows sbt-javaagent to work with sbt-revolver reStart / javaOptions ++= webapiJavaRunOptions, javaAgents += Dependencies.aspectjweaver, - fork := true, // run tests in a forked JVM + fork := true, // run tests in a forked JVM Test / testForkedParallel := false, // run forked tests in parallel Test / parallelExecution := false, // run non-forked tests in parallel // Global / concurrentRestrictions += Tags.limit(Tags.Test, 1), // restrict the number of concurrently executing tests in all projects diff --git a/dsp-api-main/src/main/scala/dsp/api/main/MainApp.scala b/dsp-api-main/src/main/scala/dsp/api/main/MainApp.scala index cbdc78b01b..fb8f48ad54 100644 --- a/dsp-api-main/src/main/scala/dsp/api/main/MainApp.scala +++ b/dsp-api-main/src/main/scala/dsp/api/main/MainApp.scala @@ -8,10 +8,10 @@ object MainApp extends ZIOAppDefault { val effect: ZIO[Console with SchemaRepo, Nothing, Unit] = for { profile <- SchemaRepo.lookup("user1").orDie - _ <- printLine(profile).orDie - _ <- printLine(42).orDie + _ <- printLine(profile).orDie + _ <- printLine(42).orDie } yield () val mainApp: ZIO[Any, Nothing, Unit] = effect.provide(Console.live ++ SchemaRepoLive.layer) - def run: ZIO[Any, Nothing, Unit] = mainApp + def run: ZIO[Any, Nothing, Unit] = mainApp } diff --git a/project/plugins.sbt b/project/plugins.sbt index 293d3d8425..a899a76a0a 100644 --- a/project/plugins.sbt +++ b/project/plugins.sbt @@ -6,22 +6,27 @@ resolvers ++= Seq( addDependencyTreePlugin // Knora -addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "1.0.2") -addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.9.9") -addSbtPlugin("io.kamon" % "sbt-aspectj-runner" % "1.1.1") +addSbtPlugin("com.typesafe.sbt" % "sbt-git" % "1.0.2") +addSbtPlugin("com.github.sbt" % "sbt-native-packager" % "1.9.9") +addSbtPlugin("io.kamon" % "sbt-aspectj-runner" % "1.1.1") // webapi -addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1") -addSbtPlugin("com.typesafe.sbt" % "sbt-twirl" % "1.5.1") -addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.10") -addSbtPlugin("com.lightbend.sbt" % "sbt-javaagent" % "0.1.5") -addSbtPlugin("io.gatling" % "gatling-sbt" % "2.2.2") -addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.6.1") -addSbtPlugin("com.codacy" % "sbt-codacy-coverage" % "1.3.15") -addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0") +addSbtPlugin("io.spray" % "sbt-revolver" % "0.9.1") +addSbtPlugin("com.typesafe.sbt" % "sbt-twirl" % "1.5.1") +addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.14.10") +addSbtPlugin("com.lightbend.sbt" % "sbt-javaagent" % "0.1.5") +addSbtPlugin("io.gatling" % "gatling-sbt" % "2.2.2") +addSbtPlugin("org.scoverage" % "sbt-scoverage" % "1.6.1") +addSbtPlugin("com.codacy" % "sbt-codacy-coverage" % "1.3.15") +addSbtPlugin("com.eed3si9n" % "sbt-buildinfo" % "0.11.0") // ad-hoc plugins - uncomment on demenad and keep it commented out in main branch + // https://github.com/rtimush/sbt-updates // addSbtPlugin("com.timushev.sbt" % "sbt-updates" % "0.6.1") + // https://github.com/cb372/sbt-explicit-dependencies // addSbtPlugin("com.github.cb372" % "sbt-explicit-dependencies" % "0.2.16") + +// https://scalameta.org/scalafmt/docs/installation.html#sbt +// addSbtPlugin("org.scalameta" % "sbt-scalafmt" % "2.4.6") diff --git a/webapi/src/main/scala/org/knora/webapi/config/AppConfig.scala b/webapi/src/main/scala/org/knora/webapi/config/AppConfig.scala index 99c7d9b58b..97c6aa841c 100644 --- a/webapi/src/main/scala/org/knora/webapi/config/AppConfig.scala +++ b/webapi/src/main/scala/org/knora/webapi/config/AppConfig.scala @@ -7,7 +7,6 @@ import zio.config._ import typesafe._ import magnolia._ - final case class AppConfig(cacheService: CacheServiceConfig) object AppConfig { diff --git a/webapi/src/main/scala/org/knora/webapi/contributors/GenerateContributorsFile.scala b/webapi/src/main/scala/org/knora/webapi/contributors/GenerateContributorsFile.scala index 852f23147e..4e422b9800 100644 --- a/webapi/src/main/scala/org/knora/webapi/contributors/GenerateContributorsFile.scala +++ b/webapi/src/main/scala/org/knora/webapi/contributors/GenerateContributorsFile.scala @@ -23,13 +23,13 @@ object GenerateContributorsFile extends App { // Configuration - val contributorsUrl = "https://api.github.com/repos/dasch-swiss/knora-api/contributors" + val contributorsUrl = "https://api.github.com/repos/dasch-swiss/knora-api/contributors" val defaultOutputFile = "Contributors.md" // Command-line args - private val conf = new GenerateContributorsFileConf(args.toIndexedSeq) - private val token = conf.token.toOption + private val conf = new GenerateContributorsFileConf(args.toIndexedSeq) + private val token = conf.token.toOption private val outputFile: Path = Paths.get(conf.output()) // Get the list of contributors. diff --git a/webapi/src/main/scala/org/knora/webapi/exceptions/Exceptions.scala b/webapi/src/main/scala/org/knora/webapi/exceptions/Exceptions.scala index f17a123a0d..88f859ba97 100644 --- a/webapi/src/main/scala/org/knora/webapi/exceptions/Exceptions.scala +++ b/webapi/src/main/scala/org/knora/webapi/exceptions/Exceptions.scala @@ -355,7 +355,7 @@ object InconsistentRepositoryDataException { } case class MissingLastModificationDateOntologyException(message: String, cause: Option[Throwable] = None) - extends InternalServerException(message, cause) + extends InternalServerException(message, cause) /** * Indicates that the API server generated invalid JSON in an API response. diff --git a/webapi/src/main/scala/org/knora/webapi/feature/FeatureFactory.scala b/webapi/src/main/scala/org/knora/webapi/feature/FeatureFactory.scala index 22e3e25975..dbd4d607f2 100644 --- a/webapi/src/main/scala/org/knora/webapi/feature/FeatureFactory.scala +++ b/webapi/src/main/scala/org/knora/webapi/feature/FeatureFactory.scala @@ -118,13 +118,13 @@ object FeatureToggle { /** * The name of the HTTP request header containing feature toggles. */ - val REQUEST_HEADER: String = "X-Knora-Feature-Toggles" + val REQUEST_HEADER: String = "X-Knora-Feature-Toggles" val REQUEST_HEADER_LOWERCASE: String = REQUEST_HEADER.toLowerCase /** * The name of the HTTP response header that lists configured feature toggles. */ - val RESPONSE_HEADER: String = REQUEST_HEADER + val RESPONSE_HEADER: String = REQUEST_HEADER val RESPONSE_HEADER_LOWERCASE: String = REQUEST_HEADER_LOWERCASE /** @@ -369,7 +369,7 @@ class RequestContextFeatureFactoryConfig(requestContext: RequestContext, parent: headerValueItem.split('=').map(_.trim) match { case Array(featureNameAndVersionStr: String, isEnabledStr: String) => val featureNameAndVersion: Array[String] = featureNameAndVersionStr.split(':').map(_.trim) - val featureName: String = featureNameAndVersion.head + val featureName: String = featureNameAndVersion.head // Accept the boolean values that are accepted in application.conf. val isEnabled: Boolean = if (TRUE_STRINGS.contains(isEnabledStr.toLowerCase)) { diff --git a/webapi/src/main/scala/org/knora/webapi/http/handler/KnoraExceptionHandler.scala b/webapi/src/main/scala/org/knora/webapi/http/handler/KnoraExceptionHandler.scala index 7152ef8db2..53fa94eff0 100644 --- a/webapi/src/main/scala/org/knora/webapi/http/handler/KnoraExceptionHandler.scala +++ b/webapi/src/main/scala/org/knora/webapi/http/handler/KnoraExceptionHandler.scala @@ -110,7 +110,7 @@ object KnoraExceptionHandler extends LazyLogging { val responseFields: Map[String, JsValue] = Map( "status" -> JsNumber(apiStatus.id), - "error" -> JsString(makeClientErrorMessage(ex, settings)) + "error" -> JsString(makeClientErrorMessage(ex, settings)) ) ++ maybeAccess HttpResponse( diff --git a/webapi/src/main/scala/org/knora/webapi/http/status/ApiStatusCodesV1.scala b/webapi/src/main/scala/org/knora/webapi/http/status/ApiStatusCodesV1.scala index ce1a020a64..fdf2e6ded8 100644 --- a/webapi/src/main/scala/org/knora/webapi/http/status/ApiStatusCodesV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/http/status/ApiStatusCodesV1.scala @@ -13,39 +13,39 @@ import org.knora.webapi.exceptions._ * Based on `salsah/api/ApiErrors.php`. */ object ApiStatusCodesV1 extends Enumeration { - val OK = Value(0) - val INVALID_REQUEST_METHOD = Value(1) - val CREDENTIALS_NOT_VALID = Value(2) + val OK = Value(0) + val INVALID_REQUEST_METHOD = Value(1) + val CREDENTIALS_NOT_VALID = Value(2) val NO_RIGHTS_FOR_OPERATION = Value(3) - val INTERNAL_SALSAH_ERROR = Value(4) - val NO_PROPERTIES = Value(5) - val NOT_IN_USERDATA = Value(6) - val RESOURCE_ID_MISSING = Value(7) - val UNKNOWN_VOCABULARY = Value(8) + val INTERNAL_SALSAH_ERROR = Value(4) + val NO_PROPERTIES = Value(5) + val NOT_IN_USERDATA = Value(6) + val RESOURCE_ID_MISSING = Value(7) + val UNKNOWN_VOCABULARY = Value(8) /** * The requested item was not found. This was called NO_NODES_FOUND in SALSAH; its meaning has been broadened here. */ val NOT_FOUND = Value(9) - val API_ENDPOINT_NOT_FOUND = Value(10) - val INVALID_REQUEST_TYPE = Value(11) - val PROPERTY_ID_MISSING = Value(12) - val NOT_YET_IMPLEMENTED = Value(13) - val COULD_NOT_OPEN_PROGRESS_FILE = Value(14) + val API_ENDPOINT_NOT_FOUND = Value(10) + val INVALID_REQUEST_TYPE = Value(11) + val PROPERTY_ID_MISSING = Value(12) + val NOT_YET_IMPLEMENTED = Value(13) + val COULD_NOT_OPEN_PROGRESS_FILE = Value(14) val VALUE_ID_OR_RESTYPE_ID_MISSING = Value(15) val HLIST_ALREADY_EXISTENT = Value(16) - val HLIST_NO_LABELS = Value(17) - val HLIST_NOT_EXISTING = Value(18) - val HLIST_NO_POSITION = Value(19) + val HLIST_NO_LABELS = Value(17) + val HLIST_NOT_EXISTING = Value(18) + val HLIST_NO_POSITION = Value(19) val HLIST_INVALID_POSITION = Value(20) - val SELECTION_NO_LABELS = Value(21) - val SELECTION_ALREADY_EXISTENT = Value(22) + val SELECTION_NO_LABELS = Value(21) + val SELECTION_ALREADY_EXISTENT = Value(22) val SELECTION_MISSING_OR_INVALID_POSITION = Value(23) - val SELECTION_DELETE_FAILED = Value(24) - val SELECTION_NODE_ALREADY_EXISTENT = Value(25) + val SELECTION_DELETE_FAILED = Value(24) + val SELECTION_NODE_ALREADY_EXISTENT = Value(25) val GEONAMES_GEONAME_ID_EXISTING = Value(26) diff --git a/webapi/src/main/scala/org/knora/webapi/http/version/ServerVersion.scala b/webapi/src/main/scala/org/knora/webapi/http/version/ServerVersion.scala index 0690d87ea6..21cc4e3ceb 100644 --- a/webapi/src/main/scala/org/knora/webapi/http/version/ServerVersion.scala +++ b/webapi/src/main/scala/org/knora/webapi/http/version/ServerVersion.scala @@ -15,9 +15,9 @@ import akka.http.scaladsl.server.Route */ object ServerVersion { - private val ApiNameAndVersion = s"${BuildInfo.name}/${BuildInfo.version}" + private val ApiNameAndVersion = s"${BuildInfo.name}/${BuildInfo.version}" private val AkkaNameAndVersion = s"akka-http/${BuildInfo.akkaHttp}" - private val AllProducts = ApiNameAndVersion + " " + AkkaNameAndVersion + private val AllProducts = ApiNameAndVersion + " " + AkkaNameAndVersion def serverVersionHeader: Server = Server(products = AllProducts) diff --git a/webapi/src/main/scala/org/knora/webapi/messages/OntologyConstants.scala b/webapi/src/main/scala/org/knora/webapi/messages/OntologyConstants.scala index d79d24a89e..ff0d3ee0fc 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/OntologyConstants.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/OntologyConstants.scala @@ -14,48 +14,48 @@ import exceptions.InconsistentRepositoryDataException object OntologyConstants { object Rdf { - val RdfOntologyIri: IRI = "http://www.w3.org/1999/02/22-rdf-syntax-ns" + val RdfOntologyIri: IRI = "http://www.w3.org/1999/02/22-rdf-syntax-ns" val RdfPrefixExpansion: IRI = RdfOntologyIri + "#" - val Type: IRI = RdfPrefixExpansion + "type" - val Subject: IRI = RdfPrefixExpansion + "subject" - val Predicate: IRI = RdfPrefixExpansion + "predicate" - val Object: IRI = RdfPrefixExpansion + "object" - val Property: IRI = RdfPrefixExpansion + "Property" + val Type: IRI = RdfPrefixExpansion + "type" + val Subject: IRI = RdfPrefixExpansion + "subject" + val Predicate: IRI = RdfPrefixExpansion + "predicate" + val Object: IRI = RdfPrefixExpansion + "object" + val Property: IRI = RdfPrefixExpansion + "Property" val LangString: IRI = RdfPrefixExpansion + "langString" } object Rdfs { - val RdfsOntologyIri: IRI = "http://www.w3.org/2000/01/rdf-schema" + val RdfsOntologyIri: IRI = "http://www.w3.org/2000/01/rdf-schema" val RdfsPrefixExpansion: IRI = RdfsOntologyIri + "#" - val Label: IRI = RdfsPrefixExpansion + "label" - val Comment: IRI = RdfsPrefixExpansion + "comment" - val SubClassOf: IRI = RdfsPrefixExpansion + "subClassOf" + val Label: IRI = RdfsPrefixExpansion + "label" + val Comment: IRI = RdfsPrefixExpansion + "comment" + val SubClassOf: IRI = RdfsPrefixExpansion + "subClassOf" val SubPropertyOf: IRI = RdfsPrefixExpansion + "subPropertyOf" - val Datatype: IRI = RdfsPrefixExpansion + "Datatype" + val Datatype: IRI = RdfsPrefixExpansion + "Datatype" } object Owl { - val OwlOntologyIri = "http://www.w3.org/2002/07/owl" + val OwlOntologyIri = "http://www.w3.org/2002/07/owl" val OwlPrefixExpansion: IRI = OwlOntologyIri + "#" - val Ontology: IRI = OwlPrefixExpansion + "Ontology" - val Restriction: IRI = OwlPrefixExpansion + "Restriction" - val OnProperty: IRI = OwlPrefixExpansion + "onProperty" - val Cardinality: IRI = OwlPrefixExpansion + "cardinality" + val Ontology: IRI = OwlPrefixExpansion + "Ontology" + val Restriction: IRI = OwlPrefixExpansion + "Restriction" + val OnProperty: IRI = OwlPrefixExpansion + "onProperty" + val Cardinality: IRI = OwlPrefixExpansion + "cardinality" val MinCardinality: IRI = OwlPrefixExpansion + "minCardinality" val MaxCardinality: IRI = OwlPrefixExpansion + "maxCardinality" - val ObjectProperty: IRI = OwlPrefixExpansion + "ObjectProperty" - val DatatypeProperty: IRI = OwlPrefixExpansion + "DatatypeProperty" + val ObjectProperty: IRI = OwlPrefixExpansion + "ObjectProperty" + val DatatypeProperty: IRI = OwlPrefixExpansion + "DatatypeProperty" val AnnotationProperty: IRI = OwlPrefixExpansion + "AnnotationProperty" val TransitiveProperty: IRI = OwlPrefixExpansion + "TransitiveProperty" val Class: IRI = OwlPrefixExpansion + "Class" val WithRestrictions: IRI = OwlPrefixExpansion + "withRestrictions" - val OnDatatype: IRI = OwlPrefixExpansion + "onDatatype" + val OnDatatype: IRI = OwlPrefixExpansion + "onDatatype" /** * Cardinality IRIs expressed as OWL restrictions, which specify the properties that resources of @@ -94,10 +94,10 @@ object OntologyConstants { object Xsd { val XsdPrefixExpansion: IRI = "http://www.w3.org/2001/XMLSchema#" - val String: IRI = XsdPrefixExpansion + "string" - val Boolean: IRI = XsdPrefixExpansion + "boolean" - val Int: IRI = XsdPrefixExpansion + "int" - val Integer: IRI = XsdPrefixExpansion + "integer" + val String: IRI = XsdPrefixExpansion + "string" + val Boolean: IRI = XsdPrefixExpansion + "boolean" + val Int: IRI = XsdPrefixExpansion + "int" + val Integer: IRI = XsdPrefixExpansion + "integer" val NonNegativeInteger: IRI = XsdPrefixExpansion + "nonNegativeInteger" lazy val integerTypes: Set[IRI] = Set( @@ -106,19 +106,19 @@ object OntologyConstants { NonNegativeInteger ) - val Decimal: IRI = XsdPrefixExpansion + "decimal" - val Uri: IRI = XsdPrefixExpansion + "anyURI" - val Pattern: IRI = XsdPrefixExpansion + "pattern" - val DateTime: IRI = XsdPrefixExpansion + "dateTime" + val Decimal: IRI = XsdPrefixExpansion + "decimal" + val Uri: IRI = XsdPrefixExpansion + "anyURI" + val Pattern: IRI = XsdPrefixExpansion + "pattern" + val DateTime: IRI = XsdPrefixExpansion + "dateTime" val DateTimeStamp: IRI = XsdPrefixExpansion + "dateTimeStamp" } object Shacl { val ShaclPrefixExpansion: IRI = "http://www.w3.org/ns/shacl#" - val Conforms: IRI = ShaclPrefixExpansion + "conforms" - val Result: IRI = ShaclPrefixExpansion + "result" - val SourceConstraintComponent: IRI = ShaclPrefixExpansion + "sourceConstraintComponent" + val Conforms: IRI = ShaclPrefixExpansion + "conforms" + val Result: IRI = ShaclPrefixExpansion + "result" + val SourceConstraintComponent: IRI = ShaclPrefixExpansion + "sourceConstraintComponent" val DatatypeConstraintComponent: IRI = ShaclPrefixExpansion + "DatatypeConstraintComponent" val MaxCountConstraintComponent: IRI = ShaclPrefixExpansion + "MaxCountConstraintComponent" } @@ -128,8 +128,8 @@ object OntologyConstants { */ object SchemaOrg { val SchemaOrgPrefixExpansion: IRI = "http://schema.org/" - val Name: IRI = SchemaOrgPrefixExpansion + "name" - val NumberOfItems: IRI = SchemaOrgPrefixExpansion + "numberOfItems" + val Name: IRI = SchemaOrgPrefixExpansion + "name" + val NumberOfItems: IRI = SchemaOrgPrefixExpansion + "numberOfItems" } object KnoraInternal { @@ -165,106 +165,106 @@ object OntologyConstants { object KnoraBase { val KnoraBaseOntologyLabel: String = "knora-base" - val KnoraBaseOntologyIri: IRI = KnoraInternal.InternalOntologyStart + "/" + KnoraBaseOntologyLabel + val KnoraBaseOntologyIri: IRI = KnoraInternal.InternalOntologyStart + "/" + KnoraBaseOntologyLabel - val KnoraBasePrefix: String = KnoraBaseOntologyLabel + ":" + val KnoraBasePrefix: String = KnoraBaseOntologyLabel + ":" val KnoraBasePrefixExpansion: IRI = KnoraBaseOntologyIri + "#" val OntologyVersion: IRI = KnoraBasePrefixExpansion + "ontologyVersion" - val IsShared: IRI = KnoraBasePrefixExpansion + "isShared" + val IsShared: IRI = KnoraBasePrefixExpansion + "isShared" val CanBeInstantiated: IRI = KnoraBasePrefixExpansion + "canBeInstantiated" - val IsEditable: IRI = KnoraBasePrefixExpansion + "isEditable" - - val Resource: IRI = KnoraBasePrefixExpansion + "Resource" - val DeletedResource: IRI = KnoraBasePrefixExpansion + "DeletedResource" - val DeletedValue: IRI = KnoraBasePrefixExpansion + "DeletedValue" - val Representation: IRI = KnoraBasePrefixExpansion + "Representation" - val AudioRepresentation: IRI = KnoraBasePrefixExpansion + "AudioRepresentation" - val DDDRepresentation: IRI = KnoraBasePrefixExpansion + "DDDRepresentation" - val DocumentRepresentation: IRI = KnoraBasePrefixExpansion + "DocumentRepresentation" - val ArchiveRepresentation: IRI = KnoraBasePrefixExpansion + "ArchiveRepresentation" + val IsEditable: IRI = KnoraBasePrefixExpansion + "isEditable" + + val Resource: IRI = KnoraBasePrefixExpansion + "Resource" + val DeletedResource: IRI = KnoraBasePrefixExpansion + "DeletedResource" + val DeletedValue: IRI = KnoraBasePrefixExpansion + "DeletedValue" + val Representation: IRI = KnoraBasePrefixExpansion + "Representation" + val AudioRepresentation: IRI = KnoraBasePrefixExpansion + "AudioRepresentation" + val DDDRepresentation: IRI = KnoraBasePrefixExpansion + "DDDRepresentation" + val DocumentRepresentation: IRI = KnoraBasePrefixExpansion + "DocumentRepresentation" + val ArchiveRepresentation: IRI = KnoraBasePrefixExpansion + "ArchiveRepresentation" val MovingImageRepresentation: IRI = KnoraBasePrefixExpansion + "MovingImageRepresentation" - val StillImageRepresentation: IRI = KnoraBasePrefixExpansion + "StillImageRepresentation" - val TextRepresentation: IRI = KnoraBasePrefixExpansion + "TextRepresentation" - - val XMLToStandoffMapping: IRI = KnoraBasePrefixExpansion + "XMLToStandoffMapping" - val HasMappingElement: IRI = KnoraBasePrefixExpansion + "hasMappingElement" - val MappingElement: IRI = KnoraBasePrefixExpansion + "MappingElement" - val MappingStandoffDataTypeClass: IRI = KnoraBasePrefixExpansion + "MappingStandoffDataTypeClass" - val MappingComponent: IRI = KnoraBasePrefixExpansion + "MappingComponent" - val MappingXMLAttribute: IRI = KnoraBasePrefixExpansion + "MappingXMLAttribute" - val MappingHasStandoffClass: IRI = KnoraBasePrefixExpansion + "mappingHasStandoffClass" - val MappingHasStandoffProperty: IRI = KnoraBasePrefixExpansion + "mappingHasStandoffProperty" - val MappingHasXMLClass: IRI = KnoraBasePrefixExpansion + "mappingHasXMLClass" - val MappingHasXMLNamespace: IRI = KnoraBasePrefixExpansion + "mappingHasXMLNamespace" - val MappingHasXMLTagname: IRI = KnoraBasePrefixExpansion + "mappingHasXMLTagname" - val MappingHasXMLAttribute: IRI = KnoraBasePrefixExpansion + "mappingHasXMLAttribute" - val MappingHasXMLAttributename: IRI = KnoraBasePrefixExpansion + "mappingHasXMLAttributename" + val StillImageRepresentation: IRI = KnoraBasePrefixExpansion + "StillImageRepresentation" + val TextRepresentation: IRI = KnoraBasePrefixExpansion + "TextRepresentation" + + val XMLToStandoffMapping: IRI = KnoraBasePrefixExpansion + "XMLToStandoffMapping" + val HasMappingElement: IRI = KnoraBasePrefixExpansion + "hasMappingElement" + val MappingElement: IRI = KnoraBasePrefixExpansion + "MappingElement" + val MappingStandoffDataTypeClass: IRI = KnoraBasePrefixExpansion + "MappingStandoffDataTypeClass" + val MappingComponent: IRI = KnoraBasePrefixExpansion + "MappingComponent" + val MappingXMLAttribute: IRI = KnoraBasePrefixExpansion + "MappingXMLAttribute" + val MappingHasStandoffClass: IRI = KnoraBasePrefixExpansion + "mappingHasStandoffClass" + val MappingHasStandoffProperty: IRI = KnoraBasePrefixExpansion + "mappingHasStandoffProperty" + val MappingHasXMLClass: IRI = KnoraBasePrefixExpansion + "mappingHasXMLClass" + val MappingHasXMLNamespace: IRI = KnoraBasePrefixExpansion + "mappingHasXMLNamespace" + val MappingHasXMLTagname: IRI = KnoraBasePrefixExpansion + "mappingHasXMLTagname" + val MappingHasXMLAttribute: IRI = KnoraBasePrefixExpansion + "mappingHasXMLAttribute" + val MappingHasXMLAttributename: IRI = KnoraBasePrefixExpansion + "mappingHasXMLAttributename" val MappingHasStandoffDataTypeClass: IRI = KnoraBasePrefixExpansion + "mappingHasStandoffDataTypeClass" val MappingElementRequiresSeparator: IRI = KnoraBasePrefixExpansion + "mappingElementRequiresSeparator" - val XSLTransformation: IRI = KnoraBasePrefixExpansion + "XSLTransformation" + val XSLTransformation: IRI = KnoraBasePrefixExpansion + "XSLTransformation" val MappingHasDefaultXSLTransformation: IRI = KnoraBasePrefixExpansion + "mappingHasDefaultXSLTransformation" - val SubjectClassConstraint: IRI = KnoraBasePrefixExpansion + "subjectClassConstraint" - val ObjectClassConstraint: IRI = KnoraBasePrefixExpansion + "objectClassConstraint" - val ObjectDatatypeConstraint: IRI = KnoraBasePrefixExpansion + "objectDatatypeConstraint" + val SubjectClassConstraint: IRI = KnoraBasePrefixExpansion + "subjectClassConstraint" + val ObjectClassConstraint: IRI = KnoraBasePrefixExpansion + "objectClassConstraint" + val ObjectDatatypeConstraint: IRI = KnoraBasePrefixExpansion + "objectDatatypeConstraint" val StandoffParentClassConstraint: IRI = KnoraBasePrefixExpansion + "standoffParentClassConstraint" - val LinkObj: IRI = KnoraBasePrefixExpansion + "LinkObj" - val HasLinkTo: IRI = KnoraBasePrefixExpansion + "hasLinkTo" + val LinkObj: IRI = KnoraBasePrefixExpansion + "LinkObj" + val HasLinkTo: IRI = KnoraBasePrefixExpansion + "hasLinkTo" val HasLinkToValue: IRI = KnoraBasePrefixExpansion + "hasLinkToValue" - val IsPartOf: IRI = KnoraBasePrefixExpansion + "isPartOf" - val IsPartOfValue: IRI = KnoraBasePrefixExpansion + "isPartOfValue" - val Region: IRI = KnoraBasePrefixExpansion + "Region" - val IsRegionOf: IRI = KnoraBasePrefixExpansion + "isRegionOf" + val IsPartOf: IRI = KnoraBasePrefixExpansion + "isPartOf" + val IsPartOfValue: IRI = KnoraBasePrefixExpansion + "isPartOfValue" + val Region: IRI = KnoraBasePrefixExpansion + "Region" + val IsRegionOf: IRI = KnoraBasePrefixExpansion + "isRegionOf" - val Value: IRI = KnoraBasePrefixExpansion + "Value" - val ValueHas: IRI = KnoraBasePrefixExpansion + "valueHas" + val Value: IRI = KnoraBasePrefixExpansion + "Value" + val ValueHas: IRI = KnoraBasePrefixExpansion + "valueHas" val ObjectCannotBeMarkedAsDeleted: IRI = KnoraBasePrefixExpansion + "objectCannotBeMarkedAsDeleted" - val ValueHasString: IRI = KnoraBasePrefixExpansion + "valueHasString" - val ValueHasUUID: IRI = KnoraBasePrefixExpansion + "valueHasUUID" + val ValueHasString: IRI = KnoraBasePrefixExpansion + "valueHasString" + val ValueHasUUID: IRI = KnoraBasePrefixExpansion + "valueHasUUID" val ValueHasMaxStandoffStartIndex: IRI = KnoraBasePrefixExpansion + "valueHasMaxStandoffStartIndex" - val ValueHasLanguage: IRI = KnoraBasePrefixExpansion + "valueHasLanguage" - val ValueHasMapping: IRI = KnoraBasePrefixExpansion + "valueHasMapping" - val ValueHasInteger: IRI = KnoraBasePrefixExpansion + "valueHasInteger" - val ValueHasDecimal: IRI = KnoraBasePrefixExpansion + "valueHasDecimal" - val ValueHasStandoff: IRI = KnoraBasePrefixExpansion + "valueHasStandoff" - val ValueHasStartJDN: IRI = KnoraBasePrefixExpansion + "valueHasStartJDN" - val ValueHasEndJDN: IRI = KnoraBasePrefixExpansion + "valueHasEndJDN" - val ValueHasCalendar: IRI = KnoraBasePrefixExpansion + "valueHasCalendar" - val ValueHasStartPrecision: IRI = KnoraBasePrefixExpansion + "valueHasStartPrecision" - val ValueHasEndPrecision: IRI = KnoraBasePrefixExpansion + "valueHasEndPrecision" - val ValueHasBoolean: IRI = KnoraBasePrefixExpansion + "valueHasBoolean" - val ValueHasUri: IRI = KnoraBasePrefixExpansion + "valueHasUri" - val ValueHasColor: IRI = KnoraBasePrefixExpansion + "valueHasColor" - val ValueHasGeometry: IRI = KnoraBasePrefixExpansion + "valueHasGeometry" - val ValueHasListNode: IRI = KnoraBasePrefixExpansion + "valueHasListNode" - val ValueHasIntervalStart: IRI = KnoraBasePrefixExpansion + "valueHasIntervalStart" - val ValueHasIntervalEnd: IRI = KnoraBasePrefixExpansion + "valueHasIntervalEnd" - val ValueHasTimeStamp: IRI = KnoraBasePrefixExpansion + "valueHasTimeStamp" - val ValueHasOrder: IRI = KnoraBasePrefixExpansion + "valueHasOrder" - val ValueHasRefCount: IRI = KnoraBasePrefixExpansion + "valueHasRefCount" - val ValueHasComment: IRI = KnoraBasePrefixExpansion + "valueHasComment" - val ValueHasGeonameCode: IRI = KnoraBasePrefixExpansion + "valueHasGeonameCode" - val Duration: IRI = KnoraBasePrefixExpansion + "duration" + val ValueHasLanguage: IRI = KnoraBasePrefixExpansion + "valueHasLanguage" + val ValueHasMapping: IRI = KnoraBasePrefixExpansion + "valueHasMapping" + val ValueHasInteger: IRI = KnoraBasePrefixExpansion + "valueHasInteger" + val ValueHasDecimal: IRI = KnoraBasePrefixExpansion + "valueHasDecimal" + val ValueHasStandoff: IRI = KnoraBasePrefixExpansion + "valueHasStandoff" + val ValueHasStartJDN: IRI = KnoraBasePrefixExpansion + "valueHasStartJDN" + val ValueHasEndJDN: IRI = KnoraBasePrefixExpansion + "valueHasEndJDN" + val ValueHasCalendar: IRI = KnoraBasePrefixExpansion + "valueHasCalendar" + val ValueHasStartPrecision: IRI = KnoraBasePrefixExpansion + "valueHasStartPrecision" + val ValueHasEndPrecision: IRI = KnoraBasePrefixExpansion + "valueHasEndPrecision" + val ValueHasBoolean: IRI = KnoraBasePrefixExpansion + "valueHasBoolean" + val ValueHasUri: IRI = KnoraBasePrefixExpansion + "valueHasUri" + val ValueHasColor: IRI = KnoraBasePrefixExpansion + "valueHasColor" + val ValueHasGeometry: IRI = KnoraBasePrefixExpansion + "valueHasGeometry" + val ValueHasListNode: IRI = KnoraBasePrefixExpansion + "valueHasListNode" + val ValueHasIntervalStart: IRI = KnoraBasePrefixExpansion + "valueHasIntervalStart" + val ValueHasIntervalEnd: IRI = KnoraBasePrefixExpansion + "valueHasIntervalEnd" + val ValueHasTimeStamp: IRI = KnoraBasePrefixExpansion + "valueHasTimeStamp" + val ValueHasOrder: IRI = KnoraBasePrefixExpansion + "valueHasOrder" + val ValueHasRefCount: IRI = KnoraBasePrefixExpansion + "valueHasRefCount" + val ValueHasComment: IRI = KnoraBasePrefixExpansion + "valueHasComment" + val ValueHasGeonameCode: IRI = KnoraBasePrefixExpansion + "valueHasGeonameCode" + val Duration: IRI = KnoraBasePrefixExpansion + "duration" val PreviousValue: IRI = KnoraBasePrefixExpansion + "previousValue" - val ResourceProperty: IRI = KnoraBasePrefixExpansion + "resourceProperty" - val HasValue: IRI = KnoraBasePrefixExpansion + "hasValue" - val HasIncomingLinkValue: IRI = KnoraBasePrefixExpansion + "hasIncomingLinkValue" - val HasFileValue: IRI = KnoraBasePrefixExpansion + "hasFileValue" - val HasStillImageFileValue: IRI = KnoraBasePrefixExpansion + "hasStillImageFileValue" + val ResourceProperty: IRI = KnoraBasePrefixExpansion + "resourceProperty" + val HasValue: IRI = KnoraBasePrefixExpansion + "hasValue" + val HasIncomingLinkValue: IRI = KnoraBasePrefixExpansion + "hasIncomingLinkValue" + val HasFileValue: IRI = KnoraBasePrefixExpansion + "hasFileValue" + val HasStillImageFileValue: IRI = KnoraBasePrefixExpansion + "hasStillImageFileValue" val HasMovingImageFileValue: IRI = KnoraBasePrefixExpansion + "hasMovingImageFileValue" - val HasAudioFileValue: IRI = KnoraBasePrefixExpansion + "hasAudioFileValue" - val HasDDDFileValue: IRI = KnoraBasePrefixExpansion + "hasDDDFileValue" - val HasTextFileValue: IRI = KnoraBasePrefixExpansion + "hasTextFileValue" - val HasDocumentFileValue: IRI = KnoraBasePrefixExpansion + "hasDocumentFileValue" - val HasArchiveFileValue: IRI = KnoraBasePrefixExpansion + "hasArchiveFileValue" - val HasComment: IRI = KnoraBasePrefixExpansion + "hasComment" + val HasAudioFileValue: IRI = KnoraBasePrefixExpansion + "hasAudioFileValue" + val HasDDDFileValue: IRI = KnoraBasePrefixExpansion + "hasDDDFileValue" + val HasTextFileValue: IRI = KnoraBasePrefixExpansion + "hasTextFileValue" + val HasDocumentFileValue: IRI = KnoraBasePrefixExpansion + "hasDocumentFileValue" + val HasArchiveFileValue: IRI = KnoraBasePrefixExpansion + "hasArchiveFileValue" + val HasComment: IRI = KnoraBasePrefixExpansion + "hasComment" val ResourceIcon: IRI = KnoraBasePrefixExpansion + "resourceIcon" @@ -272,42 +272,42 @@ object OntologyConstants { val InternalFilename: IRI = KnoraBasePrefixExpansion + "internalFilename" val OriginalFilename: IRI = KnoraBasePrefixExpansion + "originalFilename" val OriginalMimeType: IRI = KnoraBasePrefixExpansion + "originalMimeType" - val DimX: IRI = KnoraBasePrefixExpansion + "dimX" - val DimY: IRI = KnoraBasePrefixExpansion + "dimY" - val PageCount: IRI = KnoraBasePrefixExpansion + "pageCount" - val Fps: IRI = KnoraBasePrefixExpansion + "fps" - - val ValueBase: IRI = KnoraBasePrefixExpansion + "ValueBase" - val DateBase: IRI = KnoraBasePrefixExpansion + "DateBase" - val UriBase: IRI = KnoraBasePrefixExpansion + "UriBase" - val BooleanBase: IRI = KnoraBasePrefixExpansion + "BooleanBase" - val IntBase: IRI = KnoraBasePrefixExpansion + "IntBase" - val DecimalBase: IRI = KnoraBasePrefixExpansion + "DecimalBase" + val DimX: IRI = KnoraBasePrefixExpansion + "dimX" + val DimY: IRI = KnoraBasePrefixExpansion + "dimY" + val PageCount: IRI = KnoraBasePrefixExpansion + "pageCount" + val Fps: IRI = KnoraBasePrefixExpansion + "fps" + + val ValueBase: IRI = KnoraBasePrefixExpansion + "ValueBase" + val DateBase: IRI = KnoraBasePrefixExpansion + "DateBase" + val UriBase: IRI = KnoraBasePrefixExpansion + "UriBase" + val BooleanBase: IRI = KnoraBasePrefixExpansion + "BooleanBase" + val IntBase: IRI = KnoraBasePrefixExpansion + "IntBase" + val DecimalBase: IRI = KnoraBasePrefixExpansion + "DecimalBase" val IntervalBase: IRI = KnoraBasePrefixExpansion + "IntervalBase" - val TimeBase: IRI = KnoraBasePrefixExpansion + "TimeBase" - val ColorBase: IRI = KnoraBasePrefixExpansion + "ColorBase" - - val TextValue: IRI = KnoraBasePrefixExpansion + "TextValue" - val IntValue: IRI = KnoraBasePrefixExpansion + "IntValue" - val BooleanValue: IRI = KnoraBasePrefixExpansion + "BooleanValue" - val UriValue: IRI = KnoraBasePrefixExpansion + "UriValue" - val DecimalValue: IRI = KnoraBasePrefixExpansion + "DecimalValue" - val DateValue: IRI = KnoraBasePrefixExpansion + "DateValue" - val ColorValue: IRI = KnoraBasePrefixExpansion + "ColorValue" - val GeomValue: IRI = KnoraBasePrefixExpansion + "GeomValue" - val ListValue: IRI = KnoraBasePrefixExpansion + "ListValue" - val IntervalValue: IRI = KnoraBasePrefixExpansion + "IntervalValue" - val TimeValue: IRI = KnoraBasePrefixExpansion + "TimeValue" - val LinkValue: IRI = KnoraBasePrefixExpansion + "LinkValue" - val GeonameValue: IRI = KnoraBasePrefixExpansion + "GeonameValue" - val FileValue: IRI = KnoraBasePrefixExpansion + "FileValue" - val AudioFileValue: IRI = KnoraBasePrefixExpansion + "AudioFileValue" - val DDDFileValue: IRI = KnoraBasePrefixExpansion + "DDDFileValue" - val DocumentFileValue: IRI = KnoraBasePrefixExpansion + "DocumentFileValue" - val ArchiveFileValue: IRI = KnoraBasePrefixExpansion + "ArchiveFileValue" - val StillImageFileValue: IRI = KnoraBasePrefixExpansion + "StillImageFileValue" + val TimeBase: IRI = KnoraBasePrefixExpansion + "TimeBase" + val ColorBase: IRI = KnoraBasePrefixExpansion + "ColorBase" + + val TextValue: IRI = KnoraBasePrefixExpansion + "TextValue" + val IntValue: IRI = KnoraBasePrefixExpansion + "IntValue" + val BooleanValue: IRI = KnoraBasePrefixExpansion + "BooleanValue" + val UriValue: IRI = KnoraBasePrefixExpansion + "UriValue" + val DecimalValue: IRI = KnoraBasePrefixExpansion + "DecimalValue" + val DateValue: IRI = KnoraBasePrefixExpansion + "DateValue" + val ColorValue: IRI = KnoraBasePrefixExpansion + "ColorValue" + val GeomValue: IRI = KnoraBasePrefixExpansion + "GeomValue" + val ListValue: IRI = KnoraBasePrefixExpansion + "ListValue" + val IntervalValue: IRI = KnoraBasePrefixExpansion + "IntervalValue" + val TimeValue: IRI = KnoraBasePrefixExpansion + "TimeValue" + val LinkValue: IRI = KnoraBasePrefixExpansion + "LinkValue" + val GeonameValue: IRI = KnoraBasePrefixExpansion + "GeonameValue" + val FileValue: IRI = KnoraBasePrefixExpansion + "FileValue" + val AudioFileValue: IRI = KnoraBasePrefixExpansion + "AudioFileValue" + val DDDFileValue: IRI = KnoraBasePrefixExpansion + "DDDFileValue" + val DocumentFileValue: IRI = KnoraBasePrefixExpansion + "DocumentFileValue" + val ArchiveFileValue: IRI = KnoraBasePrefixExpansion + "ArchiveFileValue" + val StillImageFileValue: IRI = KnoraBasePrefixExpansion + "StillImageFileValue" val MovingImageFileValue: IRI = KnoraBasePrefixExpansion + "MovingImageFileValue" - val TextFileValue: IRI = KnoraBasePrefixExpansion + "TextFileValue" + val TextFileValue: IRI = KnoraBasePrefixExpansion + "TextFileValue" val FileValueClasses: Set[IRI] = Set( FileValue, @@ -344,11 +344,11 @@ object OntologyConstants { TextFileValue ) - val ListNode: IRI = KnoraBasePrefixExpansion + "ListNode" - val ListNodeName: IRI = KnoraBasePrefixExpansion + "listNodeName" - val IsRootNode: IRI = KnoraBasePrefixExpansion + "isRootNode" - val HasRootNode: IRI = KnoraBasePrefixExpansion + "hasRootNode" - val HasSubListNode: IRI = KnoraBasePrefixExpansion + "hasSubListNode" + val ListNode: IRI = KnoraBasePrefixExpansion + "ListNode" + val ListNodeName: IRI = KnoraBasePrefixExpansion + "listNodeName" + val IsRootNode: IRI = KnoraBasePrefixExpansion + "isRootNode" + val HasRootNode: IRI = KnoraBasePrefixExpansion + "hasRootNode" + val HasSubListNode: IRI = KnoraBasePrefixExpansion + "hasSubListNode" val ListNodePosition: IRI = KnoraBasePrefixExpansion + "listNodePosition" val IsDeleted: IRI = KnoraBasePrefixExpansion + "isDeleted" @@ -365,14 +365,14 @@ object OntologyConstants { val HasPermissions: IRI = KnoraBasePrefixExpansion + "hasPermissions" val PermissionListDelimiter: Char = '|' - val GroupListDelimiter: Char = ',' + val GroupListDelimiter: Char = ',' val RestrictedViewPermission: String = "RV" - val ViewPermission: String = "V" - val ModifyPermission: String = "M" - val DeletePermission: String = "D" - val ChangeRightsPermission: String = "CR" - val MaxPermission: String = ChangeRightsPermission + val ViewPermission: String = "V" + val ModifyPermission: String = "M" + val DeletePermission: String = "D" + val ChangeRightsPermission: String = "CR" + val MaxPermission: String = ChangeRightsPermission val EntityPermissionAbbreviations: Seq[String] = Seq( RestrictedViewPermission, @@ -384,51 +384,51 @@ object OntologyConstants { /* Standoff */ - val StandoffTag: IRI = KnoraBasePrefixExpansion + "StandoffTag" - val StandoffTagHasStart: IRI = KnoraBasePrefixExpansion + "standoffTagHasStart" - val StandoffTagHasEnd: IRI = KnoraBasePrefixExpansion + "standoffTagHasEnd" - val StandoffTagHasStartIndex: IRI = KnoraBasePrefixExpansion + "standoffTagHasStartIndex" - val StandoffTagHasEndIndex: IRI = KnoraBasePrefixExpansion + "standoffTagHasEndIndex" - val StandoffTagHasStartParent: IRI = KnoraBasePrefixExpansion + "standoffTagHasStartParent" - val StandoffTagHasEndParent: IRI = KnoraBasePrefixExpansion + "standoffTagHasEndParent" - val StandoffTagHasUUID: IRI = KnoraBasePrefixExpansion + "standoffTagHasUUID" + val StandoffTag: IRI = KnoraBasePrefixExpansion + "StandoffTag" + val StandoffTagHasStart: IRI = KnoraBasePrefixExpansion + "standoffTagHasStart" + val StandoffTagHasEnd: IRI = KnoraBasePrefixExpansion + "standoffTagHasEnd" + val StandoffTagHasStartIndex: IRI = KnoraBasePrefixExpansion + "standoffTagHasStartIndex" + val StandoffTagHasEndIndex: IRI = KnoraBasePrefixExpansion + "standoffTagHasEndIndex" + val StandoffTagHasStartParent: IRI = KnoraBasePrefixExpansion + "standoffTagHasStartParent" + val StandoffTagHasEndParent: IRI = KnoraBasePrefixExpansion + "standoffTagHasEndParent" + val StandoffTagHasUUID: IRI = KnoraBasePrefixExpansion + "standoffTagHasUUID" val StandoffTagHasOriginalXMLID: IRI = KnoraBasePrefixExpansion + "standoffTagHasOriginalXMLID" val TargetHasOriginalXMLID: IRI = KnoraBasePrefixExpansion + "targetHasOriginalXMLID" // virtual property, used only in CONSTRUCT val StandoffTagHasInternalReference: IRI = KnoraBasePrefixExpansion + "standoffTagHasInternalReference" - val StandoffTagHasStartAncestor: IRI = KnoraBasePrefixExpansion + "standoffTagHasStartAncestor" + val StandoffTagHasStartAncestor: IRI = KnoraBasePrefixExpansion + "standoffTagHasStartAncestor" - val StandoffTagHasLink: IRI = KnoraBasePrefixExpansion + "standoffTagHasLink" - val HasStandoffLinkTo: IRI = KnoraBasePrefixExpansion + "hasStandoffLinkTo" + val StandoffTagHasLink: IRI = KnoraBasePrefixExpansion + "standoffTagHasLink" + val HasStandoffLinkTo: IRI = KnoraBasePrefixExpansion + "hasStandoffLinkTo" val HasStandoffLinkToValue: IRI = KnoraBasePrefixExpansion + "hasStandoffLinkToValue" - val StandoffDateTag: IRI = KnoraBasePrefixExpansion + "StandoffDateTag" - val StandoffColorTag: IRI = KnoraBasePrefixExpansion + "StandoffColorTag" - val StandoffIntegerTag: IRI = KnoraBasePrefixExpansion + "StandoffIntegerTag" - val StandoffDecimalTag: IRI = KnoraBasePrefixExpansion + "StandoffDecimalTag" - val StandoffIntervalTag: IRI = KnoraBasePrefixExpansion + "StandoffIntervalTag" - val StandoffTimeTag: IRI = KnoraBasePrefixExpansion + "StandoffTimeTag" - val StandoffBooleanTag: IRI = KnoraBasePrefixExpansion + "StandoffBooleanTag" - val StandoffLinkTag: IRI = KnoraBasePrefixExpansion + "StandoffLinkTag" - val StandoffUriTag: IRI = KnoraBasePrefixExpansion + "StandoffUriTag" + val StandoffDateTag: IRI = KnoraBasePrefixExpansion + "StandoffDateTag" + val StandoffColorTag: IRI = KnoraBasePrefixExpansion + "StandoffColorTag" + val StandoffIntegerTag: IRI = KnoraBasePrefixExpansion + "StandoffIntegerTag" + val StandoffDecimalTag: IRI = KnoraBasePrefixExpansion + "StandoffDecimalTag" + val StandoffIntervalTag: IRI = KnoraBasePrefixExpansion + "StandoffIntervalTag" + val StandoffTimeTag: IRI = KnoraBasePrefixExpansion + "StandoffTimeTag" + val StandoffBooleanTag: IRI = KnoraBasePrefixExpansion + "StandoffBooleanTag" + val StandoffLinkTag: IRI = KnoraBasePrefixExpansion + "StandoffLinkTag" + val StandoffUriTag: IRI = KnoraBasePrefixExpansion + "StandoffUriTag" val StandoffInternalReferenceTag: IRI = KnoraBasePrefixExpansion + "StandoffInternalReferenceTag" val StandardMapping: IRI = "http://rdfh.ch/standoff/mappings/StandardMapping" - val TEIMapping: IRI = "http://rdfh.ch/standoff/mappings/TEIMapping" + val TEIMapping: IRI = "http://rdfh.ch/standoff/mappings/TEIMapping" - val CreationDate: IRI = KnoraBasePrefixExpansion + "creationDate" + val CreationDate: IRI = KnoraBasePrefixExpansion + "creationDate" val ValueCreationDate: IRI = KnoraBasePrefixExpansion + "valueCreationDate" val LastModificationDate: IRI = KnoraBasePrefixExpansion + "lastModificationDate" - val DeleteDate: IRI = KnoraBasePrefixExpansion + "deleteDate" - val DeletedBy: IRI = KnoraBasePrefixExpansion + "deletedBy" + val DeleteDate: IRI = KnoraBasePrefixExpansion + "deleteDate" + val DeletedBy: IRI = KnoraBasePrefixExpansion + "deletedBy" val DeleteComment: IRI = KnoraBasePrefixExpansion + "deleteComment" - val HasExtResValue: IRI = OntologyConstants.KnoraBase.KnoraBasePrefixExpansion + "hasExtResValue" + val HasExtResValue: IRI = OntologyConstants.KnoraBase.KnoraBasePrefixExpansion + "hasExtResValue" val ExtResAccessInfo: IRI = OntologyConstants.KnoraBase.KnoraBasePrefixExpansion + "extResAccessInfo" - val ExtResId: IRI = OntologyConstants.KnoraBase.KnoraBasePrefixExpansion + "extResId" - val ExtResProvider: IRI = OntologyConstants.KnoraBase.KnoraBasePrefixExpansion + "extResProvider" + val ExtResId: IRI = OntologyConstants.KnoraBase.KnoraBasePrefixExpansion + "extResId" + val ExtResProvider: IRI = OntologyConstants.KnoraBase.KnoraBasePrefixExpansion + "extResProvider" val ExternalResource: IRI = OntologyConstants.KnoraBase.KnoraBasePrefixExpansion + "ExternalResource" val ExternalResValue: IRI = OntologyConstants.KnoraBase.KnoraBasePrefixExpansion + "ExternalResValue" @@ -449,53 +449,53 @@ object OntologyConstants { object KnoraAdmin { val KnoraAdminOntologyLabel: String = "knora-admin" - val KnoraAdminOntologyIri: IRI = KnoraInternal.InternalOntologyStart + "/" + KnoraAdminOntologyLabel + val KnoraAdminOntologyIri: IRI = KnoraInternal.InternalOntologyStart + "/" + KnoraAdminOntologyLabel - val KnoraAdminPrefix: String = KnoraAdminOntologyLabel + ":" + val KnoraAdminPrefix: String = KnoraAdminOntologyLabel + ":" val KnoraAdminPrefixExpansion: IRI = KnoraAdminOntologyIri + "#" /* User */ - val User: IRI = KnoraAdminPrefixExpansion + "User" - val Username: IRI = KnoraAdminPrefixExpansion + "username" - val Email: IRI = KnoraAdminPrefixExpansion + "email" - val GivenName: IRI = KnoraAdminPrefixExpansion + "givenName" - val FamilyName: IRI = KnoraAdminPrefixExpansion + "familyName" - val Password: IRI = KnoraAdminPrefixExpansion + "password" - val Address: IRI = KnoraAdminPrefixExpansion + "address" - val UsersActiveProject: IRI = KnoraAdminPrefixExpansion + "currentproject" - val Status: IRI = KnoraAdminPrefixExpansion + "status" - val PreferredLanguage: IRI = KnoraAdminPrefixExpansion + "preferredLanguage" - val IsInProject: IRI = KnoraAdminPrefixExpansion + "isInProject" + val User: IRI = KnoraAdminPrefixExpansion + "User" + val Username: IRI = KnoraAdminPrefixExpansion + "username" + val Email: IRI = KnoraAdminPrefixExpansion + "email" + val GivenName: IRI = KnoraAdminPrefixExpansion + "givenName" + val FamilyName: IRI = KnoraAdminPrefixExpansion + "familyName" + val Password: IRI = KnoraAdminPrefixExpansion + "password" + val Address: IRI = KnoraAdminPrefixExpansion + "address" + val UsersActiveProject: IRI = KnoraAdminPrefixExpansion + "currentproject" + val Status: IRI = KnoraAdminPrefixExpansion + "status" + val PreferredLanguage: IRI = KnoraAdminPrefixExpansion + "preferredLanguage" + val IsInProject: IRI = KnoraAdminPrefixExpansion + "isInProject" val IsInProjectAdminGroup: IRI = KnoraAdminPrefixExpansion + "isInProjectAdminGroup" - val IsInGroup: IRI = KnoraAdminPrefixExpansion + "isInGroup" - val IsInSystemAdminGroup: IRI = KnoraAdminPrefixExpansion + "isInSystemAdminGroup" + val IsInGroup: IRI = KnoraAdminPrefixExpansion + "isInGroup" + val IsInSystemAdminGroup: IRI = KnoraAdminPrefixExpansion + "isInSystemAdminGroup" /* Project */ - val KnoraProject: IRI = KnoraAdminPrefixExpansion + "knoraProject" - val ProjectShortname: IRI = KnoraAdminPrefixExpansion + "projectShortname" - val ProjectShortcode: IRI = KnoraAdminPrefixExpansion + "projectShortcode" - val ProjectLongname: IRI = KnoraAdminPrefixExpansion + "projectLongname" - val ProjectDescription: IRI = KnoraAdminPrefixExpansion + "projectDescription" - val ProjectKeyword: IRI = KnoraAdminPrefixExpansion + "projectKeyword" - val ProjectLogo: IRI = KnoraAdminPrefixExpansion + "projectLogo" - val ProjectRestrictedViewSize: IRI = KnoraAdminPrefixExpansion + "projectRestrictedViewSize" + val KnoraProject: IRI = KnoraAdminPrefixExpansion + "knoraProject" + val ProjectShortname: IRI = KnoraAdminPrefixExpansion + "projectShortname" + val ProjectShortcode: IRI = KnoraAdminPrefixExpansion + "projectShortcode" + val ProjectLongname: IRI = KnoraAdminPrefixExpansion + "projectLongname" + val ProjectDescription: IRI = KnoraAdminPrefixExpansion + "projectDescription" + val ProjectKeyword: IRI = KnoraAdminPrefixExpansion + "projectKeyword" + val ProjectLogo: IRI = KnoraAdminPrefixExpansion + "projectLogo" + val ProjectRestrictedViewSize: IRI = KnoraAdminPrefixExpansion + "projectRestrictedViewSize" val ProjectRestrictedViewWatermark: IRI = KnoraAdminPrefixExpansion + "projectRestrictedViewWatermark" - val BelongsToInstitution: IRI = KnoraAdminPrefixExpansion + "belongsToInstitution" - val HasSelfJoinEnabled: IRI = KnoraAdminPrefixExpansion + "hasSelfJoinEnabled" + val BelongsToInstitution: IRI = KnoraAdminPrefixExpansion + "belongsToInstitution" + val HasSelfJoinEnabled: IRI = KnoraAdminPrefixExpansion + "hasSelfJoinEnabled" /* Group */ - val UserGroup: IRI = KnoraAdminPrefixExpansion + "UserGroup" - val GroupName: IRI = KnoraAdminPrefixExpansion + "groupName" + val UserGroup: IRI = KnoraAdminPrefixExpansion + "UserGroup" + val GroupName: IRI = KnoraAdminPrefixExpansion + "groupName" val GroupDescriptions: IRI = KnoraAdminPrefixExpansion + "groupDescriptions" - val BelongsToProject: IRI = KnoraAdminPrefixExpansion + "belongsToProject" + val BelongsToProject: IRI = KnoraAdminPrefixExpansion + "belongsToProject" /* Built-In Groups */ - val UnknownUser: IRI = KnoraAdminPrefixExpansion + "UnknownUser" - val KnownUser: IRI = KnoraAdminPrefixExpansion + "KnownUser" + val UnknownUser: IRI = KnoraAdminPrefixExpansion + "UnknownUser" + val KnownUser: IRI = KnoraAdminPrefixExpansion + "KnownUser" val ProjectMember: IRI = KnoraAdminPrefixExpansion + "ProjectMember" - val Creator: IRI = KnoraAdminPrefixExpansion + "Creator" - val SystemAdmin: IRI = KnoraAdminPrefixExpansion + "SystemAdmin" - val ProjectAdmin: IRI = KnoraAdminPrefixExpansion + "ProjectAdmin" + val Creator: IRI = KnoraAdminPrefixExpansion + "Creator" + val SystemAdmin: IRI = KnoraAdminPrefixExpansion + "SystemAdmin" + val ProjectAdmin: IRI = KnoraAdminPrefixExpansion + "ProjectAdmin" val BuiltInGroups: Set[IRI] = Set( UnknownUser, @@ -507,27 +507,27 @@ object OntologyConstants { ) /* Institution */ - val Institution: IRI = KnoraAdminPrefixExpansion + "Institution" + val Institution: IRI = KnoraAdminPrefixExpansion + "Institution" val InstitutionDescription: IRI = KnoraAdminPrefixExpansion + "institutionDescription" - val InstitutionName: IRI = KnoraAdminPrefixExpansion + "institutionName" - val InstitutionWebsite: IRI = KnoraAdminPrefixExpansion + "institutionWebsite" - val Phone: IRI = KnoraAdminPrefixExpansion + "phone" + val InstitutionName: IRI = KnoraAdminPrefixExpansion + "institutionName" + val InstitutionWebsite: IRI = KnoraAdminPrefixExpansion + "institutionWebsite" + val Phone: IRI = KnoraAdminPrefixExpansion + "phone" /* Permissions */ - val Permission: IRI = KnoraAdminPrefixExpansion + "Permission" - val AdministrativePermission: IRI = KnoraAdminPrefixExpansion + "AdministrativePermission" + val Permission: IRI = KnoraAdminPrefixExpansion + "Permission" + val AdministrativePermission: IRI = KnoraAdminPrefixExpansion + "AdministrativePermission" val DefaultObjectAccessPermission: IRI = KnoraAdminPrefixExpansion + "DefaultObjectAccessPermission" - val ForProject: IRI = KnoraAdminPrefixExpansion + "forProject" - val ForGroup: IRI = KnoraAdminPrefixExpansion + "forGroup" - val ForResourceClass: IRI = KnoraAdminPrefixExpansion + "forResourceClass" - val ForProperty: IRI = KnoraAdminPrefixExpansion + "forProperty" + val ForProject: IRI = KnoraAdminPrefixExpansion + "forProject" + val ForGroup: IRI = KnoraAdminPrefixExpansion + "forGroup" + val ForResourceClass: IRI = KnoraAdminPrefixExpansion + "forResourceClass" + val ForProperty: IRI = KnoraAdminPrefixExpansion + "forProperty" - val ProjectResourceCreateAllPermission: String = "ProjectResourceCreateAllPermission" + val ProjectResourceCreateAllPermission: String = "ProjectResourceCreateAllPermission" val ProjectResourceCreateRestrictedPermission: String = "ProjectResourceCreateRestrictedPermission" - val ProjectAdminAllPermission: String = "ProjectAdminAllPermission" - val ProjectAdminGroupAllPermission: String = "ProjectAdminGroupAllPermission" - val ProjectAdminGroupRestrictedPermission: String = "ProjectAdminGroupRestrictedPermission" - val ProjectAdminRightsAllPermission: String = "ProjectAdminRightsAllPermission" + val ProjectAdminAllPermission: String = "ProjectAdminAllPermission" + val ProjectAdminGroupAllPermission: String = "ProjectAdminGroupAllPermission" + val ProjectAdminGroupRestrictedPermission: String = "ProjectAdminGroupRestrictedPermission" + val ProjectAdminRightsAllPermission: String = "ProjectAdminRightsAllPermission" val AdministrativePermissionAbbreviations: Seq[String] = Seq( ProjectResourceCreateAllPermission, @@ -539,10 +539,10 @@ object OntologyConstants { ) val HasDefaultRestrictedViewPermission: IRI = KnoraAdminPrefixExpansion + "hasDefaultRestrictedViewPermission" - val HasDefaultViewPermission: IRI = KnoraAdminPrefixExpansion + "hasDefaultViewPermission" - val HasDefaultModifyPermission: IRI = KnoraAdminPrefixExpansion + "hasDefaultModifyPermission" - val HasDefaultDeletePermission: IRI = KnoraAdminPrefixExpansion + "hasDefaultDeletePermission" - val HasDefaultChangeRightsPermission: IRI = KnoraAdminPrefixExpansion + "hasDefaultChangeRightsPermission" + val HasDefaultViewPermission: IRI = KnoraAdminPrefixExpansion + "hasDefaultViewPermission" + val HasDefaultModifyPermission: IRI = KnoraAdminPrefixExpansion + "hasDefaultModifyPermission" + val HasDefaultDeletePermission: IRI = KnoraAdminPrefixExpansion + "hasDefaultDeletePermission" + val HasDefaultChangeRightsPermission: IRI = KnoraAdminPrefixExpansion + "hasDefaultChangeRightsPermission" val DefaultPermissionProperties: Set[IRI] = Set( HasDefaultRestrictedViewPermission, @@ -552,7 +552,7 @@ object OntologyConstants { HasDefaultChangeRightsPermission ) - val SystemProject: IRI = KnoraAdminPrefixExpansion + "SystemProject" + val SystemProject: IRI = KnoraAdminPrefixExpansion + "SystemProject" val DefaultSharedOntologiesProject: IRI = KnoraAdminPrefixExpansion + "DefaultSharedOntologiesProject" /** @@ -569,14 +569,14 @@ object OntologyConstants { object Standoff { val StandoffOntologyLabel: String = "standoff" - val StandoffOntologyIri: IRI = KnoraInternal.InternalOntologyStart + "/" + StandoffOntologyLabel - val StandoffPrefixExpansion: IRI = StandoffOntologyIri + "#" - - val StandoffRootTag: IRI = StandoffPrefixExpansion + "StandoffRootTag" - val StandoffParagraphTag: IRI = StandoffPrefixExpansion + "StandoffParagraphTag" - val StandoffItalicTag: IRI = StandoffPrefixExpansion + "StandoffItalicTag" - val StandoffBoldTag: IRI = StandoffPrefixExpansion + "StandoffBoldTag" - val StandoffUnderlineTag: IRI = StandoffPrefixExpansion + "StandoffUnderlineTag" + val StandoffOntologyIri: IRI = KnoraInternal.InternalOntologyStart + "/" + StandoffOntologyLabel + val StandoffPrefixExpansion: IRI = StandoffOntologyIri + "#" + + val StandoffRootTag: IRI = StandoffPrefixExpansion + "StandoffRootTag" + val StandoffParagraphTag: IRI = StandoffPrefixExpansion + "StandoffParagraphTag" + val StandoffItalicTag: IRI = StandoffPrefixExpansion + "StandoffItalicTag" + val StandoffBoldTag: IRI = StandoffPrefixExpansion + "StandoffBoldTag" + val StandoffUnderlineTag: IRI = StandoffPrefixExpansion + "StandoffUnderlineTag" val StandoffStrikethroughTag: IRI = StandoffPrefixExpansion + "StandoffStrikethroughTag" val StandoffHeader1Tag: IRI = StandoffPrefixExpansion + "StandoffHeader1Tag" @@ -586,49 +586,49 @@ object OntologyConstants { val StandoffHeader5Tag: IRI = StandoffPrefixExpansion + "StandoffHeader5Tag" val StandoffHeader6Tag: IRI = StandoffPrefixExpansion + "StandoffHeader6Tag" - val StandoffSuperscriptTag: IRI = StandoffPrefixExpansion + "StandoffSuperscriptTag" - val StandoffSubscriptTag: IRI = StandoffPrefixExpansion + "StandoffSubscriptTag" - val StandoffOrderedListTag: IRI = StandoffPrefixExpansion + "StandoffOrderedListTag" + val StandoffSuperscriptTag: IRI = StandoffPrefixExpansion + "StandoffSuperscriptTag" + val StandoffSubscriptTag: IRI = StandoffPrefixExpansion + "StandoffSubscriptTag" + val StandoffOrderedListTag: IRI = StandoffPrefixExpansion + "StandoffOrderedListTag" val StandoffUnorderedListTag: IRI = StandoffPrefixExpansion + "StandoffUnorderedListTag" - val StandoffListElementTag: IRI = StandoffPrefixExpansion + "StandoffListElementTag" - val StandoffStyleElementTag: IRI = StandoffPrefixExpansion + "StandoffStyleTag" + val StandoffListElementTag: IRI = StandoffPrefixExpansion + "StandoffListElementTag" + val StandoffStyleElementTag: IRI = StandoffPrefixExpansion + "StandoffStyleTag" } object SalsahGui { val SalsahGuiOntologyLabel: String = "salsah-gui" - val SalsahGuiOntologyIri: IRI = KnoraInternal.InternalOntologyStart + "/" + SalsahGuiOntologyLabel - val SalsahGuiPrefixExpansion: IRI = SalsahGuiOntologyIri + "#" + val SalsahGuiOntologyIri: IRI = KnoraInternal.InternalOntologyStart + "/" + SalsahGuiOntologyLabel + val SalsahGuiPrefixExpansion: IRI = SalsahGuiOntologyIri + "#" - val GuiAttribute: IRI = SalsahGuiPrefixExpansion + "guiAttribute" + val GuiAttribute: IRI = SalsahGuiPrefixExpansion + "guiAttribute" val GuiAttributeDefinition: IRI = SalsahGuiPrefixExpansion + "guiAttributeDefinition" - val GuiOrder: IRI = SalsahGuiPrefixExpansion + "guiOrder" - val GuiElementProp: IRI = SalsahGuiPrefixExpansion + "guiElement" - val GuiElementClass: IRI = SalsahGuiPrefixExpansion + "Guielement" - val SimpleText: IRI = SalsahGuiPrefixExpansion + "SimpleText" - val Textarea: IRI = SalsahGuiPrefixExpansion + "Textarea" - val Pulldown: IRI = SalsahGuiPrefixExpansion + "Pulldown" - val Slider: IRI = SalsahGuiPrefixExpansion + "Slider" - val Spinbox: IRI = SalsahGuiPrefixExpansion + "Spinbox" - val Searchbox: IRI = SalsahGuiPrefixExpansion + "Searchbox" - val Date: IRI = SalsahGuiPrefixExpansion + "Date" - val Geometry: IRI = SalsahGuiPrefixExpansion + "Geometry" - val Colorpicker: IRI = SalsahGuiPrefixExpansion + "Colorpicker" - val List: IRI = SalsahGuiPrefixExpansion + "List" - val Radio: IRI = SalsahGuiPrefixExpansion + "Radio" - val Checkbox: IRI = SalsahGuiPrefixExpansion + "Checkbox" - val Richtext: IRI = SalsahGuiPrefixExpansion + "Richtext" - val Interval: IRI = SalsahGuiPrefixExpansion + "Interval" - val TimeStamp: IRI = SalsahGuiPrefixExpansion + "TimeStamp" - val Geonames: IRI = SalsahGuiPrefixExpansion + "Geonames" - val Fileupload: IRI = SalsahGuiPrefixExpansion + "Fileupload" + val GuiOrder: IRI = SalsahGuiPrefixExpansion + "guiOrder" + val GuiElementProp: IRI = SalsahGuiPrefixExpansion + "guiElement" + val GuiElementClass: IRI = SalsahGuiPrefixExpansion + "Guielement" + val SimpleText: IRI = SalsahGuiPrefixExpansion + "SimpleText" + val Textarea: IRI = SalsahGuiPrefixExpansion + "Textarea" + val Pulldown: IRI = SalsahGuiPrefixExpansion + "Pulldown" + val Slider: IRI = SalsahGuiPrefixExpansion + "Slider" + val Spinbox: IRI = SalsahGuiPrefixExpansion + "Spinbox" + val Searchbox: IRI = SalsahGuiPrefixExpansion + "Searchbox" + val Date: IRI = SalsahGuiPrefixExpansion + "Date" + val Geometry: IRI = SalsahGuiPrefixExpansion + "Geometry" + val Colorpicker: IRI = SalsahGuiPrefixExpansion + "Colorpicker" + val List: IRI = SalsahGuiPrefixExpansion + "List" + val Radio: IRI = SalsahGuiPrefixExpansion + "Radio" + val Checkbox: IRI = SalsahGuiPrefixExpansion + "Checkbox" + val Richtext: IRI = SalsahGuiPrefixExpansion + "Richtext" + val Interval: IRI = SalsahGuiPrefixExpansion + "Interval" + val TimeStamp: IRI = SalsahGuiPrefixExpansion + "TimeStamp" + val Geonames: IRI = SalsahGuiPrefixExpansion + "Geonames" + val Fileupload: IRI = SalsahGuiPrefixExpansion + "Fileupload" object SalsahGuiAttributeType extends Enumeration { val Integer: Value = Value(0, "integer") val Percent: Value = Value(1, "percent") val Decimal: Value = Value(2, "decimal") - val Str: Value = Value(3, "string") - val Iri: Value = Value(4, "iri") + val Str: Value = Value(3, "string") + val Iri: Value = Value(4, "iri") val valueMap: Map[String, Value] = values.map(v => (v.toString, v)).toMap @@ -655,11 +655,11 @@ object OntologyConstants { object ProjectSpecificXmlImportNamespace { val XmlImportNamespaceStart: String = KnoraApi.ApiOntologyStart - val XmlImportNamespaceEnd: String = "/xml-import/v1#" + val XmlImportNamespaceEnd: String = "/xml-import/v1#" } val KnoraXmlImportNamespacePrefixLabel: String = "knoraXmlImport" - val KnoraXmlImportNamespaceV1: IRI = KnoraApi.ApiOntologyStart + KnoraXmlImportNamespacePrefixLabel + "/v1#" + val KnoraXmlImportNamespaceV1: IRI = KnoraApi.ApiOntologyStart + KnoraXmlImportNamespacePrefixLabel + "/v1#" val Resources: IRI = KnoraXmlImportNamespaceV1 + "resources" } @@ -722,84 +722,84 @@ object OntologyConstants { val VersionSegment = "/v2" - val KnoraApiOntologyIri: IRI = KnoraApi.ApiOntologyStart + KnoraApi.KnoraApiOntologyLabel + VersionSegment + val KnoraApiOntologyIri: IRI = KnoraApi.ApiOntologyStart + KnoraApi.KnoraApiOntologyLabel + VersionSegment val KnoraApiV2PrefixExpansion: IRI = KnoraApiOntologyIri + "#" - val Result: IRI = KnoraApiV2PrefixExpansion + "result" - val Error: IRI = KnoraApiV2PrefixExpansion + "error" - val CanDo: IRI = KnoraApiV2PrefixExpansion + "canDo" + val Result: IRI = KnoraApiV2PrefixExpansion + "result" + val Error: IRI = KnoraApiV2PrefixExpansion + "error" + val CanDo: IRI = KnoraApiV2PrefixExpansion + "canDo" val MayHaveMoreResults: IRI = KnoraApiV2PrefixExpansion + "mayHaveMoreResults" - val EventType: IRI = KnoraApiV2PrefixExpansion + "eventType" - val EventBody: IRI = KnoraApiV2PrefixExpansion + "eventBody" - val ResourceClassIri: IRI = KnoraApiV2PrefixExpansion + "resourceClassIri" - val ResourceIri: IRI = KnoraApiV2PrefixExpansion + "resourceIri" + val EventType: IRI = KnoraApiV2PrefixExpansion + "eventType" + val EventBody: IRI = KnoraApiV2PrefixExpansion + "eventBody" + val ResourceClassIri: IRI = KnoraApiV2PrefixExpansion + "resourceClassIri" + val ResourceIri: IRI = KnoraApiV2PrefixExpansion + "resourceIri" - val IsShared: IRI = KnoraApiV2PrefixExpansion + "isShared" + val IsShared: IRI = KnoraApiV2PrefixExpansion + "isShared" val IsBuiltIn: IRI = KnoraApiV2PrefixExpansion + "isBuiltIn" val SubjectType: IRI = KnoraApiV2PrefixExpansion + "subjectType" - val ObjectType: IRI = KnoraApiV2PrefixExpansion + "objectType" + val ObjectType: IRI = KnoraApiV2PrefixExpansion + "objectType" val KnoraProject: IRI = KnoraApiV2PrefixExpansion + "knoraProject" - val IsEditable: IRI = KnoraApiV2PrefixExpansion + "isEditable" - val IsLinkProperty: IRI = KnoraApiV2PrefixExpansion + "isLinkProperty" + val IsEditable: IRI = KnoraApiV2PrefixExpansion + "isEditable" + val IsLinkProperty: IRI = KnoraApiV2PrefixExpansion + "isLinkProperty" val IsLinkValueProperty: IRI = KnoraApiV2PrefixExpansion + "isLinkValueProperty" - val IsResourceClass: IRI = KnoraApiV2PrefixExpansion + "isResourceClass" - val IsResourceProperty: IRI = KnoraApiV2PrefixExpansion + "isResourceProperty" - val IsStandoffClass: IRI = KnoraApiV2PrefixExpansion + "isStandoffClass" - val CanBeInstantiated: IRI = KnoraApiV2PrefixExpansion + "canBeInstantiated" - val IsValueClass: IRI = KnoraApiV2PrefixExpansion + "isValueClass" - val IsInherited: IRI = KnoraApiV2PrefixExpansion + "isInherited" - val OntologyName: IRI = KnoraApiV2PrefixExpansion + "ontologyName" - - val ValueAsString: IRI = KnoraApiV2PrefixExpansion + "valueAsString" - val ValueCreationDate: IRI = KnoraApiV2PrefixExpansion + "valueCreationDate" - val ValueHasUUID: IRI = KnoraApiV2PrefixExpansion + "valueHasUUID" - val ValueHasComment: IRI = KnoraApiV2PrefixExpansion + "valueHasComment" + val IsResourceClass: IRI = KnoraApiV2PrefixExpansion + "isResourceClass" + val IsResourceProperty: IRI = KnoraApiV2PrefixExpansion + "isResourceProperty" + val IsStandoffClass: IRI = KnoraApiV2PrefixExpansion + "isStandoffClass" + val CanBeInstantiated: IRI = KnoraApiV2PrefixExpansion + "canBeInstantiated" + val IsValueClass: IRI = KnoraApiV2PrefixExpansion + "isValueClass" + val IsInherited: IRI = KnoraApiV2PrefixExpansion + "isInherited" + val OntologyName: IRI = KnoraApiV2PrefixExpansion + "ontologyName" + + val ValueAsString: IRI = KnoraApiV2PrefixExpansion + "valueAsString" + val ValueCreationDate: IRI = KnoraApiV2PrefixExpansion + "valueCreationDate" + val ValueHasUUID: IRI = KnoraApiV2PrefixExpansion + "valueHasUUID" + val ValueHasComment: IRI = KnoraApiV2PrefixExpansion + "valueHasComment" val NewValueVersionIri: IRI = KnoraApiV2PrefixExpansion + "newValueVersionIri" - val User: IRI = KnoraApiV2PrefixExpansion + "User" - val AttachedToUser: IRI = KnoraApiV2PrefixExpansion + "attachedToUser" - val AttachedToProject: IRI = KnoraApiV2PrefixExpansion + "attachedToProject" - val HasStandoffLinkTo: IRI = KnoraApiV2PrefixExpansion + "hasStandoffLinkTo" + val User: IRI = KnoraApiV2PrefixExpansion + "User" + val AttachedToUser: IRI = KnoraApiV2PrefixExpansion + "attachedToUser" + val AttachedToProject: IRI = KnoraApiV2PrefixExpansion + "attachedToProject" + val HasStandoffLinkTo: IRI = KnoraApiV2PrefixExpansion + "hasStandoffLinkTo" val HasStandoffLinkToValue: IRI = KnoraApiV2PrefixExpansion + "hasStandoffLinkToValue" - val HasPermissions: IRI = KnoraApiV2PrefixExpansion + "hasPermissions" - val UserHasPermission: String = KnoraApiV2PrefixExpansion + "userHasPermission" - val CreationDate: IRI = KnoraApiV2PrefixExpansion + "creationDate" - val LastModificationDate: IRI = KnoraApiV2PrefixExpansion + "lastModificationDate" - val VersionDate: IRI = KnoraApiV2PrefixExpansion + "versionDate" - val NewModificationDate: IRI = KnoraApiV2PrefixExpansion + "newModificationDate" - val IsDeleted: IRI = KnoraApiV2PrefixExpansion + "isDeleted" - val DeleteDate: IRI = KnoraApiV2PrefixExpansion + "deleteDate" - val DeleteComment: IRI = KnoraApiV2PrefixExpansion + "deleteComment" - val ArkUrl: IRI = KnoraApiV2PrefixExpansion + "arkUrl" - val VersionArkUrl: IRI = KnoraApiV2PrefixExpansion + "versionArkUrl" - val Author: IRI = KnoraApiV2PrefixExpansion + "author" - - val Resource: IRI = KnoraApiV2PrefixExpansion + "Resource" - val DeletedResource: IRI = KnoraApiV2PrefixExpansion + "DeletedResource" - val Region: IRI = KnoraApiV2PrefixExpansion + "Region" - val Representation: IRI = KnoraApiV2PrefixExpansion + "Representation" - val StillImageRepresentation: IRI = KnoraApiV2PrefixExpansion + "StillImageRepresentation" + val HasPermissions: IRI = KnoraApiV2PrefixExpansion + "hasPermissions" + val UserHasPermission: String = KnoraApiV2PrefixExpansion + "userHasPermission" + val CreationDate: IRI = KnoraApiV2PrefixExpansion + "creationDate" + val LastModificationDate: IRI = KnoraApiV2PrefixExpansion + "lastModificationDate" + val VersionDate: IRI = KnoraApiV2PrefixExpansion + "versionDate" + val NewModificationDate: IRI = KnoraApiV2PrefixExpansion + "newModificationDate" + val IsDeleted: IRI = KnoraApiV2PrefixExpansion + "isDeleted" + val DeleteDate: IRI = KnoraApiV2PrefixExpansion + "deleteDate" + val DeleteComment: IRI = KnoraApiV2PrefixExpansion + "deleteComment" + val ArkUrl: IRI = KnoraApiV2PrefixExpansion + "arkUrl" + val VersionArkUrl: IRI = KnoraApiV2PrefixExpansion + "versionArkUrl" + val Author: IRI = KnoraApiV2PrefixExpansion + "author" + + val Resource: IRI = KnoraApiV2PrefixExpansion + "Resource" + val DeletedResource: IRI = KnoraApiV2PrefixExpansion + "DeletedResource" + val Region: IRI = KnoraApiV2PrefixExpansion + "Region" + val Representation: IRI = KnoraApiV2PrefixExpansion + "Representation" + val StillImageRepresentation: IRI = KnoraApiV2PrefixExpansion + "StillImageRepresentation" val MovingImageRepresentation: IRI = KnoraApiV2PrefixExpansion + "MovingImageRepresentation" - val AudioRepresentation: IRI = KnoraApiV2PrefixExpansion + "AudioRepresentation" - val DDDRepresentation: IRI = KnoraApiV2PrefixExpansion + "DDDRepresentation" - val TextRepresentation: IRI = KnoraApiV2PrefixExpansion + "TextRepresentation" - val DocumentRepresentation: IRI = KnoraApiV2PrefixExpansion + "DocumentRepresentation" - val ArchiveRepresentation: IRI = KnoraApiV2PrefixExpansion + "ArchiveRepresentation" - val XMLToStandoffMapping: IRI = KnoraApiV2PrefixExpansion + "XMLToStandoffMapping" - val ListNode: IRI = KnoraApiV2PrefixExpansion + "ListNode" - val LinkObj: IRI = KnoraApiV2PrefixExpansion + "LinkObj" - - val IntBase: IRI = KnoraApiV2PrefixExpansion + "IntBase" - val BooleanBase: IRI = KnoraApiV2PrefixExpansion + "BooleanBase" - val UriBase: IRI = KnoraApiV2PrefixExpansion + "UriBase" + val AudioRepresentation: IRI = KnoraApiV2PrefixExpansion + "AudioRepresentation" + val DDDRepresentation: IRI = KnoraApiV2PrefixExpansion + "DDDRepresentation" + val TextRepresentation: IRI = KnoraApiV2PrefixExpansion + "TextRepresentation" + val DocumentRepresentation: IRI = KnoraApiV2PrefixExpansion + "DocumentRepresentation" + val ArchiveRepresentation: IRI = KnoraApiV2PrefixExpansion + "ArchiveRepresentation" + val XMLToStandoffMapping: IRI = KnoraApiV2PrefixExpansion + "XMLToStandoffMapping" + val ListNode: IRI = KnoraApiV2PrefixExpansion + "ListNode" + val LinkObj: IRI = KnoraApiV2PrefixExpansion + "LinkObj" + + val IntBase: IRI = KnoraApiV2PrefixExpansion + "IntBase" + val BooleanBase: IRI = KnoraApiV2PrefixExpansion + "BooleanBase" + val UriBase: IRI = KnoraApiV2PrefixExpansion + "UriBase" val IntervalBase: IRI = KnoraApiV2PrefixExpansion + "IntervalBase" - val ColorBase: IRI = KnoraApiV2PrefixExpansion + "ColorBase" - val DateBase: IRI = KnoraApiV2PrefixExpansion + "DateBase" - val TimeBase: IRI = KnoraApiV2PrefixExpansion + "TimeBase" - val DecimalBase: IRI = KnoraApiV2PrefixExpansion + "DecimalBase" + val ColorBase: IRI = KnoraApiV2PrefixExpansion + "ColorBase" + val DateBase: IRI = KnoraApiV2PrefixExpansion + "DateBase" + val TimeBase: IRI = KnoraApiV2PrefixExpansion + "TimeBase" + val DecimalBase: IRI = KnoraApiV2PrefixExpansion + "DecimalBase" val ValueBaseClasses: Set[IRI] = Set( IntBase, @@ -812,29 +812,29 @@ object OntologyConstants { DecimalBase ) - val Value: IRI = KnoraApiV2PrefixExpansion + "Value" - val TextValue: IRI = KnoraApiV2PrefixExpansion + "TextValue" - val IntValue: IRI = KnoraApiV2PrefixExpansion + "IntValue" - val DecimalValue: IRI = KnoraApiV2PrefixExpansion + "DecimalValue" - val BooleanValue: IRI = KnoraApiV2PrefixExpansion + "BooleanValue" - val DateValue: IRI = KnoraApiV2PrefixExpansion + "DateValue" - val GeomValue: IRI = KnoraApiV2PrefixExpansion + "GeomValue" + val Value: IRI = KnoraApiV2PrefixExpansion + "Value" + val TextValue: IRI = KnoraApiV2PrefixExpansion + "TextValue" + val IntValue: IRI = KnoraApiV2PrefixExpansion + "IntValue" + val DecimalValue: IRI = KnoraApiV2PrefixExpansion + "DecimalValue" + val BooleanValue: IRI = KnoraApiV2PrefixExpansion + "BooleanValue" + val DateValue: IRI = KnoraApiV2PrefixExpansion + "DateValue" + val GeomValue: IRI = KnoraApiV2PrefixExpansion + "GeomValue" val IntervalValue: IRI = KnoraApiV2PrefixExpansion + "IntervalValue" - val TimeValue: IRI = KnoraApiV2PrefixExpansion + "TimeValue" - val LinkValue: IRI = KnoraApiV2PrefixExpansion + "LinkValue" - val ListValue: IRI = KnoraApiV2PrefixExpansion + "ListValue" - val UriValue: IRI = KnoraApiV2PrefixExpansion + "UriValue" - val GeonameValue: IRI = KnoraApiV2PrefixExpansion + "GeonameValue" - val FileValue: IRI = KnoraApiV2PrefixExpansion + "FileValue" - val ColorValue: IRI = KnoraApiV2PrefixExpansion + "ColorValue" - - val StillImageFileValue: IRI = KnoraApiV2PrefixExpansion + "StillImageFileValue" + val TimeValue: IRI = KnoraApiV2PrefixExpansion + "TimeValue" + val LinkValue: IRI = KnoraApiV2PrefixExpansion + "LinkValue" + val ListValue: IRI = KnoraApiV2PrefixExpansion + "ListValue" + val UriValue: IRI = KnoraApiV2PrefixExpansion + "UriValue" + val GeonameValue: IRI = KnoraApiV2PrefixExpansion + "GeonameValue" + val FileValue: IRI = KnoraApiV2PrefixExpansion + "FileValue" + val ColorValue: IRI = KnoraApiV2PrefixExpansion + "ColorValue" + + val StillImageFileValue: IRI = KnoraApiV2PrefixExpansion + "StillImageFileValue" val MovingImageFileValue: IRI = KnoraApiV2PrefixExpansion + "MovingImageFileValue" - val AudioFileValue: IRI = KnoraApiV2PrefixExpansion + "AudioFileValue" - val DDDFileValue: IRI = KnoraApiV2PrefixExpansion + "DDDFileValue" - val TextFileValue: IRI = KnoraApiV2PrefixExpansion + "TextFileValue" - val DocumentFileValue: IRI = KnoraApiV2PrefixExpansion + "DocumentFileValue" - val ArchiveFileValue: IRI = KnoraApiV2PrefixExpansion + "ArchiveFileValue" + val AudioFileValue: IRI = KnoraApiV2PrefixExpansion + "AudioFileValue" + val DDDFileValue: IRI = KnoraApiV2PrefixExpansion + "DDDFileValue" + val TextFileValue: IRI = KnoraApiV2PrefixExpansion + "TextFileValue" + val DocumentFileValue: IRI = KnoraApiV2PrefixExpansion + "DocumentFileValue" + val ArchiveFileValue: IRI = KnoraApiV2PrefixExpansion + "ArchiveFileValue" val HasRepresentationValue: IRI = KnoraApiV2PrefixExpansion + "hasRepresentationValue" @@ -865,58 +865,58 @@ object OntologyConstants { ColorValue ) ++ FileValueClasses - val ResourceProperty: IRI = KnoraApiV2PrefixExpansion + "resourceProperty" - val HasValue: IRI = KnoraApiV2PrefixExpansion + "hasValue" - val ValueHas: IRI = KnoraApiV2PrefixExpansion + "valueHas" - val HasLinkTo: IRI = KnoraApiV2PrefixExpansion + "hasLinkTo" - val HasLinkToValue: IRI = KnoraApiV2PrefixExpansion + "hasLinkToValue" + val ResourceProperty: IRI = KnoraApiV2PrefixExpansion + "resourceProperty" + val HasValue: IRI = KnoraApiV2PrefixExpansion + "hasValue" + val ValueHas: IRI = KnoraApiV2PrefixExpansion + "valueHas" + val HasLinkTo: IRI = KnoraApiV2PrefixExpansion + "hasLinkTo" + val HasLinkToValue: IRI = KnoraApiV2PrefixExpansion + "hasLinkToValue" val HasIncomingLinkValue: IRI = KnoraApiV2PrefixExpansion + "hasIncomingLinkValue" - val IsPartOf: IRI = KnoraApiV2PrefixExpansion + "isPartOf" - val IsPartOfValue: IRI = KnoraApiV2PrefixExpansion + "isPartOfValue" - val IsRegionOf: IRI = KnoraApiV2PrefixExpansion + "isRegionOf" - val IsRegionOfValue: IRI = KnoraApiV2PrefixExpansion + "isRegionOfValue" - val HasGeometry: IRI = KnoraApiV2PrefixExpansion + "hasGeometry" - val HasColor: IRI = KnoraApiV2PrefixExpansion + "hasColor" - val HasComment: IRI = KnoraApiV2PrefixExpansion + "hasComment" - val HasFileValue: IRI = KnoraApiV2PrefixExpansion + "hasFileValue" - val HasStillImageFileValue: IRI = KnoraApiV2PrefixExpansion + "hasStillImageFileValue" + val IsPartOf: IRI = KnoraApiV2PrefixExpansion + "isPartOf" + val IsPartOfValue: IRI = KnoraApiV2PrefixExpansion + "isPartOfValue" + val IsRegionOf: IRI = KnoraApiV2PrefixExpansion + "isRegionOf" + val IsRegionOfValue: IRI = KnoraApiV2PrefixExpansion + "isRegionOfValue" + val HasGeometry: IRI = KnoraApiV2PrefixExpansion + "hasGeometry" + val HasColor: IRI = KnoraApiV2PrefixExpansion + "hasColor" + val HasComment: IRI = KnoraApiV2PrefixExpansion + "hasComment" + val HasFileValue: IRI = KnoraApiV2PrefixExpansion + "hasFileValue" + val HasStillImageFileValue: IRI = KnoraApiV2PrefixExpansion + "hasStillImageFileValue" val HasMovingImageFileValue: IRI = KnoraApiV2PrefixExpansion + "hasMovingImageFileValue" - val HasAudioFileValue: IRI = KnoraApiV2PrefixExpansion + "hasAudioFileValue" - val HasDDDFileValue: IRI = KnoraApiV2PrefixExpansion + "hasDDDFileValue" - val HasTextFileValue: IRI = KnoraApiV2PrefixExpansion + "hasTextFileValue" - val HasDocumentFileValue: IRI = KnoraApiV2PrefixExpansion + "hasDocumentFileValue" - val HasArchiveFileValue: IRI = KnoraApiV2PrefixExpansion + "hasArchiveFileValue" - - val DateValueHasStartYear: IRI = KnoraApiV2PrefixExpansion + "dateValueHasStartYear" - val DateValueHasEndYear: IRI = KnoraApiV2PrefixExpansion + "dateValueHasEndYear" + val HasAudioFileValue: IRI = KnoraApiV2PrefixExpansion + "hasAudioFileValue" + val HasDDDFileValue: IRI = KnoraApiV2PrefixExpansion + "hasDDDFileValue" + val HasTextFileValue: IRI = KnoraApiV2PrefixExpansion + "hasTextFileValue" + val HasDocumentFileValue: IRI = KnoraApiV2PrefixExpansion + "hasDocumentFileValue" + val HasArchiveFileValue: IRI = KnoraApiV2PrefixExpansion + "hasArchiveFileValue" + + val DateValueHasStartYear: IRI = KnoraApiV2PrefixExpansion + "dateValueHasStartYear" + val DateValueHasEndYear: IRI = KnoraApiV2PrefixExpansion + "dateValueHasEndYear" val DateValueHasStartMonth: IRI = KnoraApiV2PrefixExpansion + "dateValueHasStartMonth" - val DateValueHasEndMonth: IRI = KnoraApiV2PrefixExpansion + "dateValueHasEndMonth" - val DateValueHasStartDay: IRI = KnoraApiV2PrefixExpansion + "dateValueHasStartDay" - val DateValueHasEndDay: IRI = KnoraApiV2PrefixExpansion + "dateValueHasEndDay" - val DateValueHasStartEra: IRI = KnoraApiV2PrefixExpansion + "dateValueHasStartEra" - val DateValueHasEndEra: IRI = KnoraApiV2PrefixExpansion + "dateValueHasEndEra" - val DateValueHasCalendar: IRI = KnoraApiV2PrefixExpansion + "dateValueHasCalendar" - - val TextValueHasStandoff: IRI = KnoraApiV2PrefixExpansion + "textValueHasStandoff" - val TextValueHasMarkup: IRI = KnoraApiV2PrefixExpansion + "textValueHasMarkup" + val DateValueHasEndMonth: IRI = KnoraApiV2PrefixExpansion + "dateValueHasEndMonth" + val DateValueHasStartDay: IRI = KnoraApiV2PrefixExpansion + "dateValueHasStartDay" + val DateValueHasEndDay: IRI = KnoraApiV2PrefixExpansion + "dateValueHasEndDay" + val DateValueHasStartEra: IRI = KnoraApiV2PrefixExpansion + "dateValueHasStartEra" + val DateValueHasEndEra: IRI = KnoraApiV2PrefixExpansion + "dateValueHasEndEra" + val DateValueHasCalendar: IRI = KnoraApiV2PrefixExpansion + "dateValueHasCalendar" + + val TextValueHasStandoff: IRI = KnoraApiV2PrefixExpansion + "textValueHasStandoff" + val TextValueHasMarkup: IRI = KnoraApiV2PrefixExpansion + "textValueHasMarkup" val TextValueHasMaxStandoffStartIndex: IRI = KnoraApiV2PrefixExpansion + "textValueHasMaxStandoffStartIndex" - val TextValueAsHtml: IRI = KnoraApiV2PrefixExpansion + "textValueAsHtml" - val TextValueAsXml: IRI = KnoraApiV2PrefixExpansion + "textValueAsXml" - val TextValueHasMapping: IRI = KnoraApiV2PrefixExpansion + "textValueHasMapping" - val TextValueHasLanguage: IRI = KnoraApiV2PrefixExpansion + "textValueHasLanguage" - val StandoffTag: IRI = KnoraApiV2PrefixExpansion + "StandoffTag" - val StandoffTagHasStartParent: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasStartParent" - val StandoffTagHasEndParent: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasEndParent" - val StandoffTagHasStartParentIndex: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasStartParentIndex" - val StandoffTagHasEndParentIndex: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasEndParentIndex" - val StandoffTagHasStart: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasStart" - val StandoffTagHasEnd: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasEnd" - val StandoffTagHasStartIndex: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasStartIndex" - val StandoffTagHasEndIndex: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasEndIndex" - val StandoffTagHasUUID: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasUUID" - val StandoffTagHasOriginalXMLID: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasOriginalXMLID" - val NextStandoffStartIndex: IRI = KnoraApiV2PrefixExpansion + "nextStandoffStartIndex" + val TextValueAsHtml: IRI = KnoraApiV2PrefixExpansion + "textValueAsHtml" + val TextValueAsXml: IRI = KnoraApiV2PrefixExpansion + "textValueAsXml" + val TextValueHasMapping: IRI = KnoraApiV2PrefixExpansion + "textValueHasMapping" + val TextValueHasLanguage: IRI = KnoraApiV2PrefixExpansion + "textValueHasLanguage" + val StandoffTag: IRI = KnoraApiV2PrefixExpansion + "StandoffTag" + val StandoffTagHasStartParent: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasStartParent" + val StandoffTagHasEndParent: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasEndParent" + val StandoffTagHasStartParentIndex: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasStartParentIndex" + val StandoffTagHasEndParentIndex: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasEndParentIndex" + val StandoffTagHasStart: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasStart" + val StandoffTagHasEnd: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasEnd" + val StandoffTagHasStartIndex: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasStartIndex" + val StandoffTagHasEndIndex: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasEndIndex" + val StandoffTagHasUUID: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasUUID" + val StandoffTagHasOriginalXMLID: IRI = KnoraApiV2PrefixExpansion + "standoffTagHasOriginalXMLID" + val NextStandoffStartIndex: IRI = KnoraApiV2PrefixExpansion + "nextStandoffStartIndex" val IntValueAsInt: IRI = KnoraApiV2PrefixExpansion + "intValueAsInt" @@ -924,26 +924,26 @@ object OntologyConstants { val GeometryValueAsGeometry: IRI = KnoraApiV2PrefixExpansion + "geometryValueAsGeometry" - val LinkValueHasTarget: IRI = KnoraApiV2PrefixExpansion + "linkValueHasTarget" + val LinkValueHasTarget: IRI = KnoraApiV2PrefixExpansion + "linkValueHasTarget" val LinkValueHasTargetIri: IRI = KnoraApiV2PrefixExpansion + "linkValueHasTargetIri" - val LinkValueHasSource: IRI = KnoraApiV2PrefixExpansion + "linkValueHasSource" + val LinkValueHasSource: IRI = KnoraApiV2PrefixExpansion + "linkValueHasSource" val LinkValueHasSourceIri: IRI = KnoraApiV2PrefixExpansion + "linkValueHasSourceIri" - val FileValueAsUrl: IRI = KnoraApiV2PrefixExpansion + "fileValueAsUrl" + val FileValueAsUrl: IRI = KnoraApiV2PrefixExpansion + "fileValueAsUrl" val FileValueHasFilename: IRI = KnoraApiV2PrefixExpansion + "fileValueHasFilename" - val StillImageFileValueHasDimX: IRI = KnoraApiV2PrefixExpansion + "stillImageFileValueHasDimX" - val StillImageFileValueHasDimY: IRI = KnoraApiV2PrefixExpansion + "stillImageFileValueHasDimY" + val StillImageFileValueHasDimX: IRI = KnoraApiV2PrefixExpansion + "stillImageFileValueHasDimX" + val StillImageFileValueHasDimY: IRI = KnoraApiV2PrefixExpansion + "stillImageFileValueHasDimY" val StillImageFileValueHasIIIFBaseUrl: IRI = KnoraApiV2PrefixExpansion + "stillImageFileValueHasIIIFBaseUrl" val DocumentFileValueHasPageCount: IRI = KnoraApiV2PrefixExpansion + "documentFileValueHasPageCount" - val DocumentFileValueHasDimX: IRI = KnoraApiV2PrefixExpansion + "documentFileValueHasDimX" - val DocumentFileValueHasDimY: IRI = KnoraApiV2PrefixExpansion + "documentFileValueHasDimY" + val DocumentFileValueHasDimX: IRI = KnoraApiV2PrefixExpansion + "documentFileValueHasDimX" + val DocumentFileValueHasDimY: IRI = KnoraApiV2PrefixExpansion + "documentFileValueHasDimY" val AudioFileValueHasDuration: IRI = KnoraApiV2PrefixExpansion + "audioFileValueHasDuration" val IntervalValueHasStart: IRI = KnoraApiV2PrefixExpansion + "intervalValueHasStart" - val IntervalValueHasEnd: IRI = KnoraApiV2PrefixExpansion + "intervalValueHasEnd" + val IntervalValueHasEnd: IRI = KnoraApiV2PrefixExpansion + "intervalValueHasEnd" val TimeValueAsTimeStamp: IRI = KnoraApiV2PrefixExpansion + "timeValueAsTimeStamp" @@ -961,15 +961,15 @@ object OntologyConstants { val MappingHasName: IRI = KnoraApiV2PrefixExpansion + "mappingHasName" - val IsMainResource: IRI = KnoraApiV2PrefixExpansion + "isMainResource" - val ToSimpleDateFunction: IRI = KnoraApiV2PrefixExpansion + "toSimpleDate" - val MatchTextFunction: IRI = KnoraApiV2PrefixExpansion + "matchText" + val IsMainResource: IRI = KnoraApiV2PrefixExpansion + "isMainResource" + val ToSimpleDateFunction: IRI = KnoraApiV2PrefixExpansion + "toSimpleDate" + val MatchTextFunction: IRI = KnoraApiV2PrefixExpansion + "matchText" val MatchTextInStandoffFunction: IRI = KnoraApiV2PrefixExpansion + "matchTextInStandoff" - val MatchLabelFunction: IRI = KnoraApiV2PrefixExpansion + "matchLabel" - val StandoffLinkFunction: IRI = KnoraApiV2PrefixExpansion + "standoffLink" + val MatchLabelFunction: IRI = KnoraApiV2PrefixExpansion + "matchLabel" + val StandoffLinkFunction: IRI = KnoraApiV2PrefixExpansion + "standoffLink" val GravsearchOptions: IRI = KnoraApiV2PrefixExpansion + "GravsearchOptions" - val UseInference: IRI = KnoraApiV2PrefixExpansion + "useInference" + val UseInference: IRI = KnoraApiV2PrefixExpansion + "useInference" } object SalsahGuiApiV2WithValueObjects { @@ -977,16 +977,16 @@ object OntologyConstants { KnoraApi.ApiOntologyStart + SalsahGui.SalsahGuiOntologyLabel + KnoraApiV2Complex.VersionSegment val SalsahGuiPrefixExpansion: IRI = SalsahGuiOntologyIri + "#" - val GuiAttribute: IRI = SalsahGuiPrefixExpansion + "guiAttribute" - val GuiOrder: IRI = SalsahGuiPrefixExpansion + "guiOrder" - val GuiElementProp: IRI = SalsahGuiPrefixExpansion + "guiElement" + val GuiAttribute: IRI = SalsahGuiPrefixExpansion + "guiAttribute" + val GuiOrder: IRI = SalsahGuiPrefixExpansion + "guiOrder" + val GuiElementProp: IRI = SalsahGuiPrefixExpansion + "guiElement" val GuiAttributeDefinition: IRI = SalsahGuiPrefixExpansion + "guiAttributeDefinition" - val GuiElementClass: IRI = SalsahGuiPrefixExpansion + "Guielement" + val GuiElementClass: IRI = SalsahGuiPrefixExpansion + "Guielement" - val Geometry: IRI = SalsahGuiPrefixExpansion + "Geometry" + val Geometry: IRI = SalsahGuiPrefixExpansion + "Geometry" val Colorpicker: IRI = SalsahGuiPrefixExpansion + "Colorpicker" - val Fileupload: IRI = SalsahGuiPrefixExpansion + "Fileupload" - val Richtext: IRI = SalsahGuiPrefixExpansion + "Richtext" + val Fileupload: IRI = SalsahGuiPrefixExpansion + "Fileupload" + val Richtext: IRI = SalsahGuiPrefixExpansion + "Richtext" } object KnoraApiV2Simple { @@ -997,35 +997,35 @@ object OntologyConstants { val KnoraApiV2PrefixExpansion: IRI = KnoraApiOntologyIri + "#" - val Result: IRI = KnoraApiV2PrefixExpansion + "result" - val Error: IRI = KnoraApiV2PrefixExpansion + "error" + val Result: IRI = KnoraApiV2PrefixExpansion + "result" + val Error: IRI = KnoraApiV2PrefixExpansion + "error" val MayHaveMoreResults: IRI = KnoraApiV2PrefixExpansion + "mayHaveMoreResults" val SubjectType: IRI = KnoraApiV2PrefixExpansion + "subjectType" val ObjectType: IRI = KnoraApiV2PrefixExpansion + "objectType" - val IsMainResource: IRI = KnoraApiV2PrefixExpansion + "isMainResource" - val MatchTextFunction: IRI = KnoraApiV2PrefixExpansion + "matchText" + val IsMainResource: IRI = KnoraApiV2PrefixExpansion + "isMainResource" + val MatchTextFunction: IRI = KnoraApiV2PrefixExpansion + "matchText" val MatchLabelFunction: IRI = KnoraApiV2PrefixExpansion + "matchLabel" val ResourceProperty: IRI = KnoraApiV2PrefixExpansion + "resourceProperty" - val Region: IRI = KnoraApiV2PrefixExpansion + "Region" - val Representation: IRI = KnoraApiV2PrefixExpansion + "Representation" - val StillImageRepresentation: IRI = KnoraApiV2PrefixExpansion + "StillImageRepresentation" + val Region: IRI = KnoraApiV2PrefixExpansion + "Region" + val Representation: IRI = KnoraApiV2PrefixExpansion + "Representation" + val StillImageRepresentation: IRI = KnoraApiV2PrefixExpansion + "StillImageRepresentation" val MovingImageRepresentation: IRI = KnoraApiV2PrefixExpansion + "MovingImageRepresentation" - val AudioRepresentation: IRI = KnoraApiV2PrefixExpansion + "AudioRepresentation" - val DDDRepresentation: IRI = KnoraApiV2PrefixExpansion + "DDDRepresentation" - val TextRepresentation: IRI = KnoraApiV2PrefixExpansion + "TextRepresentation" - val ArchiveRepresentation: IRI = KnoraApiV2PrefixExpansion + "ArchiveRepresentation" - val LinkObj: IRI = KnoraApiV2PrefixExpansion + "LinkObj" - - val Date: IRI = KnoraApiV2PrefixExpansion + "Date" - val Geom: IRI = KnoraApiV2PrefixExpansion + "Geom" - val Color: IRI = KnoraApiV2PrefixExpansion + "Color" + val AudioRepresentation: IRI = KnoraApiV2PrefixExpansion + "AudioRepresentation" + val DDDRepresentation: IRI = KnoraApiV2PrefixExpansion + "DDDRepresentation" + val TextRepresentation: IRI = KnoraApiV2PrefixExpansion + "TextRepresentation" + val ArchiveRepresentation: IRI = KnoraApiV2PrefixExpansion + "ArchiveRepresentation" + val LinkObj: IRI = KnoraApiV2PrefixExpansion + "LinkObj" + + val Date: IRI = KnoraApiV2PrefixExpansion + "Date" + val Geom: IRI = KnoraApiV2PrefixExpansion + "Geom" + val Color: IRI = KnoraApiV2PrefixExpansion + "Color" val Interval: IRI = KnoraApiV2PrefixExpansion + "Interval" - val Geoname: IRI = KnoraApiV2PrefixExpansion + "Geoname" + val Geoname: IRI = KnoraApiV2PrefixExpansion + "Geoname" val ListNode: IRI = KnoraApiV2PrefixExpansion + "ListNode" val Resource: IRI = KnoraApiV2PrefixExpansion + "Resource" @@ -1038,24 +1038,24 @@ object OntologyConstants { val HasValue: IRI = KnoraApiV2PrefixExpansion + "hasValue" - val HasLinkTo: IRI = KnoraApiV2PrefixExpansion + "hasLinkTo" + val HasLinkTo: IRI = KnoraApiV2PrefixExpansion + "hasLinkTo" val HasIncomingLink: IRI = KnoraApiV2PrefixExpansion + "hasIncomingLink" - val IsPartOf: IRI = KnoraApiV2PrefixExpansion + "isPartOf" - val IsRegionOf: IRI = KnoraApiV2PrefixExpansion + "isRegionOf" + val IsPartOf: IRI = KnoraApiV2PrefixExpansion + "isPartOf" + val IsRegionOf: IRI = KnoraApiV2PrefixExpansion + "isRegionOf" val HasGeometry: IRI = KnoraApiV2PrefixExpansion + "hasGeometry" - val HasColor: IRI = KnoraApiV2PrefixExpansion + "hasColor" - val HasComment: IRI = KnoraApiV2PrefixExpansion + "hasComment" + val HasColor: IRI = KnoraApiV2PrefixExpansion + "hasColor" + val HasComment: IRI = KnoraApiV2PrefixExpansion + "hasComment" val HasFile: IRI = KnoraApiV2PrefixExpansion + "hasFile" - val HasStillImageFile: IRI = KnoraApiV2PrefixExpansion + "hasStillImageFile" + val HasStillImageFile: IRI = KnoraApiV2PrefixExpansion + "hasStillImageFile" val HasMovingImageFile: IRI = KnoraApiV2PrefixExpansion + "hasMovingImageFile" - val HasAudioFile: IRI = KnoraApiV2PrefixExpansion + "hasAudioFile" - val HasDDDFile: IRI = KnoraApiV2PrefixExpansion + "hasDDDFile" - val HasTextFile: IRI = KnoraApiV2PrefixExpansion + "hasTextFile" - val HasDocumentFile: IRI = KnoraApiV2PrefixExpansion + "hasDocumentFile" - val HasArchiveFile: IRI = KnoraApiV2PrefixExpansion + "hasArchiveFile" + val HasAudioFile: IRI = KnoraApiV2PrefixExpansion + "hasAudioFile" + val HasDDDFile: IRI = KnoraApiV2PrefixExpansion + "hasDDDFile" + val HasTextFile: IRI = KnoraApiV2PrefixExpansion + "hasTextFile" + val HasDocumentFile: IRI = KnoraApiV2PrefixExpansion + "hasDocumentFile" + val HasArchiveFile: IRI = KnoraApiV2PrefixExpansion + "hasArchiveFile" val File: IRI = KnoraApiV2PrefixExpansion + "File" @@ -1071,11 +1071,11 @@ object OntologyConstants { File ) - val ArkUrl: IRI = KnoraApiV2PrefixExpansion + "arkUrl" + val ArkUrl: IRI = KnoraApiV2PrefixExpansion + "arkUrl" val VersionArkUrl: IRI = KnoraApiV2PrefixExpansion + "versionArkUrl" val GravsearchOptions: IRI = KnoraApiV2PrefixExpansion + "GravsearchOptions" - val UseInference: IRI = KnoraApiV2PrefixExpansion + "useInference" + val UseInference: IRI = KnoraApiV2PrefixExpansion + "useInference" } /** @@ -1086,105 +1086,105 @@ object OntologyConstants { (InternalSchema, ApiV2Simple) -> Map( // All the values of this map must be either properties or datatypes. PropertyInfoContentV2.toOntologySchema // relies on this assumption. - KnoraBase.SubjectClassConstraint -> KnoraApiV2Simple.SubjectType, - KnoraBase.ObjectClassConstraint -> KnoraApiV2Simple.ObjectType, + KnoraBase.SubjectClassConstraint -> KnoraApiV2Simple.SubjectType, + KnoraBase.ObjectClassConstraint -> KnoraApiV2Simple.ObjectType, KnoraBase.ObjectDatatypeConstraint -> KnoraApiV2Simple.ObjectType, - KnoraBase.TextValue -> Xsd.String, - KnoraBase.IntValue -> Xsd.Integer, - KnoraBase.BooleanValue -> Xsd.Boolean, - KnoraBase.UriValue -> Xsd.Uri, - KnoraBase.DecimalValue -> Xsd.Decimal, - KnoraBase.TimeValue -> Xsd.DateTimeStamp, - KnoraBase.DateValue -> KnoraApiV2Simple.Date, - KnoraBase.ColorValue -> KnoraApiV2Simple.Color, - KnoraBase.GeomValue -> KnoraApiV2Simple.Geom, - KnoraBase.ListValue -> KnoraApiV2Simple.ListNode, - KnoraBase.IntervalValue -> KnoraApiV2Simple.Interval, - KnoraBase.GeonameValue -> KnoraApiV2Simple.Geoname, - KnoraBase.FileValue -> KnoraApiV2Simple.File, - KnoraBase.StillImageFileValue -> KnoraApiV2Simple.File, - KnoraBase.MovingImageFileValue -> KnoraApiV2Simple.File, - KnoraBase.AudioFileValue -> KnoraApiV2Simple.File, - KnoraBase.DDDFileValue -> KnoraApiV2Simple.File, - KnoraBase.TextFileValue -> KnoraApiV2Simple.File, - KnoraBase.DocumentFileValue -> KnoraApiV2Simple.File, - KnoraBase.ArchiveFileValue -> KnoraApiV2Simple.File, - KnoraBase.HasFileValue -> KnoraApiV2Simple.HasFile, - KnoraBase.HasStillImageFileValue -> KnoraApiV2Simple.HasStillImageFile, - KnoraBase.HasMovingImageFileValue -> KnoraApiV2Simple.HasMovingImageFile, - KnoraBase.HasAudioFileValue -> KnoraApiV2Simple.HasAudioFile, - KnoraBase.HasDDDFileValue -> KnoraApiV2Simple.HasDDDFile, - KnoraBase.HasTextFileValue -> KnoraApiV2Simple.HasTextFile, - KnoraBase.HasDocumentFileValue -> KnoraApiV2Simple.HasDocumentFile, - KnoraBase.HasArchiveFileValue -> KnoraApiV2Simple.HasArchiveFile + KnoraBase.TextValue -> Xsd.String, + KnoraBase.IntValue -> Xsd.Integer, + KnoraBase.BooleanValue -> Xsd.Boolean, + KnoraBase.UriValue -> Xsd.Uri, + KnoraBase.DecimalValue -> Xsd.Decimal, + KnoraBase.TimeValue -> Xsd.DateTimeStamp, + KnoraBase.DateValue -> KnoraApiV2Simple.Date, + KnoraBase.ColorValue -> KnoraApiV2Simple.Color, + KnoraBase.GeomValue -> KnoraApiV2Simple.Geom, + KnoraBase.ListValue -> KnoraApiV2Simple.ListNode, + KnoraBase.IntervalValue -> KnoraApiV2Simple.Interval, + KnoraBase.GeonameValue -> KnoraApiV2Simple.Geoname, + KnoraBase.FileValue -> KnoraApiV2Simple.File, + KnoraBase.StillImageFileValue -> KnoraApiV2Simple.File, + KnoraBase.MovingImageFileValue -> KnoraApiV2Simple.File, + KnoraBase.AudioFileValue -> KnoraApiV2Simple.File, + KnoraBase.DDDFileValue -> KnoraApiV2Simple.File, + KnoraBase.TextFileValue -> KnoraApiV2Simple.File, + KnoraBase.DocumentFileValue -> KnoraApiV2Simple.File, + KnoraBase.ArchiveFileValue -> KnoraApiV2Simple.File, + KnoraBase.HasFileValue -> KnoraApiV2Simple.HasFile, + KnoraBase.HasStillImageFileValue -> KnoraApiV2Simple.HasStillImageFile, + KnoraBase.HasMovingImageFileValue -> KnoraApiV2Simple.HasMovingImageFile, + KnoraBase.HasAudioFileValue -> KnoraApiV2Simple.HasAudioFile, + KnoraBase.HasDDDFileValue -> KnoraApiV2Simple.HasDDDFile, + KnoraBase.HasTextFileValue -> KnoraApiV2Simple.HasTextFile, + KnoraBase.HasDocumentFileValue -> KnoraApiV2Simple.HasDocumentFile, + KnoraBase.HasArchiveFileValue -> KnoraApiV2Simple.HasArchiveFile ), (InternalSchema, ApiV2Complex) -> Map( - KnoraBase.SubjectClassConstraint -> KnoraApiV2Complex.SubjectType, - KnoraBase.ObjectClassConstraint -> KnoraApiV2Complex.ObjectType, + KnoraBase.SubjectClassConstraint -> KnoraApiV2Complex.SubjectType, + KnoraBase.ObjectClassConstraint -> KnoraApiV2Complex.ObjectType, KnoraBase.ObjectDatatypeConstraint -> KnoraApiV2Complex.ObjectType, - KnoraBase.ValueHasString -> KnoraApiV2Complex.ValueAsString, - KnoraBase.ValueHasUri -> KnoraApiV2Complex.UriValueAsUri, - KnoraBase.ValueHasInteger -> KnoraApiV2Complex.IntValueAsInt, - KnoraBase.ValueHasDecimal -> KnoraApiV2Complex.DecimalValueAsDecimal, - KnoraBase.ValueHasBoolean -> KnoraApiV2Complex.BooleanValueAsBoolean, - KnoraBase.ValueHasIntervalStart -> KnoraApiV2Complex.IntervalValueHasStart, - KnoraBase.ValueHasIntervalEnd -> KnoraApiV2Complex.IntervalValueHasEnd, - KnoraBase.ValueHasTimeStamp -> KnoraApiV2Complex.TimeValueAsTimeStamp, - KnoraBase.ValueHasLanguage -> KnoraApiV2Complex.TextValueHasLanguage, - KnoraBase.ValueHasListNode -> KnoraApiV2Complex.ListValueAsListNode, - KnoraBase.ValueHasGeonameCode -> KnoraApiV2Complex.GeonameValueAsGeonameCode, - KnoraBase.ValueHasColor -> KnoraApiV2Complex.ColorValueAsColor, - KnoraBase.ValueHasStandoff -> KnoraApiV2Complex.TextValueHasStandoff, - KnoraBase.PageCount -> KnoraApiV2Complex.DocumentFileValueHasPageCount, - KnoraAdmin.KnoraProject -> Xsd.Uri, - KnoraAdmin.User -> Xsd.Uri + KnoraBase.ValueHasString -> KnoraApiV2Complex.ValueAsString, + KnoraBase.ValueHasUri -> KnoraApiV2Complex.UriValueAsUri, + KnoraBase.ValueHasInteger -> KnoraApiV2Complex.IntValueAsInt, + KnoraBase.ValueHasDecimal -> KnoraApiV2Complex.DecimalValueAsDecimal, + KnoraBase.ValueHasBoolean -> KnoraApiV2Complex.BooleanValueAsBoolean, + KnoraBase.ValueHasIntervalStart -> KnoraApiV2Complex.IntervalValueHasStart, + KnoraBase.ValueHasIntervalEnd -> KnoraApiV2Complex.IntervalValueHasEnd, + KnoraBase.ValueHasTimeStamp -> KnoraApiV2Complex.TimeValueAsTimeStamp, + KnoraBase.ValueHasLanguage -> KnoraApiV2Complex.TextValueHasLanguage, + KnoraBase.ValueHasListNode -> KnoraApiV2Complex.ListValueAsListNode, + KnoraBase.ValueHasGeonameCode -> KnoraApiV2Complex.GeonameValueAsGeonameCode, + KnoraBase.ValueHasColor -> KnoraApiV2Complex.ColorValueAsColor, + KnoraBase.ValueHasStandoff -> KnoraApiV2Complex.TextValueHasStandoff, + KnoraBase.PageCount -> KnoraApiV2Complex.DocumentFileValueHasPageCount, + KnoraAdmin.KnoraProject -> Xsd.Uri, + KnoraAdmin.User -> Xsd.Uri ), (ApiV2Simple, InternalSchema) -> Map( // Not all types in ApiV2Simple can be converted here to types in KnoraBase. For example, // to know whether an xsd:string corresponds to a knora-base:TextValue, or whether it should remain // an xsd:string, we would need to know the context in which it is used, which we don't have here. - KnoraApiV2Simple.SubjectType -> KnoraBase.SubjectClassConstraint, - KnoraApiV2Simple.ObjectType -> KnoraBase.ObjectClassConstraint, - KnoraApiV2Simple.Date -> KnoraBase.DateValue, - KnoraApiV2Simple.Color -> KnoraBase.ColorValue, - KnoraApiV2Simple.Geom -> KnoraBase.GeomValue, - KnoraApiV2Simple.Interval -> KnoraBase.IntervalValue, - KnoraApiV2Simple.Geoname -> KnoraBase.GeonameValue, - KnoraApiV2Simple.File -> KnoraBase.FileValue, - KnoraApiV2Simple.HasFile -> KnoraBase.HasFileValue, - KnoraApiV2Simple.HasStillImageFile -> KnoraBase.HasStillImageFileValue, + KnoraApiV2Simple.SubjectType -> KnoraBase.SubjectClassConstraint, + KnoraApiV2Simple.ObjectType -> KnoraBase.ObjectClassConstraint, + KnoraApiV2Simple.Date -> KnoraBase.DateValue, + KnoraApiV2Simple.Color -> KnoraBase.ColorValue, + KnoraApiV2Simple.Geom -> KnoraBase.GeomValue, + KnoraApiV2Simple.Interval -> KnoraBase.IntervalValue, + KnoraApiV2Simple.Geoname -> KnoraBase.GeonameValue, + KnoraApiV2Simple.File -> KnoraBase.FileValue, + KnoraApiV2Simple.HasFile -> KnoraBase.HasFileValue, + KnoraApiV2Simple.HasStillImageFile -> KnoraBase.HasStillImageFileValue, KnoraApiV2Simple.HasMovingImageFile -> KnoraBase.HasMovingImageFileValue, - KnoraApiV2Simple.HasAudioFile -> KnoraBase.HasAudioFileValue, - KnoraApiV2Simple.HasDDDFile -> KnoraBase.HasDDDFileValue, - KnoraApiV2Simple.HasTextFile -> KnoraBase.HasTextFileValue, - KnoraApiV2Simple.HasDocumentFile -> KnoraBase.HasDocumentFileValue, - KnoraApiV2Simple.HasArchiveFile -> KnoraBase.HasArchiveFileValue, - KnoraApiV2Simple.ListNode -> KnoraBase.ListValue + KnoraApiV2Simple.HasAudioFile -> KnoraBase.HasAudioFileValue, + KnoraApiV2Simple.HasDDDFile -> KnoraBase.HasDDDFileValue, + KnoraApiV2Simple.HasTextFile -> KnoraBase.HasTextFileValue, + KnoraApiV2Simple.HasDocumentFile -> KnoraBase.HasDocumentFileValue, + KnoraApiV2Simple.HasArchiveFile -> KnoraBase.HasArchiveFileValue, + KnoraApiV2Simple.ListNode -> KnoraBase.ListValue ), (ApiV2Complex, InternalSchema) -> Map( - KnoraApiV2Complex.SubjectType -> KnoraBase.SubjectClassConstraint, - KnoraApiV2Complex.ObjectType -> KnoraBase.ObjectClassConstraint, - KnoraApiV2Complex.UriValueAsUri -> KnoraBase.ValueHasUri, - KnoraApiV2Complex.IntValueAsInt -> KnoraBase.ValueHasInteger, - KnoraApiV2Complex.DecimalValueAsDecimal -> KnoraBase.ValueHasDecimal, - KnoraApiV2Complex.BooleanValueAsBoolean -> KnoraBase.ValueHasBoolean, - KnoraApiV2Complex.IntervalValueHasStart -> KnoraBase.ValueHasIntervalStart, - KnoraApiV2Complex.IntervalValueHasEnd -> KnoraBase.ValueHasIntervalEnd, - KnoraApiV2Complex.TimeValueAsTimeStamp -> KnoraBase.ValueHasTimeStamp, - KnoraApiV2Complex.ValueAsString -> KnoraBase.ValueHasString, - KnoraApiV2Complex.TextValueHasLanguage -> KnoraBase.ValueHasLanguage, - KnoraApiV2Complex.ListValueAsListNode -> KnoraBase.ValueHasListNode, - KnoraApiV2Complex.GeonameValueAsGeonameCode -> KnoraBase.ValueHasGeonameCode, - KnoraApiV2Complex.ColorValueAsColor -> KnoraBase.ValueHasColor, - KnoraApiV2Complex.TextValueHasStandoff -> KnoraBase.ValueHasStandoff, + KnoraApiV2Complex.SubjectType -> KnoraBase.SubjectClassConstraint, + KnoraApiV2Complex.ObjectType -> KnoraBase.ObjectClassConstraint, + KnoraApiV2Complex.UriValueAsUri -> KnoraBase.ValueHasUri, + KnoraApiV2Complex.IntValueAsInt -> KnoraBase.ValueHasInteger, + KnoraApiV2Complex.DecimalValueAsDecimal -> KnoraBase.ValueHasDecimal, + KnoraApiV2Complex.BooleanValueAsBoolean -> KnoraBase.ValueHasBoolean, + KnoraApiV2Complex.IntervalValueHasStart -> KnoraBase.ValueHasIntervalStart, + KnoraApiV2Complex.IntervalValueHasEnd -> KnoraBase.ValueHasIntervalEnd, + KnoraApiV2Complex.TimeValueAsTimeStamp -> KnoraBase.ValueHasTimeStamp, + KnoraApiV2Complex.ValueAsString -> KnoraBase.ValueHasString, + KnoraApiV2Complex.TextValueHasLanguage -> KnoraBase.ValueHasLanguage, + KnoraApiV2Complex.ListValueAsListNode -> KnoraBase.ValueHasListNode, + KnoraApiV2Complex.GeonameValueAsGeonameCode -> KnoraBase.ValueHasGeonameCode, + KnoraApiV2Complex.ColorValueAsColor -> KnoraBase.ValueHasColor, + KnoraApiV2Complex.TextValueHasStandoff -> KnoraBase.ValueHasStandoff, KnoraApiV2Complex.DocumentFileValueHasPageCount -> KnoraBase.PageCount ) ) object NamedGraphs { - val DataNamedGraphStart: IRI = "http://www.knora.org/data" - val AdminNamedGraph: IRI = "http://www.knora.org/data/admin" - val PermissionNamedGraph: IRI = "http://www.knora.org/data/permissions" + val DataNamedGraphStart: IRI = "http://www.knora.org/data" + val AdminNamedGraph: IRI = "http://www.knora.org/data/admin" + val PermissionNamedGraph: IRI = "http://www.knora.org/data/permissions" val PersistentMapNamedGraph: IRI = "http://www.knora.org/data/maps" val KnoraExplicitNamedGraph: IRI = "http://www.knora.org/explicit" } diff --git a/webapi/src/main/scala/org/knora/webapi/messages/StringFormatter.scala b/webapi/src/main/scala/org/knora/webapi/messages/StringFormatter.scala index 0e66c26dc3..cc2451725a 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/StringFormatter.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/StringFormatter.scala @@ -66,10 +66,10 @@ object StringFormatter { val PARAGRAPH_SEPARATOR = '\u2029' // Control sequences for changing text colour in terminals. - val ANSI_RED = "\u001B[31m" - val ANSI_GREEN = "\u001B[32m" + val ANSI_RED = "\u001B[31m" + val ANSI_GREEN = "\u001B[32m" val ANSI_YELLOW = "\u001B[33m" - val ANSI_RESET = "\u001B[0m" + val ANSI_RESET = "\u001B[0m" /** * Separates the calendar name from the rest of a Knora date. @@ -741,14 +741,14 @@ class StringFormatter private ( // Calendar:YYYY[-MM[-DD]][ EE][:YYYY[-MM[-DD]][ EE]] // EE being the era: one of BC or AD private val KnoraDateRegex: Regex = ("""^(GREGORIAN|JULIAN|ISLAMIC)""" + - CalendarSeparator + // calendar name + CalendarSeparator + // calendar name """(?:[1-9][0-9]{0,3})(""" + // year PrecisionSeparator + """(?!00)[0-9]{1,2}(""" + // month PrecisionSeparator + """(?!00)[0-9]{1,2})?)?( BC| AD| BCE| CE)?(""" + // day - CalendarSeparator + // separator if a period is given - """(?:[1-9][0-9]{0,3})(""" + // year 2 + CalendarSeparator + // separator if a period is given + """(?:[1-9][0-9]{0,3})(""" + // year 2 PrecisionSeparator + """(?!00)[0-9]{1,2}(""" + // month 2 PrecisionSeparator + @@ -918,7 +918,7 @@ class StringFormatter private ( errorFun } - val lastSegment = segments.last + val lastSegment = segments.last val lastTwoSegments = segments.slice(segments.length - 2, segments.length) if (lastTwoSegments == Vector("simple", "v2")) { @@ -999,7 +999,7 @@ class StringFormatter private ( val hashPos = iri.lastIndexOf('#') val (namespace: String, entityName: Option[String]) = if (hashPos >= 0 && hashPos < iri.length) { - val namespace = iri.substring(0, hashPos) + val namespace = iri.substring(0, hashPos) val entityName = iri.substring(hashPos + 1) // Validate the entity name as an NCName. @@ -1009,7 +1009,7 @@ class StringFormatter private ( } // Remove the URL scheme (http://), and split the remainder of the namespace into slash-delimited segments. - val body = namespace.substring(namespace.indexOf("//") + 2) + val body = namespace.substring(namespace.indexOf("//") + 2) val segments = body.split('/').toVector // The segments must contain at least a hostname. @@ -1090,7 +1090,7 @@ class StringFormatter private ( } // Extract the ontology name. - val ontologyName = ontologyPath.last + val ontologyName = ontologyPath.last val hasBuiltInOntologyName = isBuiltInOntologyName(ontologyName) if (!hasBuiltInOntologyName) { @@ -1299,7 +1299,7 @@ class StringFormatter private ( private def externalToInternalEntityIri: SmartIri = { // Construct the string representation of this IRI in the target schema. val internalOntologyName = externalToInternalOntologyName(getOntologyName) - val entityName = getEntityName + val entityName = getEntityName val internalOntologyIri = makeInternalOntologyIriStr( internalOntologyName = internalOntologyName, @@ -1328,8 +1328,8 @@ class StringFormatter private ( private def internalToExternalEntityIri(targetSchema: ApiV2Schema): SmartIri = { //Construct the string representation of this IRI in the target schema. - val entityName = getEntityName - val convertedOntologyIri = getOntologyFromEntity.toOntologySchema(targetSchema) + val entityName = getEntityName + val convertedOntologyIri = getOntologyFromEntity.toOntologySchema(targetSchema) val convertedEntityIriStr = convertedOntologyIri.toString + "#" + entityName // Get it from the cache, or construct it and cache it if it's not there. @@ -1350,7 +1350,7 @@ class StringFormatter private ( } private def internalToExternalOntologyIri(targetSchema: ApiV2Schema): SmartIri = { - val ontologyName = getOntologyName + val ontologyName = getOntologyName val versionSegment = getVersionSegment(targetSchema) val convertedIriStr: IRI = if (isKnoraBuiltInDefinitionIri) { @@ -1434,7 +1434,7 @@ class StringFormatter private ( if (entityName.endsWith("Value")) { val convertedEntityName = entityName.substring(0, entityName.length - "Value".length) - val convertedIriStr = getOntologyFromEntity.makeEntityIri(convertedEntityName).toString + val convertedIriStr = getOntologyFromEntity.makeEntityIri(convertedEntityName).toString getOrCacheSmartIri( iriStr = convertedIriStr, @@ -1461,9 +1461,9 @@ class StringFormatter private ( throw DataConversionException(s"IRI $iri is not a Knora entity IRI, so it cannot be a link property IRI") } - val entityName = getEntityName + val entityName = getEntityName val convertedEntityName = entityName + "Value" - val convertedIriStr = getOntologyFromEntity.makeEntityIri(convertedEntityName).toString + val convertedIriStr = getOntologyFromEntity.makeEntityIri(convertedEntityName).toString getOrCacheSmartIri( iriStr = convertedIriStr, @@ -1980,12 +1980,12 @@ class StringFormatter private ( def formatArkTimestamp(timestamp: Instant): String = { val offsetDateTime: OffsetDateTime = timestamp.atOffset(ZoneOffset.UTC) - val year: Int = offsetDateTime.get(ChronoField.YEAR) - val month: Int = offsetDateTime.get(ChronoField.MONTH_OF_YEAR) - val day: Int = offsetDateTime.get(ChronoField.DAY_OF_MONTH) - val hour: Int = offsetDateTime.get(ChronoField.HOUR_OF_DAY) - val minute: Int = offsetDateTime.get(ChronoField.MINUTE_OF_HOUR) - val second: Int = offsetDateTime.get(ChronoField.SECOND_OF_MINUTE) + val year: Int = offsetDateTime.get(ChronoField.YEAR) + val month: Int = offsetDateTime.get(ChronoField.MONTH_OF_YEAR) + val day: Int = offsetDateTime.get(ChronoField.DAY_OF_MONTH) + val hour: Int = offsetDateTime.get(ChronoField.HOUR_OF_DAY) + val minute: Int = offsetDateTime.get(ChronoField.MINUTE_OF_HOUR) + val second: Int = offsetDateTime.get(ChronoField.SECOND_OF_MINUTE) val nanoOfSecond: Int = offsetDateTime.get(ChronoField.NANO_OF_SECOND) val fractionStr: IRI = if (nanoOfSecond > 0) { @@ -2823,7 +2823,7 @@ class StringFormatter private ( ): Future[Boolean] = for { askString <- Future(org.knora.webapi.messages.twirl.queries.sparql.admin.txt.checkIriExists(iri).toString) - response <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] + response <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] } yield response.result /** @@ -2878,7 +2878,7 @@ class StringFormatter private ( * @return a 22-character string representing the UUID. */ def base64EncodeUuid(uuid: UUID): String = { - val bytes = Array.ofDim[Byte](16) + val bytes = Array.ofDim[Byte](16) val byteBuffer = ByteBuffer.wrap(bytes) byteBuffer.putLong(uuid.getMostSignificantBits) byteBuffer.putLong(uuid.getLeastSignificantBits) @@ -2892,7 +2892,7 @@ class StringFormatter private ( * @return the equivalent [[UUID]]. */ def base64DecodeUuid(base64Uuid: String): UUID = { - val bytes = base64Decoder.decode(base64Uuid) + val bytes = base64Decoder.decode(base64Uuid) val byteBuffer = ByteBuffer.wrap(bytes) new UUID(byteBuffer.getLong, byteBuffer.getLong) } diff --git a/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/groupsmessages/GroupsErrorMessagesADM.scala b/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/groupsmessages/GroupsErrorMessagesADM.scala index 3e86e611ef..17f3aae494 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/groupsmessages/GroupsErrorMessagesADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/groupsmessages/GroupsErrorMessagesADM.scala @@ -6,10 +6,10 @@ package org.knora.webapi.messages.admin.responder.groupsmessages object GroupsErrorMessagesADM { - val GROUP_IRI_MISSING_ERROR = "Group IRI cannot be empty." - val GROUP_IRI_INVALID_ERROR = "Group IRI is invalid." - val GROUP_NAME_MISSING_ERROR = "Group name cannot be empty." - val GROUP_NAME_INVALID_ERROR = "Group name is invalid." + val GROUP_IRI_MISSING_ERROR = "Group IRI cannot be empty." + val GROUP_IRI_INVALID_ERROR = "Group IRI is invalid." + val GROUP_NAME_MISSING_ERROR = "Group name cannot be empty." + val GROUP_NAME_INVALID_ERROR = "Group name is invalid." val GROUP_DESCRIPTION_MISSING_ERROR = "Group description cannot be empty." val GROUP_DESCRIPTION_INVALID_ERROR = "Group description is invalid." } diff --git a/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/groupsmessages/GroupsMessagesADM.scala b/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/groupsmessages/GroupsMessagesADM.scala index bb2c11a099..707dd65923 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/groupsmessages/GroupsMessagesADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/groupsmessages/GroupsMessagesADM.scala @@ -309,7 +309,7 @@ trait GroupsADMJsonProtocol extends SprayJsonSupport with DefaultJsonProtocol wi import org.knora.webapi.messages.admin.responder.usersmessages.UsersADMJsonProtocol._ - implicit val groupADMFormat: JsonFormat[GroupADM] = jsonFormat6(GroupADM) + implicit val groupADMFormat: JsonFormat[GroupADM] = jsonFormat6(GroupADM) implicit val groupShortADMFormat: JsonFormat[GroupShortADM] = jsonFormat5(GroupShortADM) implicit val groupsGetResponseADMFormat: RootJsonFormat[GroupsGetResponseADM] = jsonFormat(GroupsGetResponseADM, "groups") diff --git a/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/listsmessages/ListsErrorMessagesADM.scala b/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/listsmessages/ListsErrorMessagesADM.scala index 1da614f4e7..891a187467 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/listsmessages/ListsErrorMessagesADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/listsmessages/ListsErrorMessagesADM.scala @@ -6,19 +6,19 @@ package org.knora.webapi.messages.admin.responder.listsmessages object ListsErrorMessagesADM { - val LIST_IRI_MISSING_ERROR = "List IRI cannot be empty." - val LIST_IRI_INVALID_ERROR = "List IRI cannot be empty." - val LIST_NODE_IRI_MISSING_ERROR = "List node IRI cannot be empty." - val LIST_NODE_IRI_INVALID_ERROR = "List node IRI is invalid." - val LIST_NAME_MISSING_ERROR = "List name cannot be empty." - val LIST_NAME_INVALID_ERROR = "List name is invalid." - val LABEL_MISSING_ERROR = "At least one label needs to be supplied." - val LABEL_INVALID_ERROR = "Invalid label." - val COMMENT_MISSING_ERROR = "At least one comment needs to be supplied." - val COMMENT_INVALID_ERROR = "Invalid comment." - val LIST_CREATE_PERMISSION_ERROR = "A list can only be created by the project or system administrator." + val LIST_IRI_MISSING_ERROR = "List IRI cannot be empty." + val LIST_IRI_INVALID_ERROR = "List IRI cannot be empty." + val LIST_NODE_IRI_MISSING_ERROR = "List node IRI cannot be empty." + val LIST_NODE_IRI_INVALID_ERROR = "List node IRI is invalid." + val LIST_NAME_MISSING_ERROR = "List name cannot be empty." + val LIST_NAME_INVALID_ERROR = "List name is invalid." + val LABEL_MISSING_ERROR = "At least one label needs to be supplied." + val LABEL_INVALID_ERROR = "Invalid label." + val COMMENT_MISSING_ERROR = "At least one comment needs to be supplied." + val COMMENT_INVALID_ERROR = "Invalid comment." + val LIST_CREATE_PERMISSION_ERROR = "A list can only be created by the project or system administrator." val LIST_NODE_CREATE_PERMISSION_ERROR = "A list node can only be created by the project or system administrator." - val LIST_CHANGE_PERMISSION_ERROR = "A list can only be changed by the project or system administrator." - val UPDATE_REQUEST_EMPTY_LABEL_ERROR = "List labels cannot be empty." - val INVALID_POSITION = "Invalid position value is given, position should be either a positive value or -1." + val LIST_CHANGE_PERMISSION_ERROR = "A list can only be changed by the project or system administrator." + val UPDATE_REQUEST_EMPTY_LABEL_ERROR = "List labels cannot be empty." + val INVALID_POSITION = "Invalid position value is given, position should be either a positive value or -1." } diff --git a/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/listsmessages/ListsMessagesADM.scala b/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/listsmessages/ListsMessagesADM.scala index cc3a38b971..ec8e467206 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/listsmessages/ListsMessagesADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/listsmessages/ListsMessagesADM.scala @@ -756,7 +756,7 @@ case class ListRootNodeADM( def unescape: ListRootNodeADM = { val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - val unescapedLabels = stringFormatter.unescapeStringLiteralSeq(labels) + val unescapedLabels = stringFormatter.unescapeStringLiteralSeq(labels) val unescapedComments = stringFormatter.unescapeStringLiteralSeq(comments) val unescapedName: Option[String] = name match { @@ -931,19 +931,19 @@ trait ListADMJsonProtocol extends SprayJsonSupport with DefaultJsonProtocol with case root: ListRootNodeInfoADM => if (root.name.nonEmpty) { JsObject( - "id" -> root.id.toJson, + "id" -> root.id.toJson, "projectIri" -> root.projectIri.toJson, - "name" -> root.name.toJson, - "labels" -> JsArray(root.labels.stringLiterals.map(_.toJson)), - "comments" -> JsArray(root.comments.stringLiterals.map(_.toJson)), + "name" -> root.name.toJson, + "labels" -> JsArray(root.labels.stringLiterals.map(_.toJson)), + "comments" -> JsArray(root.comments.stringLiterals.map(_.toJson)), "isRootNode" -> true.toJson ) } else { JsObject( - "id" -> root.id.toJson, + "id" -> root.id.toJson, "projectIri" -> root.projectIri.toJson, - "labels" -> JsArray(root.labels.stringLiterals.map(_.toJson)), - "comments" -> JsArray(root.comments.stringLiterals.map(_.toJson)), + "labels" -> JsArray(root.labels.stringLiterals.map(_.toJson)), + "comments" -> JsArray(root.comments.stringLiterals.map(_.toJson)), "isRootNode" -> true.toJson ) } @@ -951,19 +951,19 @@ trait ListADMJsonProtocol extends SprayJsonSupport with DefaultJsonProtocol with case child: ListChildNodeInfoADM => if (child.name.nonEmpty) { JsObject( - "id" -> child.id.toJson, - "name" -> child.name.toJson, - "labels" -> JsArray(child.labels.stringLiterals.map(_.toJson)), - "comments" -> JsArray(child.comments.stringLiterals.map(_.toJson)), - "position" -> child.position.toJson, + "id" -> child.id.toJson, + "name" -> child.name.toJson, + "labels" -> JsArray(child.labels.stringLiterals.map(_.toJson)), + "comments" -> JsArray(child.comments.stringLiterals.map(_.toJson)), + "position" -> child.position.toJson, "hasRootNode" -> child.hasRootNode.toJson ) } else { JsObject( - "id" -> child.id.toJson, - "labels" -> JsArray(child.labels.stringLiterals.map(_.toJson)), - "comments" -> JsArray(child.comments.stringLiterals.map(_.toJson)), - "position" -> child.position.toJson, + "id" -> child.id.toJson, + "labels" -> JsArray(child.labels.stringLiterals.map(_.toJson)), + "comments" -> JsArray(child.comments.stringLiterals.map(_.toJson)), + "position" -> child.position.toJson, "hasRootNode" -> child.hasRootNode.toJson ) } @@ -1060,19 +1060,19 @@ trait ListADMJsonProtocol extends SprayJsonSupport with DefaultJsonProtocol with node match { case root: ListRootNodeADM => JsObject( - "id" -> root.id.toJson, + "id" -> root.id.toJson, "projectIri" -> root.projectIri.toJson, - "name" -> root.name.toJson, - "labels" -> JsArray(root.labels.stringLiterals.map(_.toJson)), - "comments" -> JsArray(root.comments.stringLiterals.map(_.toJson)), + "name" -> root.name.toJson, + "labels" -> JsArray(root.labels.stringLiterals.map(_.toJson)), + "comments" -> JsArray(root.comments.stringLiterals.map(_.toJson)), "isRootNode" -> true.toJson, - "children" -> JsArray(root.children.map(write).toVector) + "children" -> JsArray(root.children.map(write).toVector) ) case child: ListChildNodeADM => JsObject( - "id" -> child.id.toJson, - "name" -> child.name.toJson, + "id" -> child.id.toJson, + "name" -> child.name.toJson, "labels" -> JsArray(child.labels.stringLiterals.map(_.toJson)), "comments" -> JsArray( child.comments @@ -1080,9 +1080,9 @@ trait ListADMJsonProtocol extends SprayJsonSupport with DefaultJsonProtocol with .stringLiterals .map(_.toJson) ), - "position" -> child.position.toJson, + "position" -> child.position.toJson, "hasRootNode" -> child.hasRootNode.toJson, - "children" -> JsArray(child.children.map(write).toVector) + "children" -> JsArray(child.children.map(write).toVector) ) } @@ -1163,9 +1163,9 @@ trait ListADMJsonProtocol extends SprayJsonSupport with DefaultJsonProtocol with */ def write(element: NodePathElementADM): JsValue = JsObject( - "id" -> element.id.toJson, - "name" -> element.name.toJson, - "labels" -> JsArray(element.labels.stringLiterals.map(_.toJson)), + "id" -> element.id.toJson, + "name" -> element.name.toJson, + "labels" -> JsArray(element.labels.stringLiterals.map(_.toJson)), "comments" -> JsArray(element.comments.stringLiterals.map(_.toJson)) ) @@ -1319,7 +1319,7 @@ trait ListADMJsonProtocol extends SprayJsonSupport with DefaultJsonProtocol with implicit val nodePathGetResponseADMFormat: RootJsonFormat[NodePathGetResponseADM] = jsonFormat(NodePathGetResponseADM, "elements") implicit val listsGetResponseADMFormat: RootJsonFormat[ListsGetResponseADM] = jsonFormat(ListsGetResponseADM, "lists") - implicit val listGetResponseADMFormat: RootJsonFormat[ListGetResponseADM] = jsonFormat(ListGetResponseADM, "list") + implicit val listGetResponseADMFormat: RootJsonFormat[ListGetResponseADM] = jsonFormat(ListGetResponseADM, "list") implicit val listNodeGetResponseADMFormat: RootJsonFormat[ListNodeGetResponseADM] = jsonFormat(ListNodeGetResponseADM, "node") implicit val listInfoGetResponseADMFormat: RootJsonFormat[RootNodeInfoGetResponseADM] = diff --git a/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/permissionsmessages/PermissionsMessagesADM.scala b/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/permissionsmessages/PermissionsMessagesADM.scala index 99f5829cae..feeeba99c7 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/permissionsmessages/PermissionsMessagesADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/permissionsmessages/PermissionsMessagesADM.scala @@ -1203,7 +1203,7 @@ case class ResourceCreateOperation(resourceClass: IRI) extends OperationADM sealed trait PermissionProfileType object PermissionProfileType { case object Restricted extends PermissionProfileType - case object Full extends PermissionProfileType + case object Full extends PermissionProfileType } /** diff --git a/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/permissionsmessages/PermissionsMessagesUtilADM.scala b/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/permissionsmessages/PermissionsMessagesUtilADM.scala index 6409ce96ac..45fccb23f2 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/permissionsmessages/PermissionsMessagesUtilADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/permissionsmessages/PermissionsMessagesUtilADM.scala @@ -27,10 +27,10 @@ object PermissionsMessagesUtilADM { val PermissionTypeAndCodes: Map[String, Int] = Map( RestrictedViewPermission -> 1, - ViewPermission -> 2, - ModifyPermission -> 6, - DeletePermission -> 7, - ChangeRightsPermission -> 8 + ViewPermission -> 2, + ModifyPermission -> 6, + DeletePermission -> 7, + ChangeRightsPermission -> 8 ) //////////////////// diff --git a/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/projectsmessages/ProjectsErrorMessagesADM.scala b/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/projectsmessages/ProjectsErrorMessagesADM.scala index 569a39045c..165b4a3140 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/projectsmessages/ProjectsErrorMessagesADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/projectsmessages/ProjectsErrorMessagesADM.scala @@ -6,18 +6,18 @@ package org.knora.webapi.messages.admin.responder.projectsmessages object ProjectsErrorMessagesADM { - val PROJECT_IRI_MISSING_ERROR = "Project IRI cannot be empty." - val PROJECT_IRI_INVALID_ERROR = "Project IRI is invalid." - val SHORTCODE_MISSING_ERROR = "Shortcode cannot be empty." - val SHORTCODE_INVALID_ERROR = "Shortcode is invalid." - val SHORTNAME_MISSING_ERROR = "Shortname cannot be empty." - val SHORTNAME_INVALID_ERROR = "Shortname is invalid." - val LONGNAME_MISSING_ERROR = "Longname cannot be empty." - val LONGNAME_INVALID_ERROR = "Longname is invalid." + val PROJECT_IRI_MISSING_ERROR = "Project IRI cannot be empty." + val PROJECT_IRI_INVALID_ERROR = "Project IRI is invalid." + val SHORTCODE_MISSING_ERROR = "Shortcode cannot be empty." + val SHORTCODE_INVALID_ERROR = "Shortcode is invalid." + val SHORTNAME_MISSING_ERROR = "Shortname cannot be empty." + val SHORTNAME_INVALID_ERROR = "Shortname is invalid." + val LONGNAME_MISSING_ERROR = "Longname cannot be empty." + val LONGNAME_INVALID_ERROR = "Longname is invalid." val PROJECT_DESCRIPTION_MISSING_ERROR = "Description cannot be empty." val PROJECT_DESCRIPTION_INVALID_ERROR = "Description is invalid." - val KEYWORDS_MISSING_ERROR = "Keywords cannot be empty." - val KEYWORDS_INVALID_ERROR = "Keywords are invalid." - val LOGO_MISSING_ERROR = "Logo cannot be empty." - val LOGO_INVALID_ERROR = "Logo is invalid." + val KEYWORDS_MISSING_ERROR = "Keywords cannot be empty." + val KEYWORDS_INVALID_ERROR = "Keywords are invalid." + val LOGO_MISSING_ERROR = "Logo cannot be empty." + val LOGO_INVALID_ERROR = "Logo is invalid." } diff --git a/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/usersmessages/UsersErrorMessagesADM.scala b/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/usersmessages/UsersErrorMessagesADM.scala index a8a148a700..7c2d1b275c 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/usersmessages/UsersErrorMessagesADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/admin/responder/usersmessages/UsersErrorMessagesADM.scala @@ -6,18 +6,18 @@ package org.knora.webapi.messages.admin.responder.usersmessages object UsersErrorMessagesADM { - val USER_IRI_MISSING_ERROR = "User IRI cannot be empty." - val USER_IRI_INVALID_ERROR = "User IRI is invalid." - val USERNAME_MISSING_ERROR = "Username cannot be empty." - val USERNAME_INVALID_ERROR = "Username is invalid." - val EMAIL_MISSING_ERROR = "Email cannot be empty." - val EMAIL_INVALID_ERROR = "Email is invalid." - val PASSWORD_MISSING_ERROR = "Password cannot be empty." - val PASSWORD_INVALID_ERROR = "Password is invalid." - val GIVEN_NAME_MISSING_ERROR = "GivenName cannot be empty." - val GIVEN_NAME_INVALID_ERROR = "GivenName is invalid." - val FAMILY_NAME_MISSING_ERROR = "FamilyName cannot be empty." - val FAMILY_NAME_INVALID_ERROR = "FamilyName is invalid." + val USER_IRI_MISSING_ERROR = "User IRI cannot be empty." + val USER_IRI_INVALID_ERROR = "User IRI is invalid." + val USERNAME_MISSING_ERROR = "Username cannot be empty." + val USERNAME_INVALID_ERROR = "Username is invalid." + val EMAIL_MISSING_ERROR = "Email cannot be empty." + val EMAIL_INVALID_ERROR = "Email is invalid." + val PASSWORD_MISSING_ERROR = "Password cannot be empty." + val PASSWORD_INVALID_ERROR = "Password is invalid." + val GIVEN_NAME_MISSING_ERROR = "GivenName cannot be empty." + val GIVEN_NAME_INVALID_ERROR = "GivenName is invalid." + val FAMILY_NAME_MISSING_ERROR = "FamilyName cannot be empty." + val FAMILY_NAME_INVALID_ERROR = "FamilyName is invalid." val LANGUAGE_CODE_MISSING_ERROR = "LanguageCode cannot be empty." val LANGUAGE_CODE_INVALID_ERROR = "LanguageCode is invalid." } diff --git a/webapi/src/main/scala/org/knora/webapi/messages/store/triplestoremessages/TriplestoreMessages.scala b/webapi/src/main/scala/org/knora/webapi/messages/store/triplestoremessages/TriplestoreMessages.scala index 686961482f..14005162a0 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/store/triplestoremessages/TriplestoreMessages.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/store/triplestoremessages/TriplestoreMessages.scala @@ -125,7 +125,7 @@ object SparqlExtendedConstructResponse { implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance val statementMap: mutable.Map[SubjectV2, ConstructPredicateObjects] = mutable.Map.empty - val rdfModel: RdfModel = rdfFormatUtil.parseToRdfModel(rdfStr = turtleStr, rdfFormat = Turtle) + val rdfModel: RdfModel = rdfFormatUtil.parseToRdfModel(rdfStr = turtleStr, rdfFormat = Turtle) for (st: Statement <- rdfModel) { val subject: SubjectV2 = st.subj match { @@ -192,7 +192,7 @@ object SparqlExtendedConstructResponse { currentStatementsForSubject.getOrElse(predicateIri, Seq.empty[LiteralV2]) val updatedPredicateStatements = currentStatementsForPredicate :+ objectLiteral - val updatedSubjectStatements = currentStatementsForSubject + (predicateIri -> updatedPredicateStatements) + val updatedSubjectStatements = currentStatementsForSubject + (predicateIri -> updatedPredicateStatements) statementMap += (subject -> updatedSubjectStatements) } @@ -738,7 +738,7 @@ object SparqlResultProtocol extends DefaultJsonProtocol { } implicit val headerFormat: JsonFormat[SparqlSelectResultHeader] = jsonFormat1(SparqlSelectResultHeader) - implicit val responseFormat: JsonFormat[SparqlSelectResult] = jsonFormat2(SparqlSelectResult) + implicit val responseFormat: JsonFormat[SparqlSelectResult] = jsonFormat2(SparqlSelectResult) } /** @@ -759,7 +759,7 @@ trait TriplestoreJsonProtocol extends SprayJsonSupport with DefaultJsonProtocol // have language tag JsObject( Map( - "value" -> string.value.toJson, + "value" -> string.value.toJson, "language" -> string.language.toJson ) ) diff --git a/webapi/src/main/scala/org/knora/webapi/messages/twirl/ResourceHtmlView.scala b/webapi/src/main/scala/org/knora/webapi/messages/twirl/ResourceHtmlView.scala index bafa1edd79..3227f5f265 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/twirl/ResourceHtmlView.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/twirl/ResourceHtmlView.scala @@ -25,7 +25,7 @@ import scala.concurrent.duration.{Duration, SECONDS} object ResourceHtmlView { private implicit val timeout: Timeout = Duration(5, SECONDS) - val log = Logger(LoggerFactory.getLogger("org.knora.webapi.viewhandlers.ResourceHtmlView")) + val log = Logger(LoggerFactory.getLogger("org.knora.webapi.viewhandlers.ResourceHtmlView")) /** * A user representing the Knora API server, used in those cases where a user is required. @@ -90,7 +90,7 @@ object ResourceHtmlView { private def listValue2String(list: HierarchicalListValueV1, responderManager: ActorRef): String = { val resultFuture = responderManager ? NodePathGetRequestV1(list.hierarchicalListIri, systemUser) - val nodePath = Await.result(resultFuture, Duration(3, SECONDS)).asInstanceOf[NodePathGetResponseV1] + val nodePath = Await.result(resultFuture, Duration(3, SECONDS)).asInstanceOf[NodePathGetResponseV1] nodePath.nodelist.foldLeft("") { (z, i) => z + i.label.get + " / " diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/CalendarDateUtilV2.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/CalendarDateUtilV2.scala index 555beb6002..bada28d739 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/CalendarDateUtilV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/CalendarDateUtilV2.scala @@ -343,9 +343,9 @@ object CalendarDateV2 { // Get the year, month, and day from the com.ibm.icu.util.Calendar. // Note: in com.ibm.icu.util.Calendar, month is 0-based. - val year: Int = calendar.get(Calendar.YEAR) + val year: Int = calendar.get(Calendar.YEAR) val month: Int = calendar.get(Calendar.MONTH) + 1 - val day: Int = calendar.get(Calendar.DAY_OF_MONTH) + val day: Int = calendar.get(Calendar.DAY_OF_MONTH) // Return a CalendarDateV2 in the requested precision. precision match { @@ -490,7 +490,7 @@ case class CalendarDateRangeV2(startCalendarDate: CalendarDateV2, endCalendarDat } else { // It's a date range. Use the start JDN of the start date, and the end JDN of the end date. val (startDateStartJDN, _) = startCalendarDate.toJulianDayRange - val (_, endDateEndJDN) = endCalendarDate.toJulianDayRange + val (_, endDateEndJDN) = endCalendarDate.toJulianDayRange (startDateStartJDN, endDateEndJDN) } @@ -515,10 +515,10 @@ object CalendarDateRangeV2 { def parse(dateStr: String): CalendarDateRangeV2 = { // Validate the date string. val stringFormatter = StringFormatter.getGeneralInstance - val validDateStr = stringFormatter.validateDate(dateStr, throw BadRequestException(s"Invalid date: $dateStr")) + val validDateStr = stringFormatter.validateDate(dateStr, throw BadRequestException(s"Invalid date: $dateStr")) // Get the calendar name. - val parsedDate = validDateStr.split(StringFormatter.CalendarSeparator) + val parsedDate = validDateStr.split(StringFormatter.CalendarSeparator) val calendarNameStr: String = parsedDate(0) val calendarName = CalendarNameV2.parse(calendarNameStr, throw BadRequestException(s"Invalid calendar: $calendarNameStr")) diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/ConstructResponseUtilV2.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/ConstructResponseUtilV2.scala index 418d7d2681..b8f48fba76 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/ConstructResponseUtilV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/ConstructResponseUtilV2.scala @@ -949,14 +949,14 @@ object ConstructResponseUtilV2 { for { standoff: Vector[StandoffTagV2] <- StandoffTagUtilV2.createStandoffTagsV2FromConstructResults( - standoffAssertions = valueObject.standoff, - responderManager = responderManager, - requestingUser = requestingUser - ) + standoffAssertions = valueObject.standoff, + responderManager = responderManager, + requestingUser = requestingUser + ) valueHasMaxStandoffStartIndex: Int = valueObject.requireIntObject( - OntologyConstants.KnoraBase.ValueHasMaxStandoffStartIndex.toSmartIri - ) + OntologyConstants.KnoraBase.ValueHasMaxStandoffStartIndex.toSmartIri + ) lastStartIndexQueried = standoff.last.startIndex // Should we get more the rest of the standoff for the same text value? @@ -968,11 +968,11 @@ object ConstructResponseUtilV2 { for { standoffResponse <- (responderManager ? GetRemainingStandoffFromTextValueRequestV2( - resourceIri = resourceIri, - valueIri = valueObject.subjectIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - )).mapTo[GetStandoffResponseV2] + resourceIri = resourceIri, + valueIri = valueObject.subjectIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + )).mapTo[GetStandoffResponseV2] } yield standoff ++ standoffResponse.standoff } else { // We're not supposed to get any more standoff here, either because we have all of it already, @@ -1155,17 +1155,17 @@ object ConstructResponseUtilV2 { // Yes. Construct a ReadResourceV2 representing the nested resource. for { nestedResource <- constructReadResourceV2( - resourceIri = referredResourceIri, - resourceWithValueRdfData = nestedResourceAssertions, - mappings = mappings, - queryStandoff = queryStandoff, - versionDate = versionDate, - responderManager = responderManager, - requestingUser = requestingUser, - targetSchema = targetSchema, - featureFactoryConfig = featureFactoryConfig, - settings = settings - ) + resourceIri = referredResourceIri, + resourceWithValueRdfData = nestedResourceAssertions, + mappings = mappings, + queryStandoff = queryStandoff, + versionDate = versionDate, + responderManager = responderManager, + requestingUser = requestingUser, + targetSchema = targetSchema, + featureFactoryConfig = featureFactoryConfig, + settings = settings + ) } yield linkValue.copy( nestedResource = Some(nestedResource) ) @@ -1339,10 +1339,10 @@ object ConstructResponseUtilV2 { case ApiV2Simple => for { nodeResponse <- (responderManager ? NodeGetRequestV2( - nodeIri = listNodeIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - )).mapTo[NodeGetResponseV2] + nodeIri = listNodeIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + )).mapTo[NodeGetResponseV2] } yield listNode.copy( listNodeLabel = nodeResponse.node .getLabelInPreferredLanguage(userLang = requestingUser.lang, fallbackLang = settings.fallbackLanguage) @@ -1444,7 +1444,7 @@ object ConstructResponseUtilV2 { mayHaveDeletedStatements match { case Some(isDeleted: Boolean) => if (isDeleted) { - val deleteDate = rdfData.requireDateTimeObject(OntologyConstants.KnoraBase.DeleteDate.toSmartIri) + val deleteDate = rdfData.requireDateTimeObject(OntologyConstants.KnoraBase.DeleteDate.toSmartIri) val maybeDeleteComment = rdfData.maybeStringObject(OntologyConstants.KnoraBase.DeleteComment.toSmartIri) Some( @@ -1492,29 +1492,29 @@ object ConstructResponseUtilV2 { .map { valObj: ValueRdfData => for { valueContent: ValueContentV2 <- createValueContentV2FromValueRdfData( - resourceIri = resourceIri, - valueObject = valObj, - mappings = mappings, - queryStandoff = queryStandoff, - responderManager = responderManager, - requestingUser = requestingUser, - targetSchema = targetSchema, - featureFactoryConfig = featureFactoryConfig, - settings = settings - ) + resourceIri = resourceIri, + valueObject = valObj, + mappings = mappings, + queryStandoff = queryStandoff, + responderManager = responderManager, + requestingUser = requestingUser, + targetSchema = targetSchema, + featureFactoryConfig = featureFactoryConfig, + settings = settings + ) attachedToUser = valObj.requireIriObject(OntologyConstants.KnoraBase.AttachedToUser.toSmartIri) - permissions = valObj.requireStringObject(OntologyConstants.KnoraBase.HasPermissions.toSmartIri) + permissions = valObj.requireStringObject(OntologyConstants.KnoraBase.HasPermissions.toSmartIri) valueCreationDate: Instant = valObj.requireDateTimeObject( - OntologyConstants.KnoraBase.ValueCreationDate.toSmartIri - ) + OntologyConstants.KnoraBase.ValueCreationDate.toSmartIri + ) valueDeletionInfo = getDeletionInfo(valObj) valueHasUUID: UUID = stringFormatter.decodeUuid( - valObj.requireStringObject(OntologyConstants.KnoraBase.ValueHasUUID.toSmartIri) - ) + valObj.requireStringObject(OntologyConstants.KnoraBase.ValueHasUUID.toSmartIri) + ) previousValueIri: Option[IRI] = valObj.maybeIriObject( - OntologyConstants.KnoraBase.PreviousValue.toSmartIri - ) + OntologyConstants.KnoraBase.PreviousValue.toSmartIri + ) } yield valueContent match { case linkValueContentV2: LinkValueContentV2 => @@ -1570,11 +1570,12 @@ object ConstructResponseUtilV2 { } for { - projectResponse: ProjectGetResponseADM <- (responderManager ? ProjectGetRequestADM( - identifier = ProjectIdentifierADM(maybeIri = Some(resourceAttachedToProject)), - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - )).mapTo[ProjectGetResponseADM] + projectResponse: ProjectGetResponseADM <- + (responderManager ? ProjectGetRequestADM( + identifier = ProjectIdentifierADM(maybeIri = Some(resourceAttachedToProject)), + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + )).mapTo[ProjectGetResponseADM] valueObjects <- ActorUtil.sequenceSeqFuturesInMap(valueObjectFutures) } yield ReadResourceV2( diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/DateUtilV1.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/DateUtilV1.scala index bd25ab45d0..a431387f77 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/DateUtilV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/DateUtilV1.scala @@ -154,7 +154,7 @@ object DateUtilV1 { 12, 0, 0 - ) // January 1st of the given year. Attention: in java.util.Calendar, month count starts with 0 + ) // January 1st of the given year. Attention: in java.util.Calendar, month count starts with 0 intervalStart.get(0) // call method `get` in order to format the date; if it is invalid an exception is thrown val intervalEnd = new GregorianCalendar @@ -168,7 +168,7 @@ object DateUtilV1 { 12, 0, 0 - ) // December 31st of the given year. Attention: in java.util.Calendar, month count starts with 0 + ) // December 31st of the given year. Attention: in java.util.Calendar, month count starts with 0 intervalEnd.get(0) // call method `get` in order to format the date; if it is invalid an exception is thrown DateRange(intervalStart, intervalEnd, KnoraPrecisionV1.YEAR) @@ -195,7 +195,7 @@ object DateUtilV1 { 12, 0, 0 - ) // Attention: in java.util.Calendar, month count starts with 0; first day of the given month in the given year + ) // Attention: in java.util.Calendar, month count starts with 0; first day of the given month in the given year intervalStart.get(0) // call method `get` in order to format the date; if it is invalid an exception is thrown val intervalEnd = new GregorianCalendar @@ -209,7 +209,7 @@ object DateUtilV1 { 12, 0, 0 - ) // Attention: in java.util.Calendar, month count starts with 0; last day of the given month in the given year + ) // Attention: in java.util.Calendar, month count starts with 0; last day of the given month in the given year intervalEnd.get(0) // call method `get` in order to format the date; if it is invalid an exception is thrown DateRange(intervalStart, intervalEnd, KnoraPrecisionV1.MONTH) @@ -232,7 +232,7 @@ object DateUtilV1 { dateSegments(0).toInt, dateSegments(1).toInt - 1, dateSegments(2).toInt - ) // Attention: in java.util.Calendar, month count starts with 0 + ) // Attention: in java.util.Calendar, month count starts with 0 exactDate.get(0) // call method `get` in order to format the date; if it is invalid an exception is thrown DateRange(exactDate, exactDate, KnoraPrecisionV1.DAY) @@ -280,8 +280,8 @@ object DateUtilV1 { precision: KnoraPrecisionV1.Value ): String = { val gregorianCalendar = convertJulianDayNumberToJavaGregorianCalendar(julianDay, calendarType) - val year = gregorianCalendar.get(Calendar.YEAR) - val month = gregorianCalendar.get(Calendar.MONTH) + 1 + val year = gregorianCalendar.get(Calendar.YEAR) + val month = gregorianCalendar.get(Calendar.MONTH) + 1 // Attention: in java.util.Calendar, month count starts with 0 val day = gregorianCalendar.get(Calendar.DAY_OF_MONTH) val era = eraToString(gregorianCalendar.get(Calendar.ERA)) @@ -324,7 +324,7 @@ object DateUtilV1 { julianDay: Int, calendarType: KnoraCalendarV1.Value ): GregorianCalendar = { - val conv = new JDateTime(julianDay.toDouble) + val conv = new JDateTime(julianDay.toDouble) val gregorianCalendar = new GregorianCalendar // Set the GregorianCalendar object to use the Gregorian calendar or the Julian calendar exclusively, depending on calendarType. @@ -351,17 +351,17 @@ object DateUtilV1 { */ def createJDNValueV1FromDateString(dateStr: String): JulianDayNumberValueV1 = { val stringFormatter = StringFormatter.getGeneralInstance - val datestring = stringFormatter.validateDate(dateStr, throw BadRequestException(s"Invalid date format: $dateStr")) + val datestring = stringFormatter.validateDate(dateStr, throw BadRequestException(s"Invalid date format: $dateStr")) // parse date: Calendar:YYYY-MM-DD[:YYYY-MM-DD] val parsedDate = datestring.split(StringFormatter.CalendarSeparator) - val calendar = KnoraCalendarV1.lookup(parsedDate(0)) + val calendar = KnoraCalendarV1.lookup(parsedDate(0)) if (parsedDate.length > 2) { // it is a period: 0 : cal | 1 : start | 2 : end val start = dateString2DateRange(parsedDate(1), calendar) - val end = dateString2DateRange(parsedDate(2), calendar) + val end = dateString2DateRange(parsedDate(2), calendar) val dateval1 = convertDateToJulianDayNumber(start.start) val dateval2 = convertDateToJulianDayNumber(end.end) diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/FakeTriplestore.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/FakeTriplestore.scala index 651bf5816e..ba5fababd4 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/FakeTriplestore.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/FakeTriplestore.scala @@ -68,7 +68,7 @@ object FakeTriplestore { this.synchronized { log.info("Collecting data for fake triplestore") val paddedQueryNum = f"$queryNum%04d" - val queryDir = fakeTriplestoreDir.get.resolve(paddedQueryNum) + val queryDir = fakeTriplestoreDir.get.resolve(paddedQueryNum) Files.createDirectories(queryDir) val sparqlFile = queryDir.resolve(s"query-$paddedQueryNum.rq") FileUtil.writeTextFile(sparqlFile, sparql) diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/MessageUtil.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/MessageUtil.scala index 28aa43165c..c1e6b8e255 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/MessageUtil.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/MessageUtil.scala @@ -97,7 +97,7 @@ object MessageUtil { // Handle case classes. case caseClass: Product => - val objClass = obj.getClass + val objClass = obj.getClass val objClassName = objClass.getSimpleName val fieldMap: Map[String, Any] = caseClass.getClass.getDeclaredFields.foldLeft(Map[String, Any]()) { @@ -124,12 +124,12 @@ object MessageUtil { case _ => // Generate a named parameter initializer for each of the class's non-method fields. - val objClass = obj.getClass + val objClass = obj.getClass val objClassName = objClass.getSimpleName val runtimeMirror: ru.Mirror = ru.runtimeMirror(objClass.getClassLoader) - val instanceMirror = runtimeMirror.reflect(obj) - val objType: ru.Type = runtimeMirror.classSymbol(objClass).toType + val instanceMirror = runtimeMirror.reflect(obj) + val objType: ru.Type = runtimeMirror.classSymbol(objClass).toType val members: Iterable[String] = objType.members.filter(member => !member.isMethod).flatMap { member => val memberName = member.name.toString.trim @@ -142,7 +142,7 @@ object MessageUtil { case e: Exception => throw new Exception(s"Can't format member $memberName in class $objClassName", e) } - val memberValue = fieldMirror.get + val memberValue = fieldMirror.get val memberValueString = toSource(memberValue) Some(s"$memberName = $memberValueString") } else { diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/PermissionUtilADM.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/PermissionUtilADM.scala index 0f745736e6..cba68ed089 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/PermissionUtilADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/PermissionUtilADM.scala @@ -486,7 +486,7 @@ object PermissionUtilADM extends LazyLogging { logger.debug(s"PermissionUtil.parsePermissionsWithType - split permissions: $permissions") permissions.flatMap { permission => val splitPermission = permission.split(' ') - val abbreviation = splitPermission(0) + val abbreviation = splitPermission(0) permissionType match { case PermissionType.AP => @@ -732,36 +732,38 @@ object PermissionUtilADM extends LazyLogging { for { // Parse the permission literal. - parsedPermissions: Map[PermissionUtilADM.EntityPermission, Set[IRI]] <- Future( - parsePermissions( - permissionLiteral = permissionLiteral, - errorFun = { literal => - throw BadRequestException(s"Invalid permission literal: $literal") - } + parsedPermissions: Map[PermissionUtilADM.EntityPermission, Set[IRI]] <- + Future( + parsePermissions( + permissionLiteral = permissionLiteral, + errorFun = { literal => + throw BadRequestException(s"Invalid permission literal: $literal") + } + ) ) - ) // Get the group IRIs that are mentioned, minus the built-in groups. projectSpecificGroupIris: Set[IRI] = parsedPermissions.values.flatten.toSet -- OntologyConstants.KnoraAdmin.BuiltInGroups - validatedProjectSpecificGroupIris: Set[IRI] = projectSpecificGroupIris.map(iri => - stringFormatter.validateAndEscapeIri(iri, throw BadRequestException(s"Invalid group IRI: $iri")) - ) + validatedProjectSpecificGroupIris: Set[IRI] = + projectSpecificGroupIris.map(iri => + stringFormatter.validateAndEscapeIri(iri, throw BadRequestException(s"Invalid group IRI: $iri")) + ) // Check that those groups exist. _ <- (responderManager ? MultipleGroupsGetRequestADM( - groupIris = validatedProjectSpecificGroupIris, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - )).mapTo[Set[GroupGetResponseADM]] + groupIris = validatedProjectSpecificGroupIris, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + )).mapTo[Set[GroupGetResponseADM]] // Reformat the permission literal. permissionADMs: Set[PermissionADM] = parsedPermissions.flatMap { case (entityPermission, groupIris) => - groupIris.map { groupIri => - entityPermission.toPermissionADM(groupIri) - } - }.toSet + groupIris.map { groupIri => + entityPermission.toPermissionADM(groupIri) + } + }.toSet } yield formatPermissionADMs(permissions = permissionADMs, permissionType = PermissionType.OAP) } diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/UserUtilADM.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/UserUtilADM.scala index de1a080ce0..4ea3469b36 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/UserUtilADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/UserUtilADM.scala @@ -54,11 +54,11 @@ object UserUtilADM { } else { for { userResponse: UserResponseADM <- (responderManager ? UserGetRequestADM( - identifier = UserIdentifierADM(maybeIri = Some(requestedUserIri)), - userInformationTypeADM = UserInformationTypeADM.Full, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - )).mapTo[UserResponseADM] + identifier = UserIdentifierADM(maybeIri = Some(requestedUserIri)), + userInformationTypeADM = UserInformationTypeADM.Full, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + )).mapTo[UserResponseADM] } yield userResponse.user } } diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/ValueUtilV1.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/ValueUtilV1.scala index ba8312125a..a673d8a20e 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/ValueUtilV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/ValueUtilV1.scala @@ -147,34 +147,34 @@ class ValueUtilV1(private val settings: KnoraSettingsImpl) { // A Map of MIME types to Knora API v1 binary format name. private val mimeType2V1Format = new ErrorHandlingMap( Map( - "application/octet-stream" -> "BINARY-UNKNOWN", - "image/jpeg" -> "JPEG", - "image/jp2" -> "JPEG2000", - "image/jpx" -> "JPEG2000", - "application/pdf" -> "PDF", - "application/postscript" -> "POSTSCRIPT", - "application/vnd.ms-powerpoint" -> "PPT", + "application/octet-stream" -> "BINARY-UNKNOWN", + "image/jpeg" -> "JPEG", + "image/jp2" -> "JPEG2000", + "image/jpx" -> "JPEG2000", + "application/pdf" -> "PDF", + "application/postscript" -> "POSTSCRIPT", + "application/vnd.ms-powerpoint" -> "PPT", "application/vnd.openxmlformats-officedocument.presentationml.presentation" -> "PPTX", - "application/rtf" -> "RTF", - "video/salsah" -> "WEBVIDEO", - "text/sgml" -> "SGML", - "image/tiff" -> "TIFF", - "application/msword" -> "WORD", - "application/vnd.openxmlformats-officedocument.wordprocessingml.document" -> "WORDX", - "application/vnd.ms-excel" -> "XLS", - "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" -> "XLSX", - "application/xml" -> "XML", - "text/xml" -> "XML", - "text/csv" -> "CSV", - "text/plain" -> "TEXT", - "application/zip" -> "ZIP", - "application/x-compressed-zip" -> "ZIP", - "audio/mpeg" -> "AUDIO", - "audio/mp4" -> "AUDIO", - "audio/wav" -> "AUDIO", - "audio/x-wav" -> "AUDIO", - "audio/vnd.wave" -> "AUDIO", - "video/mp4" -> "VIDEO" + "application/rtf" -> "RTF", + "video/salsah" -> "WEBVIDEO", + "text/sgml" -> "SGML", + "image/tiff" -> "TIFF", + "application/msword" -> "WORD", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document" -> "WORDX", + "application/vnd.ms-excel" -> "XLS", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" -> "XLSX", + "application/xml" -> "XML", + "text/xml" -> "XML", + "text/csv" -> "CSV", + "text/plain" -> "TEXT", + "application/zip" -> "ZIP", + "application/x-compressed-zip" -> "ZIP", + "audio/mpeg" -> "AUDIO", + "audio/mp4" -> "AUDIO", + "audio/wav" -> "AUDIO", + "audio/x-wav" -> "AUDIO", + "audio/vnd.wave" -> "AUDIO", + "video/mp4" -> "VIDEO" ), { key: String => s"Unknown MIME type: $key" @@ -346,16 +346,16 @@ class ValueUtilV1(private val settings: KnoraSettingsImpl) { } else { for { checkSubClassResponse <- (responderManager ? CheckSubClassRequestV1( - subClassIri = valueType, - superClassIri = propertyObjectClassConstraint, - userProfile = userProfile - )).mapTo[CheckSubClassResponseV1] + subClassIri = valueType, + superClassIri = propertyObjectClassConstraint, + userProfile = userProfile + )).mapTo[CheckSubClassResponseV1] _ = if (!checkSubClassResponse.isSubClass) { - throw OntologyConstraintException( - s"Property $propertyIri requires a value of type $propertyObjectClassConstraint" - ) - } + throw OntologyConstraintException( + s"Property $propertyIri requires a value of type $propertyObjectClassConstraint" + ) + } } yield () } @@ -686,7 +686,7 @@ class ValueUtilV1(private val settings: KnoraSettingsImpl) { timeout: Timeout, executionContext: ExecutionContext ): Future[ApiValueV1] = { - val predicates = valueProps.literalData + val predicates = valueProps.literalData val timeStampStr = predicates(OntologyConstants.KnoraBase.ValueHasTimeStamp).literals.head Future( @@ -734,16 +734,16 @@ class ValueUtilV1(private val settings: KnoraSettingsImpl) { // get the mapping and the related standoff entities // v2 responder is used here directly, v1 responder would inernally use v2 responder anyway and do unnecessary back and forth conversions mappingResponse: GetMappingResponseV2 <- (responderManager ? GetMappingRequestV2( - mappingIri = mappingIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = userProfile - )).mapTo[GetMappingResponseV2] + mappingIri = mappingIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = userProfile + )).mapTo[GetMappingResponseV2] standoffTags: Seq[StandoffTagV2] <- StandoffTagUtilV2.createStandoffTagsV2FromSelectResults( - standoffAssertions = valueProps.standoff, - responderManager = responderManager, - requestingUser = userProfile - ) + standoffAssertions = valueProps.standoff, + responderManager = responderManager, + requestingUser = userProfile + ) } yield TextValueWithStandoffV1( utf8str = utf8str, diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/JsonLDUtil.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/JsonLDUtil.scala index 12d56bf0de..9ced9b6276 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/JsonLDUtil.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/JsonLDUtil.scala @@ -1117,7 +1117,7 @@ case class JsonLDDocument( this } - val bodyAsTitaniumJsonDocument: JsonDocument = JsonDocument.of(documentFlattenedIfRequested.body.toJavaxJsonValue) + val bodyAsTitaniumJsonDocument: JsonDocument = JsonDocument.of(documentFlattenedIfRequested.body.toJavaxJsonValue) val contextAsTitaniumJsonDocument: JsonDocument = JsonDocument.of(context.toJavaxJsonValue) JsonLd.compact(bodyAsTitaniumJsonDocument, contextAsTitaniumJsonDocument).get } @@ -1137,7 +1137,7 @@ case class JsonLDDocument( } val stringWriter = new StringWriter() - val jsonWriter = jsonWriterFactory.createWriter(stringWriter) + val jsonWriter = jsonWriterFactory.createWriter(stringWriter) jsonWriter.write(javaxJsonObject) jsonWriter.close() stringWriter.toString @@ -1163,7 +1163,7 @@ case class JsonLDDocument( * @return the formatted document. */ def toCompactString(flatten: Boolean = false): String = { - val config = new util.HashMap[String, Boolean]() + val config = new util.HashMap[String, Boolean]() val jsonWriterFactory: JsonWriterFactory = Json.createWriterFactory(config) formatWithJsonWriterFactory(jsonWriterFactory = jsonWriterFactory, flatten = flatten) } @@ -1175,7 +1175,7 @@ case class JsonLDDocument( */ def toRdfModel(modelFactory: RdfModelFactory): RdfModel = { implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - val model: RdfModel = modelFactory.makeEmptyModel + val model: RdfModel = modelFactory.makeEmptyModel // Add the prefixes and namespaces from the JSON-LD context to the model. for ((prefix: String, namespaceValue: JsonLDValue) <- context.value) { @@ -1281,7 +1281,7 @@ object JsonLDUtil { def objectWithLangToJsonLDObject(obj: String, lang: String): JsonLDObject = JsonLDObject( Map( - JsonLDKeywords.VALUE -> JsonLDString(obj), + JsonLDKeywords.VALUE -> JsonLDString(obj), JsonLDKeywords.LANGUAGE -> JsonLDString(lang) ) ) @@ -1305,7 +1305,7 @@ object JsonLDUtil { JsonLDObject( Map( JsonLDKeywords.VALUE -> JsonLDString(strValue), - JsonLDKeywords.TYPE -> JsonLDString(datatype.toString) + JsonLDKeywords.TYPE -> JsonLDString(datatype.toString) ) ) } @@ -1338,15 +1338,15 @@ object JsonLDUtil { */ def parseJsonLD(jsonLDString: String, flatten: Boolean = false): JsonLDDocument = { // Parse the string into a jakarta.json.JsonStructure. - val stringReader = new StringReader(jsonLDString) - val jsonReader: JsonReader = Json.createReader(stringReader) + val stringReader = new StringReader(jsonLDString) + val jsonReader: JsonReader = Json.createReader(stringReader) val jsonStructure: JsonStructure = jsonReader.read() // Convert the JsonStructure to a Titanium JsonDocument. val titaniumDocument: JsonDocument = JsonDocument.of(jsonStructure) // Use Titanium to compact the document with an empty context. - val emptyContext = JsonDocument.of(Json.createObjectBuilder().build()) + val emptyContext = JsonDocument.of(Json.createObjectBuilder().build()) val compactedJsonObject: JsonObject = JsonLd.compact(titaniumDocument, emptyContext).get // Convert the resulting jakarta.json.JsonObject to a JsonLDDocument. @@ -1531,7 +1531,7 @@ object JsonLDUtil { // Make JSON-LD content representing the predicates and their objects. val predsAndObjs: Map[IRI, JsonLDValue] = groupedByPred.keySet.map { pred: IriNode => val predStatements: Set[Statement] = groupedByPred(pred) - val predIri: IRI = pred.iri + val predIri: IRI = pred.iri // Is the predicate rdf:type? val (jsonLDKey: String, jsonLDObjs: Vector[JsonLDValue]) = if (predIri == OntologyConstants.Rdf.Type) { @@ -1593,7 +1593,7 @@ object JsonLDUtil { case datatypeLiteral: DatatypeLiteral => // Is there a native JSON-LD type for this literal? - val datatypeIri: IRI = datatypeLiteral.datatype + val datatypeIri: IRI = datatypeLiteral.datatype val datatypeValue: String = datatypeLiteral.value datatypeIri match { diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/RdfFeatureFactory.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/RdfFeatureFactory.scala index b260f5e48d..59f2f5a8ed 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/RdfFeatureFactory.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/RdfFeatureFactory.scala @@ -22,15 +22,15 @@ object RdfFeatureFactory extends FeatureFactory { private val JENA_TOGGLE_NAME = "jena-rdf-library" // Jena singletons. - private val jenaNodeFactory = new JenaNodeFactory - private val jenaModelFactory = new JenaModelFactory(jenaNodeFactory) - private val jenaFormatUtil = new JenaFormatUtil(modelFactory = jenaModelFactory, nodeFactory = jenaNodeFactory) + private val jenaNodeFactory = new JenaNodeFactory + private val jenaModelFactory = new JenaModelFactory(jenaNodeFactory) + private val jenaFormatUtil = new JenaFormatUtil(modelFactory = jenaModelFactory, nodeFactory = jenaNodeFactory) private var jenaShaclValidator: Option[JenaShaclValidator] = None // RDF4J singletons. - private val rdf4jNodeFactory = new RDF4JNodeFactory - private val rdf4jModelFactory = new RDF4JModelFactory(rdf4jNodeFactory) - private val rdf4jFormatUtil = new RDF4JFormatUtil(modelFactory = rdf4jModelFactory, nodeFactory = rdf4jNodeFactory) + private val rdf4jNodeFactory = new RDF4JNodeFactory + private val rdf4jModelFactory = new RDF4JModelFactory(rdf4jNodeFactory) + private val rdf4jFormatUtil = new RDF4JFormatUtil(modelFactory = rdf4jModelFactory, nodeFactory = rdf4jNodeFactory) private var rdf4jShaclValidator: Option[RDF4JShaclValidator] = None /** diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/jenaimpl/JenaFormatUtil.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/jenaimpl/JenaFormatUtil.scala index da8b439b4c..db5a415019 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/jenaimpl/JenaFormatUtil.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/jenaimpl/JenaFormatUtil.scala @@ -89,7 +89,7 @@ class JenaFormatUtil(private val modelFactory: JenaModelFactory, private val nod import JenaConversions._ val datasetGraph: jena.sparql.core.DatasetGraph = rdfModel.asJenaDataset.asDatasetGraph - val stringWriter: StringWriter = new StringWriter + val stringWriter: StringWriter = new StringWriter rdfFormat match { case Turtle => diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/jenaimpl/JenaModel.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/jenaimpl/JenaModel.scala index 19363eafc2..c4a7a95695 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/jenaimpl/JenaModel.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/jenaimpl/JenaModel.scala @@ -257,7 +257,7 @@ class JenaModel(private val dataset: jena.query.Dataset, private val nodeFactory // Get the namespaces used in all the named graphs in the dataset. val namedGraphNamespaces: Map[String, IRI] = datasetGraph.listGraphNodes.asScala.flatMap { graphNode: jena.graph.Node => - val graph: jena.graph.Graph = datasetGraph.getGraph(graphNode) + val graph: jena.graph.Graph = datasetGraph.getGraph(graphNode) val prefixMapping: jena.shared.PrefixMapping = graph.getPrefixMapping prefixMapping.getNsPrefixMap.asScala }.toMap @@ -410,12 +410,12 @@ class JenaRepository(private val dataset: jena.query.Dataset) extends RdfReposit // Convert the query result to a SparqlSelectResponse. - val header = SparqlSelectResultHeader(resultSet.getResultVars.asScala.toSeq) + val header = SparqlSelectResultHeader(resultSet.getResultVars.asScala.toSeq) val rowBuffer = ArrayBuffer.empty[VariableResultsRow] while (resultSet.hasNext) { val querySolution: jena.query.QuerySolution = resultSet.next - val varNames: Iterator[String] = querySolution.varNames.asScala + val varNames: Iterator[String] = querySolution.varNames.asScala val rowMap: Map[String, String] = varNames.map { varName => val varValue: jena.graph.Node = querySolution.get(varName).asNode diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/rdf4jimpl/RDF4JFormatUtil.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/rdf4jimpl/RDF4JFormatUtil.scala index f890ae03fe..95fa46f321 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/rdf4jimpl/RDF4JFormatUtil.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/rdf4jimpl/RDF4JFormatUtil.scala @@ -80,7 +80,7 @@ class RDF4JFormatUtil(private val modelFactory: RDF4JModelFactory, private val n override def formatNonJsonLD(rdfModel: RdfModel, rdfFormat: NonJsonLD, prettyPrint: Boolean): String = { import RDF4JConversions._ - val stringWriter = new StringWriter + val stringWriter = new StringWriter val rdfWriter: rdf4j.rio.RDFWriter = rdf4j.rio.Rio.createWriter(rdfFormatToRDF4JFormat(rdfFormat), stringWriter) if (prettyPrint && rdfFormat.supportsPrettyPrinting) { diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/rdf4jimpl/RDF4JModel.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/rdf4jimpl/RDF4JModel.scala index 513516716c..146a05a527 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/rdf4jimpl/RDF4JModel.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/rdf4jimpl/RDF4JModel.scala @@ -356,13 +356,13 @@ class RDF4JRepository(model: rdf4j.model.Model) extends RdfRepository { override def doSelect(selectQuery: String): SparqlSelectResult = { // Run the query. - val connection = repository.getConnection - val tupleQuery: rdf4j.query.TupleQuery = connection.prepareTupleQuery(selectQuery) + val connection = repository.getConnection + val tupleQuery: rdf4j.query.TupleQuery = connection.prepareTupleQuery(selectQuery) val tupleQueryResult: rdf4j.query.TupleQueryResult = tupleQuery.evaluate // Convert the query result to a SparqlSelectResponse. - val header = SparqlSelectResultHeader(tupleQueryResult.getBindingNames.asScala.toSeq) + val header = SparqlSelectResultHeader(tupleQueryResult.getBindingNames.asScala.toSeq) val rowBuffer = ArrayBuffer.empty[VariableResultsRow] while (tupleQueryResult.hasNext) { diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/rdf4jimpl/RDF4JShaclValidator.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/rdf4jimpl/RDF4JShaclValidator.scala index 836ff28c37..0972a63cf9 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/rdf4jimpl/RDF4JShaclValidator.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/rdf/rdf4jimpl/RDF4JShaclValidator.scala @@ -26,7 +26,7 @@ class RDF4JShaclValidator(baseDir: Path, rdfFormatUtil: RDF4JFormatUtil, private override def validateWithShaclGraph(rdfModel: RdfModel, shaclGraph: rdf4j.model.Model): ShaclValidationResult = { // Make a SailRepository repository that supports SHACL validation. - val shaclSail = new rdf4j.sail.shacl.ShaclSail(new rdf4j.sail.memory.MemoryStore()) + val shaclSail = new rdf4j.sail.shacl.ShaclSail(new rdf4j.sail.memory.MemoryStore()) val repository = new rdf4j.repository.sail.SailRepository(shaclSail) // Open a connection to the repository and begin a transaction. diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/GravsearchParser.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/GravsearchParser.scala index 934065634a..12e718feba 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/GravsearchParser.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/GravsearchParser.scala @@ -29,7 +29,7 @@ import scala.jdk.CollectionConverters._ */ object GravsearchParser { // This implementation uses the RDF4J SPARQL parser. - private val sparqlParserFactory = new SPARQLParserFactory() + private val sparqlParserFactory = new SPARQLParserFactory() private val sparqlParser: QueryParser = sparqlParserFactory.getParser /** @@ -252,7 +252,7 @@ object GravsearchParser { override def meet(node: algebra.StatementPattern): Unit = { val subj: Entity = makeEntityFromVar(node.getSubjectVar) val pred: Entity = makeEntityFromVar(node.getPredicateVar) - val obj: Entity = makeEntityFromVar(node.getObjectVar) + val obj: Entity = makeEntityFromVar(node.getObjectVar) if (Option(node.getContextVar).nonEmpty) { throw GravsearchException("Named graphs are not supported in search queries") @@ -355,7 +355,7 @@ object GravsearchParser { var subj: Option[String] = None var pred: Option[String] = None - var obj: Option[String] = None + var obj: Option[String] = None for (projectionElem: algebra.ProjectionElem <- node.getElements.asScala) { val sourceName: String = projectionElem.getSourceName @@ -396,7 +396,7 @@ object GravsearchParser { override def meet(node: algebra.Order): Unit = { for (orderElem: algebra.OrderElem <- node.getElements.asScala) { val expression: algebra.ValueExpr = orderElem.getExpr - val ascending = orderElem.isAscending + val ascending = orderElem.isAscending val queryVariable: QueryVariable = expression match { case objVar: algebra.Var => @@ -475,7 +475,7 @@ object GravsearchParser { // It's a BIND. Accept it if it refers to a Knora data IRI. valueConstant.getValue match { case iri: rdf4j.model.IRI => - val variable = makeQueryVariable(node.getName) + val variable = makeQueryVariable(node.getName) val iriValue: IriRef = makeIri(iri) if (!iriValue.iri.isKnoraDataIri) { @@ -580,7 +580,7 @@ object GravsearchParser { private def makeFilterExpression(valueExpr: algebra.ValueExpr): Expression = { valueExpr match { case compare: algebra.Compare => - val leftArg = makeFilterExpression(compare.getLeftArg) + val leftArg = makeFilterExpression(compare.getLeftArg) val rightArg = makeFilterExpression(compare.getRightArg) val operator = compare.getOperator.getSymbol @@ -594,7 +594,7 @@ object GravsearchParser { ) case and: algebra.And => - val leftArg = makeFilterExpression(and.getLeftArg) + val leftArg = makeFilterExpression(and.getLeftArg) val rightArg = makeFilterExpression(and.getRightArg) AndExpression( @@ -603,7 +603,7 @@ object GravsearchParser { ) case or: algebra.Or => - val leftArg = makeFilterExpression(or.getLeftArg) + val leftArg = makeFilterExpression(or.getLeftArg) val rightArg = makeFilterExpression(or.getRightArg) OrExpression( diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/prequery/AbstractPrequeryGenerator.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/prequery/AbstractPrequeryGenerator.scala index b30185f250..1573043dbd 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/prequery/AbstractPrequeryGenerator.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/prequery/AbstractPrequeryGenerator.scala @@ -679,20 +679,20 @@ abstract class AbstractPrequeryGenerator( // that point to literals. This is used only for generating additional statements for ORDER BY clauses, so it only needs to include // types that have a meaningful order. private val valueTypesToValuePredsForOrderBy: Map[IRI, IRI] = Map( - OntologyConstants.Xsd.Integer -> OntologyConstants.KnoraBase.ValueHasInteger, - OntologyConstants.Xsd.Decimal -> OntologyConstants.KnoraBase.ValueHasDecimal, - OntologyConstants.Xsd.Boolean -> OntologyConstants.KnoraBase.ValueHasBoolean, - OntologyConstants.Xsd.String -> OntologyConstants.KnoraBase.ValueHasString, - OntologyConstants.KnoraApiV2Simple.Date -> OntologyConstants.KnoraBase.ValueHasStartJDN, - OntologyConstants.KnoraApiV2Simple.Color -> OntologyConstants.KnoraBase.ValueHasColor, - OntologyConstants.KnoraApiV2Simple.Geoname -> OntologyConstants.KnoraBase.ValueHasGeonameCode, - OntologyConstants.KnoraApiV2Complex.TextValue -> OntologyConstants.KnoraBase.ValueHasString, - OntologyConstants.KnoraApiV2Complex.IntValue -> OntologyConstants.KnoraBase.ValueHasInteger, + OntologyConstants.Xsd.Integer -> OntologyConstants.KnoraBase.ValueHasInteger, + OntologyConstants.Xsd.Decimal -> OntologyConstants.KnoraBase.ValueHasDecimal, + OntologyConstants.Xsd.Boolean -> OntologyConstants.KnoraBase.ValueHasBoolean, + OntologyConstants.Xsd.String -> OntologyConstants.KnoraBase.ValueHasString, + OntologyConstants.KnoraApiV2Simple.Date -> OntologyConstants.KnoraBase.ValueHasStartJDN, + OntologyConstants.KnoraApiV2Simple.Color -> OntologyConstants.KnoraBase.ValueHasColor, + OntologyConstants.KnoraApiV2Simple.Geoname -> OntologyConstants.KnoraBase.ValueHasGeonameCode, + OntologyConstants.KnoraApiV2Complex.TextValue -> OntologyConstants.KnoraBase.ValueHasString, + OntologyConstants.KnoraApiV2Complex.IntValue -> OntologyConstants.KnoraBase.ValueHasInteger, OntologyConstants.KnoraApiV2Complex.DecimalValue -> OntologyConstants.KnoraBase.ValueHasDecimal, - OntologyConstants.KnoraApiV2Complex.TimeValue -> OntologyConstants.KnoraBase.ValueHasTimeStamp, + OntologyConstants.KnoraApiV2Complex.TimeValue -> OntologyConstants.KnoraBase.ValueHasTimeStamp, OntologyConstants.KnoraApiV2Complex.BooleanValue -> OntologyConstants.KnoraBase.ValueHasBoolean, - OntologyConstants.KnoraApiV2Complex.DateValue -> OntologyConstants.KnoraBase.ValueHasStartJDN, - OntologyConstants.KnoraApiV2Complex.ColorValue -> OntologyConstants.KnoraBase.ValueHasColor, + OntologyConstants.KnoraApiV2Complex.DateValue -> OntologyConstants.KnoraBase.ValueHasStartJDN, + OntologyConstants.KnoraApiV2Complex.ColorValue -> OntologyConstants.KnoraBase.ValueHasColor, OntologyConstants.KnoraApiV2Complex.GeonameValue -> OntologyConstants.KnoraBase.ValueHasGeonameCode ) @@ -1704,7 +1704,7 @@ abstract class AbstractPrequeryGenerator( val standoffTagVar: QueryVariable = functionCallExpression.getArgAsQueryVar(pos = 1) val startVariable = QueryVariable(standoffTagVar.variableName + "__start") - val endVariable = QueryVariable(standoffTagVar.variableName + "__end") + val endVariable = QueryVariable(standoffTagVar.variableName + "__end") val markedUpPatternsToAdd: Seq[QueryPattern] = if (!standoffMarkedUpVariables.contains(startVariable)) { standoffMarkedUpVariables += startVariable diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/prequery/GravsearchQueryOptimisationFactory.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/prequery/GravsearchQueryOptimisationFactory.scala index 9b3c8adc87..110393fafd 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/prequery/GravsearchQueryOptimisationFactory.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/prequery/GravsearchQueryOptimisationFactory.scala @@ -266,8 +266,8 @@ class ReorderPatternsByDependencyOptimisationFeature( val cycle: graph.Cycle = graph.findCycle.get // the cyclic node is the one that cycle starts and ends with - val cyclicNode: graph.NodeT = cycle.endNode - val cyclicEdge: graph.EdgeT = cyclicNode.edges.last + val cyclicNode: graph.NodeT = cycle.endNode + val cyclicEdge: graph.EdgeT = cyclicNode.edges.last val originNodeOfCyclicEdge: String = cyclicEdge._1.value val TargetNodeOfCyclicEdge: String = cyclicEdge._2.value val graphComponentsWithOutCycle = diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/prequery/TopologicalSortUtil.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/prequery/TopologicalSortUtil.scala index 3dd050e17f..ef8fb34587 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/prequery/TopologicalSortUtil.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/prequery/TopologicalSortUtil.scala @@ -41,7 +41,7 @@ object TopologicalSortUtil { * @return a list of all permutations of topological order. */ def findPermutations(layeredOrder: graph.LayeredTopologicalOrder[NodeT]): List[Vector[NodeT]] = { - val lastLayerNodes: Vector[NodeT] = layeredOrder.last._2.toVector + val lastLayerNodes: Vector[NodeT] = layeredOrder.last._2.toVector val allLowerLayers: Iterable[(Int, Iterable[NodeT])] = layeredOrder.dropRight(1) // Find all permutations of last layer nodes; i.e leaf nodes. diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/AnnotationReadingGravsearchTypeInspector.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/AnnotationReadingGravsearchTypeInspector.scala index 2015e411bf..c6d63c506b 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/AnnotationReadingGravsearchTypeInspector.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/AnnotationReadingGravsearchTypeInspector.scala @@ -58,53 +58,58 @@ class AnnotationReadingGravsearchTypeInspector( for { // Get all the type annotations. typeAnnotations: Seq[GravsearchTypeAnnotation] <- Future { - QueryTraverser.visitWherePatterns( - patterns = whereClause.patterns, - whereVisitor = new AnnotationCollectingWhereVisitor( - whereClause.querySchema.getOrElse(throw AssertionException(s"WhereClause has no querySchema")) - ), - initialAcc = Vector.empty[GravsearchTypeAnnotation] - ) - } + QueryTraverser.visitWherePatterns( + patterns = whereClause.patterns, + whereVisitor = new AnnotationCollectingWhereVisitor( + whereClause.querySchema.getOrElse( + throw AssertionException( + s"WhereClause has no querySchema" + ) + ) + ), + initialAcc = Vector.empty[GravsearchTypeAnnotation] + ) + } // Collect the information in the type annotations. - intermediateResult: IntermediateTypeInspectionResult = typeAnnotations.foldLeft(previousResult) { - case (acc: IntermediateTypeInspectionResult, typeAnnotation: GravsearchTypeAnnotation) => - typeAnnotation.annotationProp match { - case TypeAnnotationProperties.RdfType => - val isResource = - OntologyConstants.KnoraApi.KnoraApiV2ResourceIris.contains(typeAnnotation.typeIri.toString) - val isValue = - GravsearchTypeInspectionUtil.GravsearchValueTypeIris.contains(typeAnnotation.typeIri.toString) - acc.addTypes( - typeAnnotation.typeableEntity, - Set(NonPropertyTypeInfo(typeAnnotation.typeIri, isResourceType = isResource, isValueType = isValue)) - ) - - case TypeAnnotationProperties.ObjectType => - val isResource = - OntologyConstants.KnoraApi.KnoraApiV2ResourceIris.contains(typeAnnotation.typeIri.toString) - val isValue = - GravsearchTypeInspectionUtil.GravsearchValueTypeIris.contains(typeAnnotation.typeIri.toString) - acc.addTypes( - typeAnnotation.typeableEntity, - Set( - PropertyTypeInfo( - typeAnnotation.typeIri, - objectIsResourceType = isResource, - objectIsValueType = isValue + intermediateResult: IntermediateTypeInspectionResult = + typeAnnotations.foldLeft(previousResult) { + case (acc: IntermediateTypeInspectionResult, typeAnnotation: GravsearchTypeAnnotation) => + typeAnnotation.annotationProp match { + case TypeAnnotationProperties.RdfType => + val isResource = + OntologyConstants.KnoraApi.KnoraApiV2ResourceIris.contains(typeAnnotation.typeIri.toString) + val isValue = + GravsearchTypeInspectionUtil.GravsearchValueTypeIris.contains(typeAnnotation.typeIri.toString) + acc.addTypes( + typeAnnotation.typeableEntity, + Set(NonPropertyTypeInfo(typeAnnotation.typeIri, isResourceType = isResource, isValueType = isValue)) + ) + + case TypeAnnotationProperties.ObjectType => + val isResource = + OntologyConstants.KnoraApi.KnoraApiV2ResourceIris.contains(typeAnnotation.typeIri.toString) + val isValue = + GravsearchTypeInspectionUtil.GravsearchValueTypeIris.contains(typeAnnotation.typeIri.toString) + acc.addTypes( + typeAnnotation.typeableEntity, + Set( + PropertyTypeInfo( + typeAnnotation.typeIri, + objectIsResourceType = isResource, + objectIsValueType = isValue + ) ) ) - ) - } - } + } + } // Pass the intermediate result to the next type inspector in the pipeline. lastResult: IntermediateTypeInspectionResult <- runNextInspector( - intermediateResult = intermediateResult, - whereClause = whereClause, - requestingUser = requestingUser - ) + intermediateResult = intermediateResult, + whereClause = whereClause, + requestingUser = requestingUser + ) } yield lastResult /** diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/GravsearchTypeInspectionRunner.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/GravsearchTypeInspectionRunner.scala index a069f6fa29..b93b6ebf9e 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/GravsearchTypeInspectionRunner.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/GravsearchTypeInspectionRunner.scala @@ -56,22 +56,22 @@ class GravsearchTypeInspectionRunner(responderData: ResponderData, inferTypes: B for { // Get the set of typeable entities in the Gravsearch query. typeableEntities: Set[TypeableEntity] <- Future { - QueryTraverser.visitWherePatterns( - patterns = whereClause.patterns, - whereVisitor = new TypeableEntityCollectingWhereVisitor, - initialAcc = Set.empty[TypeableEntity] - ) - } + QueryTraverser.visitWherePatterns( + patterns = whereClause.patterns, + whereVisitor = new TypeableEntityCollectingWhereVisitor, + initialAcc = Set.empty[TypeableEntity] + ) + } // In the initial intermediate result, none of the entities have types yet. initialResult: IntermediateTypeInspectionResult = IntermediateTypeInspectionResult(typeableEntities) // Run the pipeline and get its result. lastResult: IntermediateTypeInspectionResult <- typeInspectionPipeline.inspectTypes( - previousResult = initialResult, - whereClause = whereClause, - requestingUser = requestingUser - ) + previousResult = initialResult, + whereClause = whereClause, + requestingUser = requestingUser + ) // Are any entities still untyped? untypedEntities: Set[TypeableEntity] = lastResult.untypedEntities diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/GravsearchTypeInspectionUtil.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/GravsearchTypeInspectionUtil.scala index ee1356c817..4e0d198eb6 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/GravsearchTypeInspectionUtil.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/GravsearchTypeInspectionUtil.scala @@ -36,8 +36,8 @@ object GravsearchTypeInspectionUtil { case object ObjectType extends TypeAnnotationProperty private val valueMap = Map( - OntologyConstants.Rdf.Type -> RdfType, - OntologyConstants.KnoraApiV2Simple.ObjectType -> ObjectType, + OntologyConstants.Rdf.Type -> RdfType, + OntologyConstants.KnoraApiV2Simple.ObjectType -> ObjectType, OntologyConstants.KnoraApiV2Complex.ObjectType -> ObjectType ) diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/GravsearchTypeInspector.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/GravsearchTypeInspector.scala index 07153f2bab..c9887754bf 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/GravsearchTypeInspector.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/GravsearchTypeInspector.scala @@ -27,7 +27,7 @@ abstract class GravsearchTypeInspector( responderData: ResponderData ) { - protected val system: ActorSystem = responderData.system + protected val system: ActorSystem = responderData.system protected val settings: KnoraSettingsImpl = KnoraSettings(system) protected implicit val executionContext: ExecutionContext = system.dispatchers.lookup(KnoraDispatchers.KnoraActorDispatcher) diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/InferringGravsearchTypeInspector.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/InferringGravsearchTypeInspector.scala index 385d78fda2..34c54a9c3b 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/InferringGravsearchTypeInspector.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/search/gravsearch/types/InferringGravsearchTypeInspector.scala @@ -507,9 +507,9 @@ class InferringGravsearchTypeInspector(nextInspector: Option[GravsearchTypeInspe case Some(typesFromFilters: Set[SmartIri]) => // Yes. Return those types. typesFromFilters.map { typeFromFilter: SmartIri => - val isValueType = GravsearchTypeInspectionUtil.GravsearchValueTypeIris.contains(typeFromFilter.toString) + val isValueType = GravsearchTypeInspectionUtil.GravsearchValueTypeIris.contains(typeFromFilter.toString) val isStandoffTagType = typeFromFilter.toString == OntologyConstants.KnoraApiV2Complex.StandoffTag - val isResourceType = !(isValueType || isStandoffTagType) + val isResourceType = !(isValueType || isStandoffTagType) val inferredType = NonPropertyTypeInfo( typeFromFilter, isResourceType = isResourceType, @@ -853,31 +853,31 @@ class InferringGravsearchTypeInspector(nextInspector: Option[GravsearchTypeInspe // Iterate over the inference rules until no new type information can be inferred. intermediateResult: IntermediateTypeInspectionResult = doIterations( - iterationNumber = 1, - intermediateResult = previousResult, - entityInfo = allEntityInfo, - usageIndex = usageIndex - ) + iterationNumber = 1, + intermediateResult = previousResult, + entityInfo = allEntityInfo, + usageIndex = usageIndex + ) // refine the determined types before sending to the next inspector refinedIntermediateResult: IntermediateTypeInspectionResult = refineDeterminedTypes( - intermediateResult = intermediateResult, - entityInfo = allEntityInfo - ) + intermediateResult = intermediateResult, + entityInfo = allEntityInfo + ) // sanitize the inconsistent resource types inferred for an entity sanitizedResults: IntermediateTypeInspectionResult = sanitizeInconsistentResourceTypes( - refinedIntermediateResult, - usageIndex.querySchema, - entityInfo = allEntityInfo - ) + refinedIntermediateResult, + usageIndex.querySchema, + entityInfo = allEntityInfo + ) // Pass the intermediate result to the next type inspector in the pipeline. lastResult: IntermediateTypeInspectionResult <- runNextInspector( - intermediateResult = sanitizedResults, - whereClause = whereClause, - requestingUser = requestingUser - ) + intermediateResult = sanitizedResults, + whereClause = whereClause, + requestingUser = requestingUser + ) } yield lastResult } @@ -899,73 +899,83 @@ class InferringGravsearchTypeInspector(nextInspector: Option[GravsearchTypeInspe // Ask the ontology responder about all the Knora class and property IRIs mentioned in the query. initialEntityInfoRequest = EntityInfoGetRequestV2( - classIris = usageIndex.knoraClassIris, - propertyIris = usageIndex.knoraPropertyIris, - requestingUser = requestingUser - ) + classIris = usageIndex.knoraClassIris, + propertyIris = usageIndex.knoraPropertyIris, + requestingUser = requestingUser + ) initialEntityInfo: EntityInfoGetResponseV2 <- (responderManager ? initialEntityInfoRequest) - .mapTo[EntityInfoGetResponseV2] + .mapTo[EntityInfoGetResponseV2] // The ontology responder may return the requested information in the internal schema. Convert each entity // definition back to the input schema. initialEntityInfoInInputSchemas: EntityInfoGetResponseV2 = convertEntityInfoResponseToInputSchemas( - usageIndex = usageIndex, - entityInfo = initialEntityInfo - ) + usageIndex = usageIndex, + entityInfo = initialEntityInfo + ) // Ask the ontology responder about all the Knora classes mentioned as subject or object types of the // properties returned. subjectAndObjectTypes: Set[SmartIri] = initialEntityInfoInInputSchemas.propertyInfoMap.foldLeft( - Set.empty[SmartIri] - ) { case (acc, (propertyIri, propertyDef)) => - val propertyIriSchema = propertyIri.getOntologySchema match { - case Some(apiV2Schema: ApiV2Schema) => apiV2Schema - case other => throw AssertionException(s"Expected an ApiV2Schema, got $other") - } - - val maybeSubjectType: Option[SmartIri] = propertyDef.entityInfoContent.getPredicateIriObject( - OntologyConstants.KnoraApi.getSubjectTypePredicate(propertyIriSchema).toSmartIri - ) match { - case Some(subjectType) if subjectType.isKnoraEntityIri => Some(subjectType) - case _ => None - } - - val maybeObjectType: Option[SmartIri] = propertyDef.entityInfoContent.getPredicateIriObject( - OntologyConstants.KnoraApi.getObjectTypePredicate(propertyIriSchema).toSmartIri - ) match { - case Some(objectType) if objectType.isKnoraEntityIri => Some(objectType) - case _ => None - } - - acc ++ maybeSubjectType ++ maybeObjectType - } + Set.empty[SmartIri] + ) { case (acc, (propertyIri, propertyDef)) => + val propertyIriSchema = propertyIri.getOntologySchema match { + case Some(apiV2Schema: ApiV2Schema) => apiV2Schema + case other => + throw AssertionException(s"Expected an ApiV2Schema, got $other") + } + + val maybeSubjectType: Option[SmartIri] = + propertyDef.entityInfoContent.getPredicateIriObject( + OntologyConstants.KnoraApi + .getSubjectTypePredicate(propertyIriSchema) + .toSmartIri + ) match { + case Some(subjectType) if subjectType.isKnoraEntityIri => + Some(subjectType) + case _ => None + } + + val maybeObjectType: Option[SmartIri] = + propertyDef.entityInfoContent.getPredicateIriObject( + OntologyConstants.KnoraApi + .getObjectTypePredicate(propertyIriSchema) + .toSmartIri + ) match { + case Some(objectType) if objectType.isKnoraEntityIri => + Some(objectType) + case _ => None + } + + acc ++ maybeSubjectType ++ maybeObjectType + } additionalEntityInfoRequest = EntityInfoGetRequestV2( - classIris = subjectAndObjectTypes, - requestingUser = requestingUser - ) + classIris = subjectAndObjectTypes, + requestingUser = requestingUser + ) additionalEntityInfo: EntityInfoGetResponseV2 <- (responderManager ? additionalEntityInfoRequest) - .mapTo[EntityInfoGetResponseV2] + .mapTo[EntityInfoGetResponseV2] // Add the additional classes to the usage index. usageIndexWithAdditionalClasses = usageIndex.copy( - knoraClassIris = usageIndex.knoraClassIris ++ subjectAndObjectTypes - ) + knoraClassIris = usageIndex.knoraClassIris ++ subjectAndObjectTypes + ) // The ontology responder may return the requested information in the internal schema. Convert each entity // definition back to the input schema. additionalEntityInfoInInputSchemas: EntityInfoGetResponseV2 = convertEntityInfoResponseToInputSchemas( - usageIndex = usageIndexWithAdditionalClasses, - entityInfo = additionalEntityInfo - ) + usageIndex = usageIndexWithAdditionalClasses, + entityInfo = additionalEntityInfo + ) // Combine all the entity info into one object. - allEntityInfo: EntityInfoGetResponseV2 = initialEntityInfoInInputSchemas.copy( - classInfoMap = initialEntityInfoInInputSchemas.classInfoMap ++ additionalEntityInfoInInputSchemas.classInfoMap - ) + allEntityInfo: EntityInfoGetResponseV2 = + initialEntityInfoInInputSchemas.copy( + classInfoMap = initialEntityInfoInInputSchemas.classInfoMap ++ additionalEntityInfoInInputSchemas.classInfoMap + ) } yield (usageIndexWithAdditionalClasses, allEntityInfo) @@ -1414,7 +1424,7 @@ class InferringGravsearchTypeInspector(nextInspector: Option[GravsearchTypeInspe usageIndex.copy( entitiesComparedInFilters = usageIndex.entitiesComparedInFilters + (leftTypeableVariable -> (currentComparisonsForLeftVariable + rightTypeableEntity)) + - (rightTypeableEntity -> (currentComparisonsForRightEntity + leftTypeableVariable)) + (rightTypeableEntity -> (currentComparisonsForRightEntity + leftTypeableVariable)) ) } @@ -1563,7 +1573,7 @@ class InferringGravsearchTypeInspector(nextInspector: Option[GravsearchTypeInspe usageIndex.copy( typedEntitiesInFilters = usageIndex.typedEntitiesInFilters + - (textVar -> (currentTextVarTypesFromFilters + OntologyConstants.KnoraApiV2Complex.TextValue.toSmartIri)) + + (textVar -> (currentTextVarTypesFromFilters + OntologyConstants.KnoraApiV2Complex.TextValue.toSmartIri)) + (standoffTagVar -> (currentStandoffVarTypesFromFilters + OntologyConstants.KnoraApiV2Complex.StandoffTag.toSmartIri)) ) diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/standoff/StandoffTagUtilV2.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/standoff/StandoffTagUtilV2.scala index f733432425..1cd670a466 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/standoff/StandoffTagUtilV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/standoff/StandoffTagUtilV2.scala @@ -323,7 +323,7 @@ object StandoffTagUtilV2 { } }.toVector - val xmlStandoffUtil = new XMLToStandoffUtil() + val xmlStandoffUtil = new XMLToStandoffUtil() val textWithStandoff: TextWithStandoff = xmlStandoffUtil.xml2TextWithStandoff(xml, elementsSeparatorRequired, log) val standoffTagsV2: Seq[StandoffTagV2] = convertXMLStandoffTagToStandoffTagV2( @@ -1066,140 +1066,160 @@ object StandoffTagUtilV2 { for { standoffEntities: StandoffEntityInfoGetResponseV2 <- (responderManager ? StandoffEntityInfoGetRequestV2( - standoffClassIris = standoffClassIris, - standoffPropertyIris = standoffPropertyIris, - requestingUser = requestingUser - )).mapTo[StandoffEntityInfoGetResponseV2] + standoffClassIris = standoffClassIris, + standoffPropertyIris = standoffPropertyIris, + requestingUser = requestingUser + )).mapTo[StandoffEntityInfoGetResponseV2] standoffTags = standoffAssertions.map { case (standoffTagIri: IRI, standoffTagAssertions: Map[IRI, String]) => - val standoffTagSmartIri: SmartIri = standoffTagIri.toSmartIri - - if (!standoffTagSmartIri.isKnoraStandoffIri) { - throw InconsistentRepositoryDataException(s"Invalid standoff tag IRI: $standoffTagIri") - } - - // The start index in the tag's IRI should match the one in its assertions. - - val startIndexFromIri: Int = standoffTagSmartIri.getStandoffStartIndex.get - val startIndexFromAssertions: Int = - standoffTagAssertions(OntologyConstants.KnoraBase.StandoffTagHasStartIndex).toInt - - if (startIndexFromAssertions != startIndexFromIri) { - throw InconsistentRepositoryDataException( - s"Standoff tag $standoffTagIri has start index $startIndexFromAssertions (expected $startIndexFromIri)" - ) - } - - // create a sequence of `StandoffTagAttributeV2` from the given attributes - val attributes: Seq[StandoffTagAttributeV2] = - (standoffTagAssertions -- StandoffProperties.systemProperties - OntologyConstants.Rdf.Type).map { - case (propIri: IRI, value) => - val propSmartIri = propIri.toSmartIri - val propDef: ReadPropertyInfoV2 = standoffEntities.standoffPropertyInfoMap(propSmartIri) - val propPredicates: Map[SmartIri, PredicateInfoV2] = propDef.entityInfoContent.predicates - - // check if the given property has an object type constraint (linking property) or an object data type constraint - if (propPredicates.contains(OntologyConstants.KnoraBase.ObjectClassConstraint.toSmartIri)) { - - // it is a linking property - // check if it refers to a resource or a standoff node - - if (propDef.isStandoffInternalReferenceProperty) { - // it refers to a standoff node, recreate the original id - - // value points to another standoff node - - // If a v2 SPARQL template was used, the XML ID is in this standoff tag. - val originalId: String = - standoffTagAssertions.get(OntologyConstants.KnoraBase.TargetHasOriginalXMLID) match { - case Some(targetXmlID) => targetXmlID - - case None => - // If a v1 SPARQL template was used, we have to get the target node and to get its XML ID. - standoffAssertions(value).getOrElse( - OntologyConstants.KnoraBase.StandoffTagHasOriginalXMLID, - throw InconsistentRepositoryDataException( - s"referred standoff $value node has no original XML id" - ) - ) - } - - // recreate the original id reference - StandoffTagInternalReferenceAttributeV2(standoffPropertyIri = propSmartIri, value = originalId) - } else { - // it refers to a knora resource - StandoffTagIriAttributeV2(standoffPropertyIri = propSmartIri, value = value) - } - } else if (propPredicates.contains(OntologyConstants.KnoraBase.ObjectDatatypeConstraint.toSmartIri)) { - - // it is a data type property (literal) - val propDataType: PredicateInfoV2 = - propPredicates(OntologyConstants.KnoraBase.ObjectDatatypeConstraint.toSmartIri) - - propDataType.objects.headOption match { - case Some(SmartIriLiteralV2(SmartIri(OntologyConstants.Xsd.String))) => - StandoffTagStringAttributeV2(standoffPropertyIri = propSmartIri, value = value) - - case Some(SmartIriLiteralV2(SmartIri(OntologyConstants.Xsd.Integer))) => - StandoffTagIntegerAttributeV2(standoffPropertyIri = propSmartIri, value = value.toInt) - - case Some(SmartIriLiteralV2(SmartIri(OntologyConstants.Xsd.Decimal))) => - StandoffTagDecimalAttributeV2(standoffPropertyIri = propSmartIri, value = BigDecimal(value)) - - case Some(SmartIriLiteralV2(SmartIri(OntologyConstants.Xsd.Boolean))) => - StandoffTagBooleanAttributeV2(standoffPropertyIri = propSmartIri, value = value.toBoolean) - - case Some(SmartIriLiteralV2(SmartIri(OntologyConstants.Xsd.DateTime))) | - Some(SmartIriLiteralV2(SmartIri(OntologyConstants.Xsd.DateTimeStamp))) => - val timeStamp = stringFormatter.xsdDateTimeStampToInstant( - value, - throw DataConversionException(s"Couldn't parse timestamp: $value") - ) - StandoffTagTimeAttributeV2(standoffPropertyIri = propSmartIri, value = timeStamp) - - case Some(SmartIriLiteralV2(SmartIri(OntologyConstants.Xsd.Uri))) => - StandoffTagUriAttributeV2(standoffPropertyIri = propSmartIri, value = value) - - case None => - throw InconsistentRepositoryDataException( - s"did not find ${OntologyConstants.KnoraBase.ObjectDatatypeConstraint} for $propIri" - ) - - case other => - throw InconsistentRepositoryDataException( - s"triplestore returned unknown ${OntologyConstants.KnoraBase.ObjectDatatypeConstraint} '$other' for $propIri" - ) - - } - } else { - throw InconsistentRepositoryDataException( - s"no object class or data type constraint found for property '$propIri'" - ) - } - - }.toVector - - StandoffTagV2( - standoffTagClassIri = standoffTagAssertions(OntologyConstants.Rdf.Type).toSmartIri, - startPosition = standoffTagAssertions(OntologyConstants.KnoraBase.StandoffTagHasStart).toInt, - endPosition = standoffTagAssertions(OntologyConstants.KnoraBase.StandoffTagHasEnd).toInt, - dataType = standoffEntities - .standoffClassInfoMap(standoffTagAssertions(OntologyConstants.Rdf.Type).toSmartIri) - .standoffDataType, - startIndex = startIndexFromAssertions, - endIndex = standoffTagAssertions.get(OntologyConstants.KnoraBase.StandoffTagHasEndIndex).map(_.toInt), - uuid = stringFormatter.decodeUuid(standoffTagAssertions(OntologyConstants.KnoraBase.StandoffTagHasUUID)), - originalXMLID = standoffTagAssertions.get(OntologyConstants.KnoraBase.StandoffTagHasOriginalXMLID), - startParentIndex = standoffTagAssertions - .get(OntologyConstants.KnoraBase.StandoffTagHasStartParent) - .flatMap(_.toSmartIri.getStandoffStartIndex), - endParentIndex = standoffTagAssertions - .get(OntologyConstants.KnoraBase.StandoffTagHasEndParent) - .flatMap(_.toSmartIri.getStandoffStartIndex), - attributes = attributes - ) - }.toVector - .sortBy(_.startIndex) + val standoffTagSmartIri: SmartIri = standoffTagIri.toSmartIri + + if (!standoffTagSmartIri.isKnoraStandoffIri) { + throw InconsistentRepositoryDataException(s"Invalid standoff tag IRI: $standoffTagIri") + } + + // The start index in the tag's IRI should match the one in its assertions. + + val startIndexFromIri: Int = standoffTagSmartIri.getStandoffStartIndex.get + val startIndexFromAssertions: Int = + standoffTagAssertions(OntologyConstants.KnoraBase.StandoffTagHasStartIndex).toInt + + if (startIndexFromAssertions != startIndexFromIri) { + throw InconsistentRepositoryDataException( + s"Standoff tag $standoffTagIri has start index $startIndexFromAssertions (expected $startIndexFromIri)" + ) + } + + // create a sequence of `StandoffTagAttributeV2` from the given attributes + val attributes: Seq[StandoffTagAttributeV2] = + (standoffTagAssertions -- StandoffProperties.systemProperties - OntologyConstants.Rdf.Type).map { + case (propIri: IRI, value) => + val propSmartIri = propIri.toSmartIri + val propDef: ReadPropertyInfoV2 = standoffEntities.standoffPropertyInfoMap(propSmartIri) + val propPredicates: Map[SmartIri, PredicateInfoV2] = propDef.entityInfoContent.predicates + + // check if the given property has an object type constraint (linking property) or an object data type constraint + if ( + propPredicates.contains(OntologyConstants.KnoraBase.ObjectClassConstraint.toSmartIri) + ) { + + // it is a linking property + // check if it refers to a resource or a standoff node + + if (propDef.isStandoffInternalReferenceProperty) { + // it refers to a standoff node, recreate the original id + + // value points to another standoff node + + // If a v2 SPARQL template was used, the XML ID is in this standoff tag. + val originalId: String = + standoffTagAssertions.get(OntologyConstants.KnoraBase.TargetHasOriginalXMLID) match { + case Some(targetXmlID) => targetXmlID + + case None => + // If a v1 SPARQL template was used, we have to get the target node and to get its XML ID. + standoffAssertions(value).getOrElse( + OntologyConstants.KnoraBase.StandoffTagHasOriginalXMLID, + throw InconsistentRepositoryDataException( + s"referred standoff $value node has no original XML id" + ) + ) + } + + // recreate the original id reference + StandoffTagInternalReferenceAttributeV2( + standoffPropertyIri = propSmartIri, + value = originalId + ) + } else { + // it refers to a knora resource + StandoffTagIriAttributeV2(standoffPropertyIri = propSmartIri, value = value) + } + } else if ( + propPredicates.contains(OntologyConstants.KnoraBase.ObjectDatatypeConstraint.toSmartIri) + ) { + + // it is a data type property (literal) + val propDataType: PredicateInfoV2 = + propPredicates(OntologyConstants.KnoraBase.ObjectDatatypeConstraint.toSmartIri) + + propDataType.objects.headOption match { + case Some(SmartIriLiteralV2(SmartIri(OntologyConstants.Xsd.String))) => + StandoffTagStringAttributeV2(standoffPropertyIri = propSmartIri, value = value) + + case Some(SmartIriLiteralV2(SmartIri(OntologyConstants.Xsd.Integer))) => + StandoffTagIntegerAttributeV2( + standoffPropertyIri = propSmartIri, + value = value.toInt + ) + + case Some(SmartIriLiteralV2(SmartIri(OntologyConstants.Xsd.Decimal))) => + StandoffTagDecimalAttributeV2( + standoffPropertyIri = propSmartIri, + value = BigDecimal(value) + ) + + case Some(SmartIriLiteralV2(SmartIri(OntologyConstants.Xsd.Boolean))) => + StandoffTagBooleanAttributeV2( + standoffPropertyIri = propSmartIri, + value = value.toBoolean + ) + + case Some(SmartIriLiteralV2(SmartIri(OntologyConstants.Xsd.DateTime))) | + Some(SmartIriLiteralV2(SmartIri(OntologyConstants.Xsd.DateTimeStamp))) => + val timeStamp = stringFormatter.xsdDateTimeStampToInstant( + value, + throw DataConversionException(s"Couldn't parse timestamp: $value") + ) + StandoffTagTimeAttributeV2(standoffPropertyIri = propSmartIri, value = timeStamp) + + case Some(SmartIriLiteralV2(SmartIri(OntologyConstants.Xsd.Uri))) => + StandoffTagUriAttributeV2(standoffPropertyIri = propSmartIri, value = value) + + case None => + throw InconsistentRepositoryDataException( + s"did not find ${OntologyConstants.KnoraBase.ObjectDatatypeConstraint} for $propIri" + ) + + case other => + throw InconsistentRepositoryDataException( + s"triplestore returned unknown ${OntologyConstants.KnoraBase.ObjectDatatypeConstraint} '$other' for $propIri" + ) + + } + } else { + throw InconsistentRepositoryDataException( + s"no object class or data type constraint found for property '$propIri'" + ) + } + + }.toVector + + StandoffTagV2( + standoffTagClassIri = standoffTagAssertions(OntologyConstants.Rdf.Type).toSmartIri, + startPosition = standoffTagAssertions(OntologyConstants.KnoraBase.StandoffTagHasStart).toInt, + endPosition = standoffTagAssertions(OntologyConstants.KnoraBase.StandoffTagHasEnd).toInt, + dataType = standoffEntities + .standoffClassInfoMap(standoffTagAssertions(OntologyConstants.Rdf.Type).toSmartIri) + .standoffDataType, + startIndex = startIndexFromAssertions, + endIndex = + standoffTagAssertions.get(OntologyConstants.KnoraBase.StandoffTagHasEndIndex).map(_.toInt), + uuid = stringFormatter.decodeUuid( + standoffTagAssertions(OntologyConstants.KnoraBase.StandoffTagHasUUID) + ), + originalXMLID = + standoffTagAssertions.get(OntologyConstants.KnoraBase.StandoffTagHasOriginalXMLID), + startParentIndex = standoffTagAssertions + .get(OntologyConstants.KnoraBase.StandoffTagHasStartParent) + .flatMap(_.toSmartIri.getStandoffStartIndex), + endParentIndex = standoffTagAssertions + .get(OntologyConstants.KnoraBase.StandoffTagHasEndParent) + .flatMap(_.toSmartIri.getStandoffStartIndex), + attributes = attributes + ) + }.toVector + .sortBy(_.startIndex) } yield standoffTags } diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/standoff/XMLToStandoffUtil.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/standoff/XMLToStandoffUtil.scala index ef3cd58ccc..7369ed5071 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/standoff/XMLToStandoffUtil.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/standoff/XMLToStandoffUtil.scala @@ -426,7 +426,7 @@ class XMLToStandoffUtil( } val xmlStrWithSep: StringWriter = new StringWriter() - val out = proc.newSerializer(xmlStrWithSep) + val out = proc.newSerializer(xmlStrWithSep) val trans = exp.load() trans.setInitialContextNode(source) @@ -521,7 +521,7 @@ class XMLToStandoffUtil( } val groupedTags: Map[Option[Int], Seq[IndexedStandoffTag]] = tags.groupBy(_.parentIndex) - val stringBuilder = new StringBuilder(XmlHeader) + val stringBuilder = new StringBuilder(XmlHeader) // Start with the root. groupedTags.get(None) match { @@ -688,17 +688,17 @@ class XMLToStandoffUtil( tag.uuid -> tag }.toMap - val oldTags = makeStandoffTagUuidMap(oldStandoff) + val oldTags = makeStandoffTagUuidMap(oldStandoff) val oldUuids = oldTags.keySet - val newTags = makeStandoffTagUuidMap(newStandoff) + val newTags = makeStandoffTagUuidMap(newStandoff) val newUuids = newTags.keySet val addedTagUuids = newUuids -- oldUuids - val addedTags = addedTagUuids.map(uuid => newTags(uuid)) + val addedTags = addedTagUuids.map(uuid => newTags(uuid)) val removedTagUuids = oldUuids -- newUuids - val removedTags = removedTagUuids.map(uuid => oldTags(uuid)) + val removedTags = removedTagUuids.map(uuid => oldTags(uuid)) (addedTags, removedTags) } @@ -778,8 +778,8 @@ class XMLToStandoffUtil( // We got an XML element. Generate a standoff tag for it. // println(s"got Elem <${elem.label}>") - val newTagIndex = acc.nextIndex - val attrMap = elem.attributes.asAttrMap + val newTagIndex = acc.nextIndex + val attrMap = elem.attributes.asAttrMap val isEmptyElement = elem.text.length == 0 if (isEmptyElement && attrMap.contains(XmlClixStartIdAttrName)) { diff --git a/webapi/src/main/scala/org/knora/webapi/messages/util/standoff/XMLUtil.scala b/webapi/src/main/scala/org/knora/webapi/messages/util/standoff/XMLUtil.scala index 6da3856773..5e74b2c81f 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/util/standoff/XMLUtil.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/util/standoff/XMLUtil.scala @@ -42,7 +42,7 @@ object XMLUtil { } val xmlTransformedStr: StringWriter = new StringWriter() - val out = proc.newSerializer(xmlTransformedStr) + val out = proc.newSerializer(xmlTransformedStr) val trans = exp.load() trans.setInitialContextNode(source) diff --git a/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/ckanmessages/CkanMessagesV1.scala b/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/ckanmessages/CkanMessagesV1.scala index 959091538a..728cf5f67b 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/ckanmessages/CkanMessagesV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/ckanmessages/CkanMessagesV1.scala @@ -187,7 +187,7 @@ object CkanV1JsonProtocol extends SprayJsonSupport with DefaultJsonProtocol { CkanProjectDatasetFileV1 ) implicit val ckanProjectDatasetV1Format: JsonFormat[CkanProjectDatasetV1] = jsonFormat4(CkanProjectDatasetV1) - implicit val ckanProjectInfoV1Format: JsonFormat[CkanProjectInfoV1] = jsonFormat4(CkanProjectInfoV1) - implicit val ckanProjectV1Format: JsonFormat[CkanProjectV1] = jsonFormat2(CkanProjectV1) - implicit val ckanResponseV1Format: RootJsonFormat[CkanResponseV1] = jsonFormat1(CkanResponseV1) + implicit val ckanProjectInfoV1Format: JsonFormat[CkanProjectInfoV1] = jsonFormat4(CkanProjectInfoV1) + implicit val ckanProjectV1Format: JsonFormat[CkanProjectV1] = jsonFormat2(CkanProjectV1) + implicit val ckanResponseV1Format: RootJsonFormat[CkanResponseV1] = jsonFormat1(CkanResponseV1) } diff --git a/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/listmessages/ListMessagesV1.scala b/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/listmessages/ListMessagesV1.scala index 698648a25e..096a77f6b2 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/listmessages/ListMessagesV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/listmessages/ListMessagesV1.scala @@ -148,8 +148,8 @@ trait ListV1JsonProtocol extends SprayJsonSupport with DefaultJsonProtocol with } val fields = Map( - "id" -> tree.id.toJson, - "name" -> tree.name.toJson, + "id" -> tree.id.toJson, + "name" -> tree.name.toJson, "label" -> tree.label.toJson, "level" -> tree.level.toJson ) ++ childrenOption diff --git a/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/ontologymessages/OntologyMessagesV1.scala b/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/ontologymessages/OntologyMessagesV1.scala index c144f32e33..1755dd7372 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/ontologymessages/OntologyMessagesV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/ontologymessages/OntologyMessagesV1.scala @@ -629,10 +629,10 @@ object ResourceTypeV1JsonProtocol extends SprayJsonSupport with DefaultJsonProto implicit val resourceTypeResponseV1Format: RootJsonFormat[ResourceTypeResponseV1] = jsonFormat1( ResourceTypeResponseV1 ) - implicit val namedGraphV1Format: RootJsonFormat[NamedGraphV1] = jsonFormat7(NamedGraphV1) + implicit val namedGraphV1Format: RootJsonFormat[NamedGraphV1] = jsonFormat7(NamedGraphV1) implicit val namedGraphsResponseV1Format: RootJsonFormat[NamedGraphsResponseV1] = jsonFormat1(NamedGraphsResponseV1) - implicit val propertyTypeV1Format: RootJsonFormat[PropertyTypeV1] = jsonFormat2(PropertyTypeV1) - implicit val resourceTypeV1Format: RootJsonFormat[ResourceTypeV1] = jsonFormat3(ResourceTypeV1) + implicit val propertyTypeV1Format: RootJsonFormat[PropertyTypeV1] = jsonFormat2(PropertyTypeV1) + implicit val resourceTypeV1Format: RootJsonFormat[ResourceTypeV1] = jsonFormat3(ResourceTypeV1) implicit val resourceTypesForNamedGraphResponseV1Format: RootJsonFormat[ResourceTypesForNamedGraphResponseV1] = jsonFormat1(ResourceTypesForNamedGraphResponseV1) implicit val propertyTypesForNamedGraphResponseV1Format: RootJsonFormat[PropertyTypesForNamedGraphResponseV1] = diff --git a/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/resourcemessages/ResourceMessagesV1.scala b/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/resourcemessages/ResourceMessagesV1.scala index 5bbe71e10d..8342b9d784 100755 --- a/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/resourcemessages/ResourceMessagesV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/resourcemessages/ResourceMessagesV1.scala @@ -824,23 +824,23 @@ object SalsahGuiConversions { * A [[Map]] of Knora IRIs to SALSAH GUI element names. */ private val iris2SalsahGuiElements: Map[IRI, IRI] = Map( - OntologyConstants.SalsahGui.SimpleText -> "text", - OntologyConstants.SalsahGui.Textarea -> "textarea", - OntologyConstants.SalsahGui.Pulldown -> "pulldown", - OntologyConstants.SalsahGui.Slider -> "slider", - OntologyConstants.SalsahGui.Spinbox -> "spinbox", - OntologyConstants.SalsahGui.Searchbox -> "searchbox", - OntologyConstants.SalsahGui.Date -> "date", - OntologyConstants.SalsahGui.Geometry -> "geometry", + OntologyConstants.SalsahGui.SimpleText -> "text", + OntologyConstants.SalsahGui.Textarea -> "textarea", + OntologyConstants.SalsahGui.Pulldown -> "pulldown", + OntologyConstants.SalsahGui.Slider -> "slider", + OntologyConstants.SalsahGui.Spinbox -> "spinbox", + OntologyConstants.SalsahGui.Searchbox -> "searchbox", + OntologyConstants.SalsahGui.Date -> "date", + OntologyConstants.SalsahGui.Geometry -> "geometry", OntologyConstants.SalsahGui.Colorpicker -> "colorpicker", - OntologyConstants.SalsahGui.List -> "hlist", - OntologyConstants.SalsahGui.Radio -> "radio", - OntologyConstants.SalsahGui.Checkbox -> "checkbox", - OntologyConstants.SalsahGui.Richtext -> "richtext", - OntologyConstants.SalsahGui.Interval -> "interval", - OntologyConstants.SalsahGui.TimeStamp -> "timestamp", - OntologyConstants.SalsahGui.Geonames -> "geoname", - OntologyConstants.SalsahGui.Fileupload -> "fileupload" + OntologyConstants.SalsahGui.List -> "hlist", + OntologyConstants.SalsahGui.Radio -> "radio", + OntologyConstants.SalsahGui.Checkbox -> "checkbox", + OntologyConstants.SalsahGui.Richtext -> "richtext", + OntologyConstants.SalsahGui.Interval -> "interval", + OntologyConstants.SalsahGui.TimeStamp -> "timestamp", + OntologyConstants.SalsahGui.Geonames -> "geoname", + OntologyConstants.SalsahGui.Fileupload -> "fileupload" ) /** @@ -890,7 +890,7 @@ case class ResourceCreateValueResponseV1(value: ResourceCreateValueObjectRespons */ object LiteralValueType extends Enumeration { type ValueType = Value - val StringValue: Value = Value(0, "string") + val StringValue: Value = Value(0, "string") val IntegerValue: Value = Value(1, "integer") val DecimalValue: Value = Value(2, "decimal") @@ -1015,15 +1015,15 @@ object ResourceV1JsonProtocol extends SprayJsonSupport with DefaultJsonProtocol // Convert each PropertyV1 object into a JsObject. val properties: Map[IRI, JsValue] = propsV1.properties.map { propertyV1 => val fields = Map( - "pid" -> propertyV1.pid.toJson, + "pid" -> propertyV1.pid.toJson, "regular_property" -> propertyV1.regular_property.toJson, - "valuetype_id" -> propertyV1.valuetype_id.toJson, - "guiorder" -> propertyV1.guiorder.toJson, - "guielement" -> propertyV1.guielement.toJson, - "is_annotation" -> propertyV1.is_annotation.toJson, - "label" -> propertyV1.label.toJson, - "attributes" -> propertyV1.attributes.toJson, - "occurrence" -> propertyV1.occurrence.toJson + "valuetype_id" -> propertyV1.valuetype_id.toJson, + "guiorder" -> propertyV1.guiorder.toJson, + "guielement" -> propertyV1.guielement.toJson, + "is_annotation" -> propertyV1.is_annotation.toJson, + "label" -> propertyV1.label.toJson, + "attributes" -> propertyV1.attributes.toJson, + "occurrence" -> propertyV1.occurrence.toJson ) ++ // Don't generate JSON for these lists if they're empty. list2JsonOption("values", propertyV1.values, () => propertyV1.values.toJson) ++ @@ -1061,13 +1061,13 @@ object ResourceV1JsonProtocol extends SprayJsonSupport with DefaultJsonProtocol // Convert each PropertyGetV1 object into a JsObject. val properties: Map[IRI, JsValue] = propsGetV1.properties.map { (propertyGetV1: PropertyGetV1) => val fields = Map( - "pid" -> propertyGetV1.pid.toJson, - "label" -> propertyGetV1.label.toJson, - "valuetype_id" -> propertyGetV1.valuetype_id.toJson, - "valuetype" -> propertyGetV1.valuetype.toJson, - "guielement" -> propertyGetV1.guielement.toJson, + "pid" -> propertyGetV1.pid.toJson, + "label" -> propertyGetV1.label.toJson, + "valuetype_id" -> propertyGetV1.valuetype_id.toJson, + "valuetype" -> propertyGetV1.valuetype.toJson, + "guielement" -> propertyGetV1.guielement.toJson, "is_annotation" -> propertyGetV1.is_annotation.toJson, - "attributes" -> propertyGetV1.attributes.toJson + "attributes" -> propertyGetV1.attributes.toJson ) ++ // Don't generate JSON for these lists if they're empty. list2JsonOption("values", propertyGetV1.values, () => propertyGetV1.values.toJson) @@ -1144,13 +1144,13 @@ object ResourceV1JsonProtocol extends SprayJsonSupport with DefaultJsonProtocol // Convert each PropertyGetV1 object into a JsObject. val properties: Map[IRI, JsValue] = propsGetForRegionV1.properties.map { (propertyGetV1: PropertyGetV1) => val fields = Map( - "pid" -> propertyGetV1.pid.toJson, - "label" -> propertyGetV1.label.toJson, - "valuetype_id" -> propertyGetV1.valuetype_id.toJson, - "valuetype" -> propertyGetV1.valuetype.toJson, - "guielement" -> propertyGetV1.guielement.toJson, + "pid" -> propertyGetV1.pid.toJson, + "label" -> propertyGetV1.label.toJson, + "valuetype_id" -> propertyGetV1.valuetype_id.toJson, + "valuetype" -> propertyGetV1.valuetype.toJson, + "guielement" -> propertyGetV1.guielement.toJson, "is_annotation" -> propertyGetV1.is_annotation.toJson, - "attributes" -> propertyGetV1.attributes.toJson + "attributes" -> propertyGetV1.attributes.toJson ) ++ // Don't generate JSON for these lists if they're empty. list2JsonOption("values", propertyGetV1.values, () => propertyGetV1.values.toJson) @@ -1159,7 +1159,7 @@ object ResourceV1JsonProtocol extends SprayJsonSupport with DefaultJsonProtocol JsObject( properties ++ Map( - "res_id" -> propsGetForRegionV1.res_id.toJson, + "res_id" -> propsGetForRegionV1.res_id.toJson, "iconsrc" -> propsGetForRegionV1.iconsrc.toJson ) ) // add res_id and iconsrc to response @@ -1190,21 +1190,21 @@ object ResourceV1JsonProtocol extends SprayJsonSupport with DefaultJsonProtocol } val fields = Map( - "project_id" -> resInfoV1.project_id.toJson, - "person_id" -> resInfoV1.person_id.toJson, - "restype_id" -> resInfoV1.restype_id.toJson, - "restype_name" -> resInfoV1.restype_name.toJson, - "restype_label" -> resInfoV1.restype_label.toJson, - "restype_description" -> resInfoV1.restype_description.toJson, - "restype_iconsrc" -> resInfoV1.restype_iconsrc.toJson, - "preview" -> resInfoV1.preview.toJson, - "locations" -> resInfoV1.locations.toJson, - "locdata" -> resInfoV1.locdata.toJson, - "resclass_name" -> resInfoV1.resclass_name.toJson, + "project_id" -> resInfoV1.project_id.toJson, + "person_id" -> resInfoV1.person_id.toJson, + "restype_id" -> resInfoV1.restype_id.toJson, + "restype_name" -> resInfoV1.restype_name.toJson, + "restype_label" -> resInfoV1.restype_label.toJson, + "restype_description" -> resInfoV1.restype_description.toJson, + "restype_iconsrc" -> resInfoV1.restype_iconsrc.toJson, + "preview" -> resInfoV1.preview.toJson, + "locations" -> resInfoV1.locations.toJson, + "locdata" -> resInfoV1.locdata.toJson, + "resclass_name" -> resInfoV1.resclass_name.toJson, "resclass_has_location" -> resInfoV1.resclass_has_location.toJson, - "lastmod" -> resInfoV1.lastmod.toJson, - "value_of" -> resInfoV1.value_of.toJson, - "regions" -> resInfoV1.regions.toJson + "lastmod" -> resInfoV1.lastmod.toJson, + "value_of" -> resInfoV1.value_of.toJson, + "regions" -> resInfoV1.regions.toJson ) ++ firstProp JsObject(fields) @@ -1238,7 +1238,7 @@ object ResourceV1JsonProtocol extends SprayJsonSupport with DefaultJsonProtocol override def write(obj: ResourceCreateResponseV1): JsValue = { val fields = Map( - "res_id" -> obj.res_id.toJson, + "res_id" -> obj.res_id.toJson, "results" -> obj.results.toJson ) @@ -1256,9 +1256,9 @@ object ResourceV1JsonProtocol extends SprayJsonSupport with DefaultJsonProtocol implicit val resourceInfoResponseV1Format: RootJsonFormat[ResourceInfoResponseV1] = jsonFormat2( ResourceInfoResponseV1 ) - implicit val resourceDataV1Format: JsonFormat[ResourceDataV1] = jsonFormat5(ResourceDataV1) + implicit val resourceDataV1Format: JsonFormat[ResourceDataV1] = jsonFormat5(ResourceDataV1) implicit val externalResourceIDV1Format: JsonFormat[ExternalResourceIDV1] = jsonFormat2(ExternalResourceIDV1) - implicit val incomingV1Format: JsonFormat[IncomingV1] = jsonFormat3(IncomingV1) + implicit val incomingV1Format: JsonFormat[IncomingV1] = jsonFormat3(IncomingV1) implicit val resourceFullResponseV1Format: RootJsonFormat[ResourceFullResponseV1] = jsonFormat5( ResourceFullResponseV1 ) diff --git a/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/searchmessages/SearchMessagesV1.scala b/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/searchmessages/SearchMessagesV1.scala index 8fa6aec4ec..b79fe3d37f 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/searchmessages/SearchMessagesV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/searchmessages/SearchMessagesV1.scala @@ -59,7 +59,7 @@ case class ExtendedSearchGetRequestV1( propertyIri: Seq[IRI] = Nil, // parallel structure propertyValueType: Seq[IRI] = Nil, compareProps: Seq[SearchComparisonOperatorV1.Value] = Nil, // parallel structure - searchValue: Seq[String] = Nil, // parallel structure + searchValue: Seq[String] = Nil, // parallel structure startAt: Int, showNRows: Int, userProfile: UserADM @@ -89,17 +89,17 @@ case class SearchGetResponseV1( * Enumeration representing the possible operators for comparing properties to a given value */ object SearchComparisonOperatorV1 extends Enumeration { - val EXISTS = Value(0, "EXISTS") - val EQ = Value(1, "EQ") - val NOT_EQ = Value(2, "!EQ") - val GT = Value(3, "GT") - val GT_EQ = Value(4, "GT_EQ") - val LT = Value(5, "LT") - val LT_EQ = Value(6, "LT_EQ") - val MATCH = Value(7, "MATCH") + val EXISTS = Value(0, "EXISTS") + val EQ = Value(1, "EQ") + val NOT_EQ = Value(2, "!EQ") + val GT = Value(3, "GT") + val GT_EQ = Value(4, "GT_EQ") + val LT = Value(5, "LT") + val LT_EQ = Value(6, "LT_EQ") + val MATCH = Value(7, "MATCH") val MATCH_BOOLEAN = Value(8, "MATCH_BOOLEAN") - val LIKE = Value(9, "LIKE") - val NOT_LIKE = Value(10, "!LIKE") + val LIKE = Value(9, "LIKE") + val NOT_LIKE = Value(10, "!LIKE") val valueMap: Map[String, SearchComparisonOperatorV1.Value] = values.map(v => (v.toString, v)).toMap @@ -165,6 +165,6 @@ object SearchV1JsonProtocol extends SprayJsonSupport with DefaultJsonProtocol wi implicit val searchPreviewDimensionsV1Format: JsonFormat[SearchPreviewDimensionsV1] = jsonFormat2( SearchPreviewDimensionsV1 ) - implicit val searchResultRowV1Format: JsonFormat[SearchResultRowV1] = jsonFormat11(SearchResultRowV1) + implicit val searchResultRowV1Format: JsonFormat[SearchResultRowV1] = jsonFormat11(SearchResultRowV1) implicit val searchResponseV1Format: RootJsonFormat[SearchGetResponseV1] = jsonFormat4(SearchGetResponseV1) } diff --git a/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/usermessages/UserMessagesV1.scala b/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/usermessages/UserMessagesV1.scala index c712ea137a..fed979f56f 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/usermessages/UserMessagesV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/usermessages/UserMessagesV1.scala @@ -253,10 +253,10 @@ case class UserProfileV1( UserProfileV1( userData = newUserData, - groups = Vector.empty[IRI], // removed groups + groups = Vector.empty[IRI], // removed groups projects_info = Map.empty[IRI, ProjectInfoV1], // removed projects - permissionData = PermissionsDataADM(), // remove permissions - sessionId = None // removed sessionId + permissionData = PermissionsDataADM(), // remove permissions + sessionId = None // removed sessionId ) case UserProfileTypeV1.RESTRICTED => val oldUserData = userData @@ -290,8 +290,8 @@ case class UserProfileV1( } def getDigest: String = { - val md = java.security.MessageDigest.getInstance("SHA-1") - val time = System.currentTimeMillis().toString + val md = java.security.MessageDigest.getInstance("SHA-1") + val time = System.currentTimeMillis().toString val value = (time + userData.toString).getBytes("UTF-8") md.digest(value).map("%02x".format(_)).mkString } @@ -364,9 +364,9 @@ object UserProfileTypeV1 extends Enumeration { type UserProfileType = Value - val SHORT: UserProfileTypeV1.Value = Value(0, "short") // only userdata + val SHORT: UserProfileTypeV1.Value = Value(0, "short") // only userdata val RESTRICTED: UserProfileTypeV1.Value = Value(1, "restricted") // without sensitive information - val FULL: UserProfileTypeV1.Value = Value(2, "full") // everything, including sensitive information + val FULL: UserProfileTypeV1.Value = Value(2, "full") // everything, including sensitive information val valueMap: Map[String, Value] = values.map(v => (v.toString, v)).toMap @@ -397,9 +397,9 @@ object UserV1JsonProtocol with ProjectV1JsonProtocol with PermissionsADMJsonProtocol { - implicit val userDataV1Format: JsonFormat[UserDataV1] = lazyFormat(jsonFormat8(UserDataV1)) - implicit val userProfileV1Format: JsonFormat[UserProfileV1] = jsonFormat6(UserProfileV1) - implicit val usersGetResponseV1Format: RootJsonFormat[UsersGetResponseV1] = jsonFormat1(UsersGetResponseV1) + implicit val userDataV1Format: JsonFormat[UserDataV1] = lazyFormat(jsonFormat8(UserDataV1)) + implicit val userProfileV1Format: JsonFormat[UserProfileV1] = jsonFormat6(UserProfileV1) + implicit val usersGetResponseV1Format: RootJsonFormat[UsersGetResponseV1] = jsonFormat1(UsersGetResponseV1) implicit val userProfileResponseV1Format: RootJsonFormat[UserProfileResponseV1] = jsonFormat1(UserProfileResponseV1) implicit val userProjectMembershipsGetResponseV1Format: RootJsonFormat[UserProjectMembershipsGetResponseV1] = jsonFormat1(UserProjectMembershipsGetResponseV1) diff --git a/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/valuemessages/ValueMessagesV1.scala b/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/valuemessages/ValueMessagesV1.scala index e9ee1a3199..3151bf8fc7 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/valuemessages/ValueMessagesV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/v1/responder/valuemessages/ValueMessagesV1.scala @@ -592,9 +592,9 @@ case class ValueObjectV1( * of the values of this enumeration; use `lookup` instead, because it reports errors better. */ object KnoraCalendarV1 extends Enumeration { - val JULIAN: Value = Value(0, "JULIAN") - val GREGORIAN: Value = Value(1, "GREGORIAN") - val JEWISH: Value = Value(2, "JEWISH") + val JULIAN: Value = Value(0, "JULIAN") + val GREGORIAN: Value = Value(1, "GREGORIAN") + val JEWISH: Value = Value(2, "JEWISH") val REVOLUTIONARY: Value = Value(3, "REVOLUTIONARY") val valueMap: Map[String, Value] = values.map(v => (v.toString, v)).toMap @@ -618,9 +618,9 @@ object KnoraCalendarV1 extends Enumeration { * of the values of this enumeration; use `lookup` instead, because it reports errors better. */ object KnoraPrecisionV1 extends Enumeration { - val DAY: Value = Value(0, "DAY") + val DAY: Value = Value(0, "DAY") val MONTH: Value = Value(1, "MONTH") - val YEAR: Value = Value(2, "YEAR") + val YEAR: Value = Value(2, "YEAR") val valueMap: Map[String, Value] = values.map(v => (v.toString, v)).toMap @@ -699,14 +699,14 @@ case class TextValueWithStandoffV1( language match { case Some(lang) => JsObject( - "xml" -> JsString(xml), + "xml" -> JsString(xml), "mapping_id" -> JsString(mappingIri), - "language" -> JsString(lang) + "language" -> JsString(lang) ) case None => JsObject( - "xml" -> JsString(xml), + "xml" -> JsString(xml), "mapping_id" -> JsString(mappingIri) ) } @@ -767,7 +767,7 @@ case class TextValueWithStandoffV1( } val startParentIndex: Option[Int] = standoffTag.standoffNode.startParentIndex - val endParentIndex: Option[Int] = standoffTag.standoffNode.endParentIndex + val endParentIndex: Option[Int] = standoffTag.standoffNode.endParentIndex // return standoff tag with updated attributes standoffTag.copy( @@ -848,7 +848,7 @@ case class TextValueSimpleV1(utf8str: String, language: Option[String] = None) language match { case Some(lang) => JsObject( - "utf8str" -> JsString(utf8str), + "utf8str" -> JsString(utf8str), "language" -> JsString(lang) ) @@ -1910,17 +1910,17 @@ object ApiValueV1JsonProtocol extends SprayJsonSupport with DefaultJsonProtocol ) } - implicit val createFileV1Format: RootJsonFormat[CreateFileV1] = jsonFormat3(CreateFileV1) - implicit val valueGetResponseV1Format: RootJsonFormat[ValueGetResponseV1] = jsonFormat7(ValueGetResponseV1) - implicit val dateValueV1Format: JsonFormat[DateValueV1] = jsonFormat5(DateValueV1) - implicit val stillImageFileValueV1Format: JsonFormat[StillImageFileValueV1] = jsonFormat7(StillImageFileValueV1) - implicit val documentFileValueV1Format: JsonFormat[DocumentFileValueV1] = jsonFormat8(DocumentFileValueV1) - implicit val archiveFileValueV1Format: JsonFormat[ArchiveFileValueV1] = jsonFormat5(ArchiveFileValueV1) - implicit val textFileValueV1Format: JsonFormat[TextFileValueV1] = jsonFormat5(TextFileValueV1) - implicit val audioFileValueV1Format: JsonFormat[AudioFileValueV1] = jsonFormat6(AudioFileValueV1) + implicit val createFileV1Format: RootJsonFormat[CreateFileV1] = jsonFormat3(CreateFileV1) + implicit val valueGetResponseV1Format: RootJsonFormat[ValueGetResponseV1] = jsonFormat7(ValueGetResponseV1) + implicit val dateValueV1Format: JsonFormat[DateValueV1] = jsonFormat5(DateValueV1) + implicit val stillImageFileValueV1Format: JsonFormat[StillImageFileValueV1] = jsonFormat7(StillImageFileValueV1) + implicit val documentFileValueV1Format: JsonFormat[DocumentFileValueV1] = jsonFormat8(DocumentFileValueV1) + implicit val archiveFileValueV1Format: JsonFormat[ArchiveFileValueV1] = jsonFormat5(ArchiveFileValueV1) + implicit val textFileValueV1Format: JsonFormat[TextFileValueV1] = jsonFormat5(TextFileValueV1) + implicit val audioFileValueV1Format: JsonFormat[AudioFileValueV1] = jsonFormat6(AudioFileValueV1) implicit val movingImageFileValueV1Format: JsonFormat[MovingImageFileValueV1] = jsonFormat9(MovingImageFileValueV1) - implicit val valueVersionV1Format: JsonFormat[ValueVersionV1] = jsonFormat3(ValueVersionV1) - implicit val linkValueV1Format: JsonFormat[LinkValueV1] = jsonFormat4(LinkValueV1) + implicit val valueVersionV1Format: JsonFormat[ValueVersionV1] = jsonFormat3(ValueVersionV1) + implicit val linkValueV1Format: JsonFormat[LinkValueV1] = jsonFormat4(LinkValueV1) implicit val valueVersionHistoryGetResponseV1Format: RootJsonFormat[ValueVersionHistoryGetResponseV1] = jsonFormat1( ValueVersionHistoryGetResponseV1 ) diff --git a/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/KnoraResponseV2.scala b/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/KnoraResponseV2.scala index 02f1e9eafa..0bb2761830 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/KnoraResponseV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/KnoraResponseV2.scala @@ -78,7 +78,7 @@ trait KnoraJsonLDResponseV2 extends KnoraResponseV2 { case nonJsonLD: NonJsonLD => // Some other format. Convert the JSON-LD document to an RDF model. val rdfFormatUtil: RdfFormatUtil = RdfFeatureFactory.getRdfFormatUtil(featureFactoryConfig) - val rdfModel: RdfModel = jsonLDDocument.toRdfModel(rdfFormatUtil.getRdfModelFactory) + val rdfModel: RdfModel = jsonLDDocument.toRdfModel(rdfFormatUtil.getRdfModelFactory) // Convert the model to the requested format. rdfFormatUtil.format( @@ -133,7 +133,7 @@ trait KnoraTurtleResponseV2 extends KnoraResponseV2 { case _ => // Some other format. Parse the Turtle to an RdfModel. val rdfFormatUtil: RdfFormatUtil = RdfFeatureFactory.getRdfFormatUtil(featureFactoryConfig) - val rdfModel: RdfModel = rdfFormatUtil.parseToRdfModel(rdfStr = turtle, rdfFormat = Turtle) + val rdfModel: RdfModel = rdfFormatUtil.parseToRdfModel(rdfStr = turtle, rdfFormat = Turtle) // Return the model in the requested format. rdfFormatUtil.format( diff --git a/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/listsmessages/ListsMessagesV2.scala b/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/listsmessages/ListsMessagesV2.scala index e2ae9bbf2e..674e56ca52 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/listsmessages/ListsMessagesV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/listsmessages/ListsMessagesV2.scala @@ -172,9 +172,9 @@ case class ListGetResponseV2(list: ListADM, userLang: String, fallbackLang: Stri OntologyConstants.KnoraApiV2Complex.KnoraApiV2PrefixExpansion ), "rdfs" -> JsonLDString("http://www.w3.org/2000/01/rdf-schema#"), - "rdf" -> JsonLDString("http://www.w3.org/1999/02/22-rdf-syntax-ns#"), - "owl" -> JsonLDString("http://www.w3.org/2002/07/owl#"), - "xsd" -> JsonLDString("http://www.w3.org/2001/XMLSchema#") + "rdf" -> JsonLDString("http://www.w3.org/1999/02/22-rdf-syntax-ns#"), + "owl" -> JsonLDString("http://www.w3.org/2002/07/owl#"), + "xsd" -> JsonLDString("http://www.w3.org/2001/XMLSchema#") ) ) @@ -270,9 +270,9 @@ case class NodeGetResponseV2(node: ListNodeInfoADM, userLang: String, fallbackLa OntologyConstants.KnoraApiV2Complex.KnoraApiV2PrefixExpansion ), "rdfs" -> JsonLDString("http://www.w3.org/2000/01/rdf-schema#"), - "rdf" -> JsonLDString("http://www.w3.org/1999/02/22-rdf-syntax-ns#"), - "owl" -> JsonLDString("http://www.w3.org/2002/07/owl#"), - "xsd" -> JsonLDString("http://www.w3.org/2001/XMLSchema#") + "rdf" -> JsonLDString("http://www.w3.org/1999/02/22-rdf-syntax-ns#"), + "owl" -> JsonLDString("http://www.w3.org/2002/07/owl#"), + "xsd" -> JsonLDString("http://www.w3.org/2001/XMLSchema#") ) ) diff --git a/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/ontologymessages/KnoraBaseToApiV2ComplexTransformationRules.scala b/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/ontologymessages/KnoraBaseToApiV2ComplexTransformationRules.scala index fd738e2e2e..404136f2c5 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/ontologymessages/KnoraBaseToApiV2ComplexTransformationRules.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/ontologymessages/KnoraBaseToApiV2ComplexTransformationRules.scala @@ -1457,23 +1457,23 @@ object KnoraBaseToApiV2ComplexTransformationRules extends OntologyTransformation private val ResourceCardinalities = Map( OntologyConstants.KnoraApiV2Complex.HasIncomingLinkValue -> Cardinality.MayHaveMany, - OntologyConstants.KnoraApiV2Complex.ArkUrl -> Cardinality.MustHaveOne, - OntologyConstants.KnoraApiV2Complex.VersionArkUrl -> Cardinality.MustHaveOne, - OntologyConstants.KnoraApiV2Complex.VersionDate -> Cardinality.MayHaveOne, - OntologyConstants.KnoraApiV2Complex.UserHasPermission -> Cardinality.MustHaveOne, - OntologyConstants.KnoraApiV2Complex.IsDeleted -> Cardinality.MayHaveOne + OntologyConstants.KnoraApiV2Complex.ArkUrl -> Cardinality.MustHaveOne, + OntologyConstants.KnoraApiV2Complex.VersionArkUrl -> Cardinality.MustHaveOne, + OntologyConstants.KnoraApiV2Complex.VersionDate -> Cardinality.MayHaveOne, + OntologyConstants.KnoraApiV2Complex.UserHasPermission -> Cardinality.MustHaveOne, + OntologyConstants.KnoraApiV2Complex.IsDeleted -> Cardinality.MayHaveOne ) private val DateBaseCardinalities = Map( - OntologyConstants.KnoraApiV2Complex.DateValueHasStartYear -> Cardinality.MustHaveOne, - OntologyConstants.KnoraApiV2Complex.DateValueHasEndYear -> Cardinality.MustHaveOne, + OntologyConstants.KnoraApiV2Complex.DateValueHasStartYear -> Cardinality.MustHaveOne, + OntologyConstants.KnoraApiV2Complex.DateValueHasEndYear -> Cardinality.MustHaveOne, OntologyConstants.KnoraApiV2Complex.DateValueHasStartMonth -> Cardinality.MayHaveOne, - OntologyConstants.KnoraApiV2Complex.DateValueHasEndMonth -> Cardinality.MayHaveOne, - OntologyConstants.KnoraApiV2Complex.DateValueHasStartDay -> Cardinality.MayHaveOne, - OntologyConstants.KnoraApiV2Complex.DateValueHasEndDay -> Cardinality.MayHaveOne, - OntologyConstants.KnoraApiV2Complex.DateValueHasStartEra -> Cardinality.MustHaveOne, - OntologyConstants.KnoraApiV2Complex.DateValueHasEndEra -> Cardinality.MustHaveOne, - OntologyConstants.KnoraApiV2Complex.DateValueHasCalendar -> Cardinality.MustHaveOne + OntologyConstants.KnoraApiV2Complex.DateValueHasEndMonth -> Cardinality.MayHaveOne, + OntologyConstants.KnoraApiV2Complex.DateValueHasStartDay -> Cardinality.MayHaveOne, + OntologyConstants.KnoraApiV2Complex.DateValueHasEndDay -> Cardinality.MayHaveOne, + OntologyConstants.KnoraApiV2Complex.DateValueHasStartEra -> Cardinality.MustHaveOne, + OntologyConstants.KnoraApiV2Complex.DateValueHasEndEra -> Cardinality.MustHaveOne, + OntologyConstants.KnoraApiV2Complex.DateValueHasCalendar -> Cardinality.MustHaveOne ) private val UriBaseCardinalities = Map( @@ -1494,7 +1494,7 @@ object KnoraBaseToApiV2ComplexTransformationRules extends OntologyTransformation private val IntervalBaseCardinalities = Map( OntologyConstants.KnoraApiV2Complex.IntervalValueHasStart -> Cardinality.MustHaveOne, - OntologyConstants.KnoraApiV2Complex.IntervalValueHasEnd -> Cardinality.MustHaveOne + OntologyConstants.KnoraApiV2Complex.IntervalValueHasEnd -> Cardinality.MustHaveOne ) private val ColorBaseCardinalities = Map( @@ -1502,33 +1502,33 @@ object KnoraBaseToApiV2ComplexTransformationRules extends OntologyTransformation ) private val ValueCardinalities = Map( - OntologyConstants.KnoraApiV2Complex.ValueAsString -> Cardinality.MayHaveOne, - OntologyConstants.KnoraApiV2Complex.HasPermissions -> Cardinality.MustHaveOne, + OntologyConstants.KnoraApiV2Complex.ValueAsString -> Cardinality.MayHaveOne, + OntologyConstants.KnoraApiV2Complex.HasPermissions -> Cardinality.MustHaveOne, OntologyConstants.KnoraApiV2Complex.UserHasPermission -> Cardinality.MustHaveOne, - OntologyConstants.KnoraApiV2Complex.ArkUrl -> Cardinality.MustHaveOne, - OntologyConstants.KnoraApiV2Complex.VersionArkUrl -> Cardinality.MustHaveOne, - OntologyConstants.KnoraApiV2Complex.IsDeleted -> Cardinality.MayHaveOne, - OntologyConstants.KnoraApiV2Complex.ValueHasUUID -> Cardinality.MustHaveOne + OntologyConstants.KnoraApiV2Complex.ArkUrl -> Cardinality.MustHaveOne, + OntologyConstants.KnoraApiV2Complex.VersionArkUrl -> Cardinality.MustHaveOne, + OntologyConstants.KnoraApiV2Complex.IsDeleted -> Cardinality.MayHaveOne, + OntologyConstants.KnoraApiV2Complex.ValueHasUUID -> Cardinality.MustHaveOne ) private val TextValueCardinalities = Map( - OntologyConstants.KnoraApiV2Complex.TextValueHasStandoff -> Cardinality.MayHaveMany, - OntologyConstants.KnoraApiV2Complex.TextValueHasMarkup -> Cardinality.MayHaveOne, - OntologyConstants.KnoraApiV2Complex.TextValueHasLanguage -> Cardinality.MayHaveOne, - OntologyConstants.KnoraApiV2Complex.TextValueAsXml -> Cardinality.MayHaveOne, - OntologyConstants.KnoraApiV2Complex.TextValueAsHtml -> Cardinality.MayHaveOne, - OntologyConstants.KnoraApiV2Complex.TextValueHasMapping -> Cardinality.MayHaveOne, + OntologyConstants.KnoraApiV2Complex.TextValueHasStandoff -> Cardinality.MayHaveMany, + OntologyConstants.KnoraApiV2Complex.TextValueHasMarkup -> Cardinality.MayHaveOne, + OntologyConstants.KnoraApiV2Complex.TextValueHasLanguage -> Cardinality.MayHaveOne, + OntologyConstants.KnoraApiV2Complex.TextValueAsXml -> Cardinality.MayHaveOne, + OntologyConstants.KnoraApiV2Complex.TextValueAsHtml -> Cardinality.MayHaveOne, + OntologyConstants.KnoraApiV2Complex.TextValueHasMapping -> Cardinality.MayHaveOne, OntologyConstants.KnoraApiV2Complex.TextValueHasMaxStandoffStartIndex -> Cardinality.MayHaveOne ) private val StandoffTagCardinalities = Map( OntologyConstants.KnoraApiV2Complex.StandoffTagHasStartParentIndex -> Cardinality.MayHaveOne, - OntologyConstants.KnoraApiV2Complex.StandoffTagHasEndParentIndex -> Cardinality.MayHaveOne + OntologyConstants.KnoraApiV2Complex.StandoffTagHasEndParentIndex -> Cardinality.MayHaveOne ) private val LinkValueCardinalities = Map( - OntologyConstants.KnoraApiV2Complex.LinkValueHasSource -> Cardinality.MayHaveOne, - OntologyConstants.KnoraApiV2Complex.LinkValueHasTarget -> Cardinality.MayHaveOne, + OntologyConstants.KnoraApiV2Complex.LinkValueHasSource -> Cardinality.MayHaveOne, + OntologyConstants.KnoraApiV2Complex.LinkValueHasTarget -> Cardinality.MayHaveOne, OntologyConstants.KnoraApiV2Complex.LinkValueHasSourceIri -> Cardinality.MayHaveOne, OntologyConstants.KnoraApiV2Complex.LinkValueHasTargetIri -> Cardinality.MayHaveOne ) @@ -1546,20 +1546,20 @@ object KnoraBaseToApiV2ComplexTransformationRules extends OntologyTransformation ) private val FileValueCardinalities = Map( - OntologyConstants.KnoraApiV2Complex.FileValueAsUrl -> Cardinality.MustHaveOne, + OntologyConstants.KnoraApiV2Complex.FileValueAsUrl -> Cardinality.MustHaveOne, OntologyConstants.KnoraApiV2Complex.FileValueHasFilename -> Cardinality.MustHaveOne ) private val StillImageFileValueCardinalities = Map( - OntologyConstants.KnoraApiV2Complex.StillImageFileValueHasDimX -> Cardinality.MustHaveOne, - OntologyConstants.KnoraApiV2Complex.StillImageFileValueHasDimY -> Cardinality.MustHaveOne, + OntologyConstants.KnoraApiV2Complex.StillImageFileValueHasDimX -> Cardinality.MustHaveOne, + OntologyConstants.KnoraApiV2Complex.StillImageFileValueHasDimY -> Cardinality.MustHaveOne, OntologyConstants.KnoraApiV2Complex.StillImageFileValueHasIIIFBaseUrl -> Cardinality.MustHaveOne ) private val DocumentFileValueCardinalities = Map( OntologyConstants.KnoraApiV2Complex.DocumentFileValueHasPageCount -> Cardinality.MustHaveOne, - OntologyConstants.KnoraApiV2Complex.DocumentFileValueHasDimX -> Cardinality.MayHaveOne, - OntologyConstants.KnoraApiV2Complex.DocumentFileValueHasDimY -> Cardinality.MayHaveOne + OntologyConstants.KnoraApiV2Complex.DocumentFileValueHasDimX -> Cardinality.MayHaveOne, + OntologyConstants.KnoraApiV2Complex.DocumentFileValueHasDimY -> Cardinality.MayHaveOne ) private val AudioFileValueCardinalities = Map( @@ -1654,25 +1654,25 @@ object KnoraBaseToApiV2ComplexTransformationRules extends OntologyTransformation * added to the specified classes to obtain `knora-api`. */ override val externalCardinalitiesToAdd: Map[SmartIri, Map[SmartIri, KnoraCardinalityInfo]] = Map( - OntologyConstants.KnoraApiV2Complex.Resource -> ResourceCardinalities, - OntologyConstants.KnoraApiV2Complex.DateBase -> DateBaseCardinalities, - OntologyConstants.KnoraApiV2Complex.UriBase -> UriBaseCardinalities, - OntologyConstants.KnoraApiV2Complex.BooleanBase -> BooleanBaseCardinalities, - OntologyConstants.KnoraApiV2Complex.IntBase -> IntBaseCardinalities, - OntologyConstants.KnoraApiV2Complex.DecimalBase -> DecimalBaseCardinalities, - OntologyConstants.KnoraApiV2Complex.IntervalBase -> IntervalBaseCardinalities, - OntologyConstants.KnoraApiV2Complex.ColorBase -> ColorBaseCardinalities, - OntologyConstants.KnoraApiV2Complex.Value -> ValueCardinalities, - OntologyConstants.KnoraApiV2Complex.TextValue -> TextValueCardinalities, - OntologyConstants.KnoraApiV2Complex.StandoffTag -> StandoffTagCardinalities, - OntologyConstants.KnoraApiV2Complex.LinkValue -> LinkValueCardinalities, - OntologyConstants.KnoraApiV2Complex.GeomValue -> GeomValueCardinalities, - OntologyConstants.KnoraApiV2Complex.ListValue -> ListValueCardinalities, - OntologyConstants.KnoraApiV2Complex.GeonameValue -> GeonameValueCardinalities, - OntologyConstants.KnoraApiV2Complex.FileValue -> FileValueCardinalities, + OntologyConstants.KnoraApiV2Complex.Resource -> ResourceCardinalities, + OntologyConstants.KnoraApiV2Complex.DateBase -> DateBaseCardinalities, + OntologyConstants.KnoraApiV2Complex.UriBase -> UriBaseCardinalities, + OntologyConstants.KnoraApiV2Complex.BooleanBase -> BooleanBaseCardinalities, + OntologyConstants.KnoraApiV2Complex.IntBase -> IntBaseCardinalities, + OntologyConstants.KnoraApiV2Complex.DecimalBase -> DecimalBaseCardinalities, + OntologyConstants.KnoraApiV2Complex.IntervalBase -> IntervalBaseCardinalities, + OntologyConstants.KnoraApiV2Complex.ColorBase -> ColorBaseCardinalities, + OntologyConstants.KnoraApiV2Complex.Value -> ValueCardinalities, + OntologyConstants.KnoraApiV2Complex.TextValue -> TextValueCardinalities, + OntologyConstants.KnoraApiV2Complex.StandoffTag -> StandoffTagCardinalities, + OntologyConstants.KnoraApiV2Complex.LinkValue -> LinkValueCardinalities, + OntologyConstants.KnoraApiV2Complex.GeomValue -> GeomValueCardinalities, + OntologyConstants.KnoraApiV2Complex.ListValue -> ListValueCardinalities, + OntologyConstants.KnoraApiV2Complex.GeonameValue -> GeonameValueCardinalities, + OntologyConstants.KnoraApiV2Complex.FileValue -> FileValueCardinalities, OntologyConstants.KnoraApiV2Complex.StillImageFileValue -> StillImageFileValueCardinalities, - OntologyConstants.KnoraApiV2Complex.DocumentFileValue -> DocumentFileValueCardinalities, - OntologyConstants.KnoraApiV2Complex.AudioFileValue -> AudioFileValueCardinalities + OntologyConstants.KnoraApiV2Complex.DocumentFileValue -> DocumentFileValueCardinalities, + OntologyConstants.KnoraApiV2Complex.AudioFileValue -> AudioFileValueCardinalities ).map { case (classIri, cardinalities) => classIri.toSmartIri -> cardinalities.map { case (propertyIri, cardinality) => propertyIri.toSmartIri -> Cardinality.KnoraCardinalityInfo(cardinality) diff --git a/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/ontologymessages/KnoraBaseToApiV2SimpleTransformationRules.scala b/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/ontologymessages/KnoraBaseToApiV2SimpleTransformationRules.scala index 3486279a1c..14d49cce70 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/ontologymessages/KnoraBaseToApiV2SimpleTransformationRules.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/ontologymessages/KnoraBaseToApiV2SimpleTransformationRules.scala @@ -394,8 +394,8 @@ object KnoraBaseToApiV2SimpleTransformationRules extends OntologyTransformationR private val ResourceCardinalites = Map( OntologyConstants.KnoraApiV2Simple.HasIncomingLink -> Cardinality.MayHaveMany, - OntologyConstants.KnoraApiV2Simple.ArkUrl -> Cardinality.MustHaveOne, - OntologyConstants.KnoraApiV2Simple.VersionArkUrl -> Cardinality.MustHaveOne + OntologyConstants.KnoraApiV2Simple.ArkUrl -> Cardinality.MustHaveOne, + OntologyConstants.KnoraApiV2Simple.VersionArkUrl -> Cardinality.MustHaveOne ) /** diff --git a/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/ontologymessages/OntologyMessagesV2.scala b/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/ontologymessages/OntologyMessagesV2.scala index 6a3e1db6cd..fbb13cbb10 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/ontologymessages/OntologyMessagesV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/ontologymessages/OntologyMessagesV2.scala @@ -357,7 +357,7 @@ object OntologyUpdateHelper { } val predicateInfoToUpdate = predicatesWithNewData.values.head - val predicateToUpdate = predicateInfoToUpdate.predicateIri + val predicateToUpdate = predicateInfoToUpdate.predicateIri if (!LabelAndCommentPredicates.contains(predicateToUpdate.toString)) { throw BadRequestException(s"Invalid predicate: $predicateToUpdate") @@ -439,9 +439,9 @@ object CreatePropertyRequestV2 extends KnoraJsonLDRequestReaderV2[CreateProperty // Get the property definition and the ontology's last modification date from the JSON-LD. - val inputOntologiesV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) - val propertyUpdateInfo = OntologyUpdateHelper.getPropertyDef(inputOntologiesV2) - val propertyInfoContent = propertyUpdateInfo.propertyInfoContent + val inputOntologiesV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) + val propertyUpdateInfo = OntologyUpdateHelper.getPropertyDef(inputOntologiesV2) + val propertyInfoContent = propertyUpdateInfo.propertyInfoContent val lastModificationDate = propertyUpdateInfo.lastModificationDate // Check that the knora-api:subjectType (if provided) and the knora-api:objectType point to valid entity IRIs. @@ -544,9 +544,9 @@ object CreateClassRequestV2 extends KnoraJsonLDRequestReaderV2[CreateClassReques // Get the class definition and the ontology's last modification date from the JSON-LD. - val inputOntologiesV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) - val classUpdateInfo = OntologyUpdateHelper.getClassDef(inputOntologiesV2) - val classInfoContent = classUpdateInfo.classInfoContent + val inputOntologiesV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) + val classUpdateInfo = OntologyUpdateHelper.getClassDef(inputOntologiesV2) + val classInfoContent = classUpdateInfo.classInfoContent val lastModificationDate = classUpdateInfo.lastModificationDate // The request must provide an rdfs:label @@ -626,9 +626,9 @@ object AddCardinalitiesToClassRequestV2 extends KnoraJsonLDRequestReaderV2[AddCa ): AddCardinalitiesToClassRequestV2 = { // Get the class definition and the ontology's last modification date from the JSON-LD. - val inputOntologiesV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) - val classUpdateInfo = OntologyUpdateHelper.getClassDef(inputOntologiesV2) - val classInfoContent = classUpdateInfo.classInfoContent + val inputOntologiesV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) + val classUpdateInfo = OntologyUpdateHelper.getClassDef(inputOntologiesV2) + val classInfoContent = classUpdateInfo.classInfoContent val lastModificationDate = classUpdateInfo.lastModificationDate // The request must provide cardinalities. @@ -719,9 +719,9 @@ object ChangeCardinalitiesRequestV2 extends KnoraJsonLDRequestReaderV2[ChangeCar featureFactoryConfig: FeatureFactoryConfig, requestingUser: UserADM ): ChangeCardinalitiesRequestV2 = { - val inputOntologiesV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) - val classUpdateInfo = OntologyUpdateHelper.getClassDef(inputOntologiesV2) - val classInfoContent = classUpdateInfo.classInfoContent + val inputOntologiesV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) + val classUpdateInfo = OntologyUpdateHelper.getClassDef(inputOntologiesV2) + val classInfoContent = classUpdateInfo.classInfoContent val lastModificationDate = classUpdateInfo.lastModificationDate ChangeCardinalitiesRequestV2( @@ -795,9 +795,9 @@ object CanDeleteCardinalitiesFromClassRequestV2 featureFactoryConfig: FeatureFactoryConfig, requestingUser: UserADM ): CanDeleteCardinalitiesFromClassRequestV2 = { - val inputOntology = InputOntologyV2.fromJsonLD(jsonLDDocument) - val classUpdateInfo = OntologyUpdateHelper.getClassDef(inputOntology) - val classInfoContent = classUpdateInfo.classInfoContent + val inputOntology = InputOntologyV2.fromJsonLD(jsonLDDocument) + val classUpdateInfo = OntologyUpdateHelper.getClassDef(inputOntology) + val classInfoContent = classUpdateInfo.classInfoContent val lastModificationDate = classUpdateInfo.lastModificationDate CanDeleteCardinalitiesFromClassRequestV2( @@ -870,9 +870,9 @@ object DeleteCardinalitiesFromClassRequestV2 extends KnoraJsonLDRequestReaderV2[ featureFactoryConfig: FeatureFactoryConfig, requestingUser: UserADM ): DeleteCardinalitiesFromClassRequestV2 = { - val inputOntology = InputOntologyV2.fromJsonLD(jsonLDDocument) - val classUpdateInfo = OntologyUpdateHelper.getClassDef(inputOntology) - val classInfoContent = classUpdateInfo.classInfoContent + val inputOntology = InputOntologyV2.fromJsonLD(jsonLDDocument) + val classUpdateInfo = OntologyUpdateHelper.getClassDef(inputOntology) + val classInfoContent = classUpdateInfo.classInfoContent val lastModificationDate = classUpdateInfo.lastModificationDate DeleteCardinalitiesFromClassRequestV2( @@ -1025,9 +1025,9 @@ object ChangePropertyGuiElementRequest extends KnoraJsonLDRequestReaderV2[Change ): ChangePropertyGuiElementRequest = { implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - val inputOntologiesV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) - val propertyUpdateInfo = OntologyUpdateHelper.getPropertyDef(inputOntologiesV2) - val propertyInfoContent = propertyUpdateInfo.propertyInfoContent + val inputOntologiesV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) + val propertyUpdateInfo = OntologyUpdateHelper.getPropertyDef(inputOntologiesV2) + val propertyInfoContent = propertyUpdateInfo.propertyInfoContent val lastModificationDate = propertyUpdateInfo.lastModificationDate val newGuiElement: Option[SmartIri] = @@ -1131,10 +1131,10 @@ object ChangePropertyLabelsOrCommentsRequestV2 featureFactoryConfig: FeatureFactoryConfig, requestingUser: UserADM ): ChangePropertyLabelsOrCommentsRequestV2 = { - val inputOntologiesV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) - val propertyUpdateInfo = OntologyUpdateHelper.getPropertyDef(inputOntologiesV2) - val propertyInfoContent = propertyUpdateInfo.propertyInfoContent - val lastModificationDate = propertyUpdateInfo.lastModificationDate + val inputOntologiesV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) + val propertyUpdateInfo = OntologyUpdateHelper.getPropertyDef(inputOntologiesV2) + val propertyInfoContent = propertyUpdateInfo.propertyInfoContent + val lastModificationDate = propertyUpdateInfo.lastModificationDate val predicateInfoToUpdate = OntologyUpdateHelper.getLabelsOrComments(propertyInfoContent) ChangePropertyLabelsOrCommentsRequestV2( @@ -1210,9 +1210,9 @@ object DeletePropertyCommentRequestV2 extends KnoraJsonLDRequestReaderV2[DeleteP featureFactoryConfig: FeatureFactoryConfig, requestingUser: UserADM ): DeletePropertyCommentRequestV2 = { - val inputOntologyV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) - val propertyUpdateInfo = OntologyUpdateHelper.getPropertyDef(inputOntologyV2) - val propertyInfoContent = propertyUpdateInfo.propertyInfoContent + val inputOntologyV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) + val propertyUpdateInfo = OntologyUpdateHelper.getPropertyDef(inputOntologyV2) + val propertyInfoContent = propertyUpdateInfo.propertyInfoContent val lastModificationDate = propertyUpdateInfo.lastModificationDate DeletePropertyCommentRequestV2( @@ -1289,10 +1289,10 @@ object ChangeClassLabelsOrCommentsRequestV2 extends KnoraJsonLDRequestReaderV2[C featureFactoryConfig: FeatureFactoryConfig, requestingUser: UserADM ): ChangeClassLabelsOrCommentsRequestV2 = { - val inputOntologiesV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) - val classUpdateInfo = OntologyUpdateHelper.getClassDef(inputOntologiesV2) - val classInfoContent = classUpdateInfo.classInfoContent - val lastModificationDate = classUpdateInfo.lastModificationDate + val inputOntologiesV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) + val classUpdateInfo = OntologyUpdateHelper.getClassDef(inputOntologiesV2) + val classInfoContent = classUpdateInfo.classInfoContent + val lastModificationDate = classUpdateInfo.lastModificationDate val predicateInfoToUpdate = OntologyUpdateHelper.getLabelsOrComments(classInfoContent) ChangeClassLabelsOrCommentsRequestV2( @@ -1368,10 +1368,10 @@ object DeleteClassCommentRequestV2 extends KnoraJsonLDRequestReaderV2[DeleteClas featureFactoryConfig: FeatureFactoryConfig, requestingUser: UserADM ): DeleteClassCommentRequestV2 = { - val inputOntologyV2: InputOntologyV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) - val classUpdateInfo: ClassUpdateInfo = OntologyUpdateHelper.getClassDef(inputOntologyV2) + val inputOntologyV2: InputOntologyV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) + val classUpdateInfo: ClassUpdateInfo = OntologyUpdateHelper.getClassDef(inputOntologyV2) val classInfoContent: ClassInfoContentV2 = classUpdateInfo.classInfoContent - val lastModificationDate: Instant = classUpdateInfo.lastModificationDate + val lastModificationDate: Instant = classUpdateInfo.lastModificationDate DeleteClassCommentRequestV2( classIri = classInfoContent.classIri, @@ -1419,9 +1419,9 @@ object ChangeGuiOrderRequestV2 extends KnoraJsonLDRequestReaderV2[ChangeGuiOrder ): ChangeGuiOrderRequestV2 = { // Get the class definition and the ontology's last modification date from the JSON-LD. - val inputOntologiesV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) - val classUpdateInfo = OntologyUpdateHelper.getClassDef(inputOntologiesV2) - val classInfoContent = classUpdateInfo.classInfoContent + val inputOntologiesV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) + val classUpdateInfo = OntologyUpdateHelper.getClassDef(inputOntologiesV2) + val classInfoContent = classUpdateInfo.classInfoContent val lastModificationDate = classUpdateInfo.lastModificationDate // The request must provide cardinalities. @@ -1503,10 +1503,10 @@ object ChangeOntologyMetadataRequestV2 extends KnoraJsonLDRequestReaderV2[Change featureFactoryConfig: FeatureFactoryConfig, requestingUser: UserADM ): ChangeOntologyMetadataRequestV2 = { - val inputOntologyV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) - val inputMetadata = inputOntologyV2.ontologyMetadata - val ontologyIri = inputMetadata.ontologyIri - val label: Option[String] = inputMetadata.label + val inputOntologyV2 = InputOntologyV2.fromJsonLD(jsonLDDocument) + val inputMetadata = inputOntologyV2.ontologyMetadata + val ontologyIri = inputMetadata.ontologyIri + val label: Option[String] = inputMetadata.label val comment: Option[String] = inputMetadata.comment val lastModificationDate = inputMetadata.lastModificationDate.getOrElse( throw BadRequestException("No knora-api:lastModificationDate submitted") @@ -1901,10 +1901,10 @@ case class ReadOntologyV2( val context = JsonLDUtil.makeContext( fixedPrefixes = Map( OntologyConstants.KnoraApi.KnoraApiOntologyLabel -> knoraApiPrefixExpansion, - "rdf" -> OntologyConstants.Rdf.RdfPrefixExpansion, - "rdfs" -> OntologyConstants.Rdfs.RdfsPrefixExpansion, - "owl" -> OntologyConstants.Owl.OwlPrefixExpansion, - "xsd" -> OntologyConstants.Xsd.XsdPrefixExpansion + "rdf" -> OntologyConstants.Rdf.RdfPrefixExpansion, + "rdfs" -> OntologyConstants.Rdfs.RdfsPrefixExpansion, + "owl" -> OntologyConstants.Owl.OwlPrefixExpansion, + "xsd" -> OntologyConstants.Xsd.XsdPrefixExpansion ) ++ salsahGuiPrefix, knoraOntologiesNeedingPrefixes = otherKnoraOntologiesUsed ) @@ -1939,7 +1939,7 @@ case class ReadOntologyV2( } }.toVector - val allEntities = jsonClasses ++ jsonProperties ++ jsonIndividuals + val allEntities = jsonClasses ++ jsonProperties ++ jsonIndividuals val allEntitiesSorted = allEntities.sortBy(_.value(JsonLDKeywords.ID)) // Assemble the JSON-LD document. @@ -2181,9 +2181,9 @@ case class ReadOntologyMetadataV2(ontologies: Set[OntologyMetadataV2]) val context = JsonLDObject( Map( OntologyConstants.KnoraApi.KnoraApiOntologyLabel -> JsonLDString(knoraApiOntologyPrefixExpansion), - "xsd" -> JsonLDString(OntologyConstants.Xsd.XsdPrefixExpansion), - "rdfs" -> JsonLDString(OntologyConstants.Rdfs.RdfsPrefixExpansion), - "owl" -> JsonLDString(OntologyConstants.Owl.OwlPrefixExpansion) + "xsd" -> JsonLDString(OntologyConstants.Xsd.XsdPrefixExpansion), + "rdfs" -> JsonLDString(OntologyConstants.Rdfs.RdfsPrefixExpansion), + "owl" -> JsonLDString(OntologyConstants.Owl.OwlPrefixExpansion) ) ) @@ -2339,9 +2339,9 @@ object Cardinality extends Enumeration { type Cardinality = Value - val MayHaveOne: Value = Value(0, "0-1") - val MayHaveMany: Value = Value(1, "0-n") - val MustHaveOne: Value = Value(2, "1") + val MayHaveOne: Value = Value(0, "0-1") + val MayHaveMany: Value = Value(1, "0-n") + val MustHaveOne: Value = Value(2, "1") val MustHaveSome: Value = Value(3, "1-n") val valueMap: Map[String, Value] = values.map(v => (v.toString, v)).toMap @@ -2937,7 +2937,7 @@ case class ReadClassInfoV2( val knoraResourcePropertiesInTargetSchema = knoraResourcePropertiesConsideringLinkValueProps.map(_.toOntologySchema(targetSchema)) - val linkPropertiesInTargetSchema = linkProperties.map(_.toOntologySchema(targetSchema)) + val linkPropertiesInTargetSchema = linkProperties.map(_.toOntologySchema(targetSchema)) val linkValuePropertiesInTargetSchema = linkValuePropsForSchema.map(_.toOntologySchema(targetSchema)) val fileValuePropertiesInTargetSchema = fileValueProperties.map(_.toOntologySchema(targetSchema)) @@ -2983,7 +2983,7 @@ case class ReadClassInfoV2( val prop2card: (IRI, JsonLDInt) = cardinalityInfo.cardinality match { case Cardinality.MayHaveMany => OntologyConstants.Owl.MinCardinality -> JsonLDInt(0) case Cardinality.MayHaveOne => OntologyConstants.Owl.MaxCardinality -> JsonLDInt(1) - case Cardinality.MustHaveOne => OntologyConstants.Owl.Cardinality -> JsonLDInt(1) + case Cardinality.MustHaveOne => OntologyConstants.Owl.Cardinality -> JsonLDInt(1) case Cardinality.MustHaveSome => OntologyConstants.Owl.MinCardinality -> JsonLDInt(1) } @@ -3006,7 +3006,7 @@ case class ReadClassInfoV2( JsonLDObject( Map( - JsonLDKeywords.TYPE -> JsonLDString(OntologyConstants.Owl.Restriction), + JsonLDKeywords.TYPE -> JsonLDString(OntologyConstants.Owl.Restriction), OntologyConstants.Owl.OnProperty -> JsonLDUtil.iriToJsonLDObject(propertyIri.toString), prop2card ) ++ isInheritedStatement ++ guiOrderStatement @@ -3076,7 +3076,7 @@ case class ReadClassInfoV2( } Map( - JsonLDKeywords.ID -> JsonLDString(entityInfoContent.classIri.toString), + JsonLDKeywords.ID -> JsonLDString(entityInfoContent.classIri.toString), JsonLDKeywords.TYPE -> JsonLDArray(entityInfoContent.getRdfTypes.map(typeIri => JsonLDString(typeIri.toString))) ) ++ jsonSubClassOfStatement ++ resourceIconStatement ++ isKnoraResourceClassStatement ++ isStandoffClassStatement ++ canBeInstantiatedStatement ++ isValueClassStatement ++ jsonRestriction @@ -3214,7 +3214,7 @@ case class ReadPropertyInfoV2( } Map( - JsonLDKeywords.ID -> JsonLDString(entityInfoContent.propertyIri.toString), + JsonLDKeywords.ID -> JsonLDString(entityInfoContent.propertyIri.toString), JsonLDKeywords.TYPE -> JsonLDArray(entityInfoContent.getRdfTypes.map(typeIri => JsonLDString(typeIri.toString))) ) ++ jsonSubPropertyOfStatement ++ subjectTypeStatement ++ objectTypeStatement ++ isResourcePropStatement ++ isEditableStatement ++ isLinkValuePropertyStatement ++ @@ -3609,7 +3609,7 @@ case class PropertyInfoContentV2( if (sourcePropertyType.toString == OntologyConstants.Owl.ObjectProperty) { // Yes. See if we need to change it to a datatype property. Does it have a knora-base:objectClassConstraint? - val objectClassConstraintIri = OntologyConstants.KnoraBase.ObjectClassConstraint.toSmartIri + val objectClassConstraintIri = OntologyConstants.KnoraBase.ObjectClassConstraint.toSmartIri val maybeObjectType: Option[SmartIri] = getPredicateIriObject(objectClassConstraintIri) maybeObjectType match { @@ -3971,7 +3971,7 @@ case class OntologyMetadataV2( } Map( - JsonLDKeywords.ID -> JsonLDString(ontologyIri.toString), + JsonLDKeywords.ID -> JsonLDString(ontologyIri.toString), JsonLDKeywords.TYPE -> JsonLDString(OntologyConstants.Owl.Ontology) ) ++ projectIriStatement ++ labelStatement ++ commentStatement ++ lastModDateStatement ++ isSharedStatement ++ isBuiltInStatement } diff --git a/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/resourcemessages/ResourceMessagesV2.scala b/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/resourcemessages/ResourceMessagesV2.scala index d6929f1118..a86acd610b 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/resourcemessages/ResourceMessagesV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/resourcemessages/ResourceMessagesV2.scala @@ -222,9 +222,9 @@ case class ResourceVersionHistoryResponseV2(history: Seq[ResourceHistoryEntry]) val context = JsonLDUtil.makeContext( fixedPrefixes = Map( - "rdf" -> OntologyConstants.Rdf.RdfPrefixExpansion, - "rdfs" -> OntologyConstants.Rdfs.RdfsPrefixExpansion, - "xsd" -> OntologyConstants.Xsd.XsdPrefixExpansion, + "rdf" -> OntologyConstants.Rdf.RdfPrefixExpansion, + "rdfs" -> OntologyConstants.Rdfs.RdfsPrefixExpansion, + "xsd" -> OntologyConstants.Xsd.XsdPrefixExpansion, OntologyConstants.KnoraApi.KnoraApiOntologyLabel -> OntologyConstants.KnoraApiV2Complex.KnoraApiV2PrefixExpansion ) ) @@ -460,9 +460,9 @@ case class ReadResourceV2( val metadataForComplexSchema: Map[IRI, JsonLDValue] = if (targetSchema == ApiV2Complex) { val requiredMetadataForComplexSchema: Map[IRI, JsonLDValue] = Map( - OntologyConstants.KnoraApiV2Complex.AttachedToUser -> JsonLDUtil.iriToJsonLDObject(attachedToUser), + OntologyConstants.KnoraApiV2Complex.AttachedToUser -> JsonLDUtil.iriToJsonLDObject(attachedToUser), OntologyConstants.KnoraApiV2Complex.AttachedToProject -> JsonLDUtil.iriToJsonLDObject(projectADM.id), - OntologyConstants.KnoraApiV2Complex.HasPermissions -> JsonLDString(permissions), + OntologyConstants.KnoraApiV2Complex.HasPermissions -> JsonLDString(permissions), OntologyConstants.KnoraApiV2Complex.UserHasPermission -> JsonLDString(userPermission.toString), OntologyConstants.KnoraApiV2Complex.CreationDate -> JsonLDUtil.datatypeValueToJsonLDObject( value = creationDate.toString, @@ -528,8 +528,8 @@ case class ReadResourceV2( JsonLDObject( Map( - JsonLDKeywords.ID -> JsonLDString(resourceIri), - JsonLDKeywords.TYPE -> JsonLDString(resourceClassIri.toString), + JsonLDKeywords.ID -> JsonLDString(resourceIri), + JsonLDKeywords.TYPE -> JsonLDString(resourceClassIri.toString), OntologyConstants.Rdfs.Label -> JsonLDString(label) ) ++ propertiesAndValuesAsJsonLD ++ metadataForComplexSchema + arkUrlAsJsonLD + versionArkUrlAsJsonLD ) @@ -572,7 +572,7 @@ case class ReadResourceV2( */ def withDeletedValues(): ReadResourceV2 = { implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - val delIri: SmartIri = OntologyConstants.KnoraBase.DeletedValue.toSmartIri + val delIri: SmartIri = OntologyConstants.KnoraBase.DeletedValue.toSmartIri val valuesWithDeletedValues: Map[SmartIri, Seq[ReadValueV2]] = this.values.toList .foldLeft(Seq.empty[(SmartIri, ReadValueV2)])((aggregator, valueMap) => @@ -709,81 +709,82 @@ object CreateResourceRequestV2 extends KnoraJsonLDRequestReaderV2[CreateResource // Get the resource's rdfs:label. label: String = jsonLDDocument.requireStringWithValidation( - OntologyConstants.Rdfs.Label, - stringFormatter.toSparqlEncodedString - ) + OntologyConstants.Rdfs.Label, + stringFormatter.toSparqlEncodedString + ) // Get information about the project that the resource should be created in. projectIri: SmartIri = jsonLDDocument.requireIriInObject( - OntologyConstants.KnoraApiV2Complex.AttachedToProject, - stringFormatter.toSmartIriWithErr - ) + OntologyConstants.KnoraApiV2Complex.AttachedToProject, + stringFormatter.toSmartIriWithErr + ) - projectInfoResponse: ProjectGetResponseADM <- (responderManager ? ProjectGetRequestADM( - identifier = ProjectIdentifierADM(maybeIri = Some(projectIri.toString)), - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - )).mapTo[ProjectGetResponseADM] + projectInfoResponse: ProjectGetResponseADM <- + (responderManager ? ProjectGetRequestADM( + identifier = ProjectIdentifierADM(maybeIri = Some(projectIri.toString)), + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + )).mapTo[ProjectGetResponseADM] _ = maybeCustomResourceIri.foreach { iri => - if (!iri.isKnoraResourceIri) { - throw BadRequestException(s"<$iri> is not a Knora resource IRI") - } + if (!iri.isKnoraResourceIri) { + throw BadRequestException(s"<$iri> is not a Knora resource IRI") + } - stringFormatter.validateUUIDOfResourceIRI(iri) + stringFormatter.validateUUIDOfResourceIRI(iri) - if (!iri.getProjectCode.contains(projectInfoResponse.project.shortcode)) { - throw BadRequestException(s"The provided resource IRI does not contain the correct project code") - } - } + if (!iri.getProjectCode.contains(projectInfoResponse.project.shortcode)) { + throw BadRequestException(s"The provided resource IRI does not contain the correct project code") + } + } // Get the resource's permissions. permissions: Option[String] = jsonLDDocument.maybeStringWithValidation( - OntologyConstants.KnoraApiV2Complex.HasPermissions, - stringFormatter.toSparqlEncodedString - ) + OntologyConstants.KnoraApiV2Complex.HasPermissions, + stringFormatter.toSparqlEncodedString + ) // Get the user who should be indicated as the creator of the resource, if specified. maybeAttachedToUserIri: Option[SmartIri] = jsonLDDocument.maybeIriInObject( - OntologyConstants.KnoraApiV2Complex.AttachedToUser, - stringFormatter.toSmartIriWithErr - ) + OntologyConstants.KnoraApiV2Complex.AttachedToUser, + stringFormatter.toSmartIriWithErr + ) maybeAttachedToUserFuture: Option[Future[UserADM]] = maybeAttachedToUserIri.map { attachedToUserIri => - UserUtilADM.switchToUser( - requestingUser = requestingUser, - requestedUserIri = attachedToUserIri.toString, - projectIri = projectIri.toString, - featureFactoryConfig = featureFactoryConfig, - responderManager = responderManager - ) - } + UserUtilADM.switchToUser( + requestingUser = requestingUser, + requestedUserIri = attachedToUserIri.toString, + projectIri = projectIri.toString, + featureFactoryConfig = featureFactoryConfig, + responderManager = responderManager + ) + } maybeAttachedToUser: Option[UserADM] <- ActorUtil.optionFuture2FutureOption(maybeAttachedToUserFuture) // Get the resource's creation date. creationDate: Option[Instant] = jsonLDDocument.maybeDatatypeValueInObject( - key = OntologyConstants.KnoraApiV2Complex.CreationDate, - expectedDatatype = OntologyConstants.Xsd.DateTimeStamp.toSmartIri, - validationFun = stringFormatter.xsdDateTimeStampToInstant - ) + key = OntologyConstants.KnoraApiV2Complex.CreationDate, + expectedDatatype = OntologyConstants.Xsd.DateTimeStamp.toSmartIri, + validationFun = stringFormatter.xsdDateTimeStampToInstant + ) // Get the resource's values. propertyIriStrs: Set[IRI] = jsonLDDocument.body.value.keySet -- - Set( - JsonLDKeywords.ID, - JsonLDKeywords.TYPE, - OntologyConstants.Rdfs.Label, - OntologyConstants.KnoraApiV2Complex.AttachedToProject, - OntologyConstants.KnoraApiV2Complex.AttachedToUser, - OntologyConstants.KnoraApiV2Complex.HasPermissions, - OntologyConstants.KnoraApiV2Complex.CreationDate - ) - - propertyValueFuturesMap: Map[SmartIri, Seq[Future[CreateValueInNewResourceV2]]] = propertyIriStrs.map { - propertyIriStr => + Set( + JsonLDKeywords.ID, + JsonLDKeywords.TYPE, + OntologyConstants.Rdfs.Label, + OntologyConstants.KnoraApiV2Complex.AttachedToProject, + OntologyConstants.KnoraApiV2Complex.AttachedToUser, + OntologyConstants.KnoraApiV2Complex.HasPermissions, + OntologyConstants.KnoraApiV2Complex.CreationDate + ) + + propertyValueFuturesMap: Map[SmartIri, Seq[Future[CreateValueInNewResourceV2]]] = + propertyIriStrs.map { propertyIriStr => val propertyIri: SmartIri = propertyIriStr.toSmartIriWithErr(throw BadRequestException(s"Invalid property IRI: <$propertyIriStr>")) val valuesArray: JsonLDArray = jsonLDDocument.requireArray(propertyIriStr) @@ -796,40 +797,46 @@ object CreateResourceRequestV2 extends KnoraJsonLDRequestReaderV2[CreateResource for { valueContent: ValueContentV2 <- ValueContentV2.fromJsonLDObject( - jsonLDObject = valueJsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + jsonLDObject = valueJsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) maybeCustomValueIri: Option[SmartIri] = valueJsonLDObject.maybeIDAsKnoraDataIri maybeCustomValueUUID: Option[UUID] = valueJsonLDObject.maybeUUID( - OntologyConstants.KnoraApiV2Complex.ValueHasUUID - ) + OntologyConstants.KnoraApiV2Complex.ValueHasUUID + ) // Get the value's creation date. // TODO: creationDate for values is a bug, and will not be supported in future. Use valueCreationDate instead. maybeCustomValueCreationDate: Option[Instant] = valueJsonLDObject - .maybeDatatypeValueInObject( - key = OntologyConstants.KnoraApiV2Complex.ValueCreationDate, - expectedDatatype = OntologyConstants.Xsd.DateTimeStamp.toSmartIri, - validationFun = stringFormatter.xsdDateTimeStampToInstant - ) - .orElse( - valueJsonLDObject.maybeDatatypeValueInObject( - key = OntologyConstants.KnoraApiV2Complex.CreationDate, - expectedDatatype = OntologyConstants.Xsd.DateTimeStamp.toSmartIri, - validationFun = stringFormatter.xsdDateTimeStampToInstant - ) - ) + .maybeDatatypeValueInObject( + key = + OntologyConstants.KnoraApiV2Complex.ValueCreationDate, + expectedDatatype = + OntologyConstants.Xsd.DateTimeStamp.toSmartIri, + validationFun = + stringFormatter.xsdDateTimeStampToInstant + ) + .orElse( + valueJsonLDObject.maybeDatatypeValueInObject( + key = + OntologyConstants.KnoraApiV2Complex.CreationDate, + expectedDatatype = + OntologyConstants.Xsd.DateTimeStamp.toSmartIri, + validationFun = + stringFormatter.xsdDateTimeStampToInstant + ) + ) maybePermissions: Option[String] = valueJsonLDObject.maybeStringWithValidation( - OntologyConstants.KnoraApiV2Complex.HasPermissions, - stringFormatter.toSparqlEncodedString - ) + OntologyConstants.KnoraApiV2Complex.HasPermissions, + stringFormatter.toSparqlEncodedString + ) } yield CreateValueInNewResourceV2( valueContent = valueContent, customValueIri = maybeCustomValueIri, @@ -840,11 +847,11 @@ object CreateResourceRequestV2 extends KnoraJsonLDRequestReaderV2[CreateResource } propertyIri -> valueFuturesSeq - }.toMap + }.toMap propertyValuesMap: Map[SmartIri, Seq[CreateValueInNewResourceV2]] <- ActorUtil.sequenceSeqFuturesInMap( - propertyValueFuturesMap - ) + propertyValueFuturesMap + ) } yield CreateResourceRequestV2( createResource = CreateResourceV2( resourceIri = maybeCustomResourceIri, @@ -1018,9 +1025,9 @@ case class UpdateResourceMetadataResponseV2( val context: JsonLDObject = JsonLDUtil.makeContext( fixedPrefixes = Map( - "rdf" -> OntologyConstants.Rdf.RdfPrefixExpansion, - "rdfs" -> OntologyConstants.Rdfs.RdfsPrefixExpansion, - "xsd" -> OntologyConstants.Xsd.XsdPrefixExpansion, + "rdf" -> OntologyConstants.Rdf.RdfPrefixExpansion, + "rdfs" -> OntologyConstants.Rdfs.RdfsPrefixExpansion, + "xsd" -> OntologyConstants.Xsd.XsdPrefixExpansion, OntologyConstants.KnoraApi.KnoraApiOntologyLabel -> knoraApiPrefixExpansion ) ) @@ -1046,7 +1053,7 @@ case class UpdateResourceMetadataResponseV2( val resourceIri_resourceClassIri_map = Map( - OntologyConstants.KnoraApiV2Complex.ResourceIri -> JsonLDString(resourceIri), + OntologyConstants.KnoraApiV2Complex.ResourceIri -> JsonLDString(resourceIri), OntologyConstants.KnoraApiV2Complex.ResourceClassIri -> JsonLDString(resourceClassIri.toString) ) @@ -1229,9 +1236,9 @@ case class ReadResourcesSequenceV2( val context: JsonLDObject = JsonLDUtil.makeContext( fixedPrefixes = Map( - "rdf" -> OntologyConstants.Rdf.RdfPrefixExpansion, - "rdfs" -> OntologyConstants.Rdfs.RdfsPrefixExpansion, - "xsd" -> OntologyConstants.Xsd.XsdPrefixExpansion, + "rdf" -> OntologyConstants.Rdf.RdfPrefixExpansion, + "rdfs" -> OntologyConstants.Rdfs.RdfsPrefixExpansion, + "xsd" -> OntologyConstants.Xsd.XsdPrefixExpansion, OntologyConstants.KnoraApi.KnoraApiOntologyLabel -> knoraApiPrefixExpansion ), knoraOntologiesNeedingPrefixes = projectSpecificOntologiesUsed @@ -1409,7 +1416,7 @@ case class GraphDataGetResponseV2(nodes: Seq[GraphNodeV2], edges: Seq[GraphEdgeV implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance val sortedNodesInTargetSchema: Seq[GraphNodeV2] = nodes.map(_.toOntologySchema(targetSchema)).sortBy(_.resourceIri) - val edgesInTargetSchema: Seq[GraphEdgeV2] = edges.map(_.toOntologySchema(targetSchema)) + val edgesInTargetSchema: Seq[GraphEdgeV2] = edges.map(_.toOntologySchema(targetSchema)) // Make JSON-LD prefixes for the project-specific ontologies used in the response. @@ -1432,9 +1439,9 @@ case class GraphDataGetResponseV2(nodes: Seq[GraphNodeV2], edges: Seq[GraphEdgeV val context = JsonLDUtil.makeContext( fixedPrefixes = Map( - "rdf" -> OntologyConstants.Rdf.RdfPrefixExpansion, - "rdfs" -> OntologyConstants.Rdfs.RdfsPrefixExpansion, - "xsd" -> OntologyConstants.Xsd.XsdPrefixExpansion, + "rdf" -> OntologyConstants.Rdf.RdfPrefixExpansion, + "rdfs" -> OntologyConstants.Rdfs.RdfsPrefixExpansion, + "xsd" -> OntologyConstants.Xsd.XsdPrefixExpansion, OntologyConstants.KnoraApi.KnoraApiOntologyLabel -> knoraApiPrefixExpansion ), knoraOntologiesNeedingPrefixes = projectSpecificOntologiesUsed @@ -1447,8 +1454,8 @@ case class GraphDataGetResponseV2(nodes: Seq[GraphNodeV2], edges: Seq[GraphEdgeV val nodesWithEdges: Seq[JsonLDObject] = sortedNodesInTargetSchema.map { node: GraphNodeV2 => // Convert the node to JSON-LD. val jsonLDNodeMap = Map( - JsonLDKeywords.ID -> JsonLDString(node.resourceIri), - JsonLDKeywords.TYPE -> JsonLDString(node.resourceClassIri.toString), + JsonLDKeywords.ID -> JsonLDString(node.resourceIri), + JsonLDKeywords.TYPE -> JsonLDString(node.resourceClassIri.toString), OntologyConstants.Rdfs.Label -> JsonLDString(node.resourceLabel) ) @@ -1590,8 +1597,8 @@ case class ResourceEventBody( } JsonLDObject( Map( - OntologyConstants.KnoraApiV2Complex.ResourceIri -> JsonLDString(resourceIri), - OntologyConstants.KnoraApiV2Complex.ResourceClassIri -> JsonLDString(resourceClassIri.toString), + OntologyConstants.KnoraApiV2Complex.ResourceIri -> JsonLDString(resourceIri), + OntologyConstants.KnoraApiV2Complex.ResourceClassIri -> JsonLDString(resourceClassIri.toString), OntologyConstants.KnoraApiV2Complex.AttachedToProject -> JsonLDUtil.iriToJsonLDObject(projectADM.id) ) ++ resourceLabel ++ creationDateAsJsonLD ++ propertiesAndValuesAsJsonLD ++ lastModificationDateAsJsonLD ++ deletionInfoAsJsonLD ++ permissionAsJsonLD @@ -1620,7 +1627,7 @@ case class ResourceMetadataEventBody( JsonLDObject( Map( - OntologyConstants.KnoraApiV2Complex.ResourceIri -> JsonLDString(resourceIri), + OntologyConstants.KnoraApiV2Complex.ResourceIri -> JsonLDString(resourceIri), OntologyConstants.KnoraApiV2Complex.ResourceClassIri -> JsonLDString(resourceClassIri.toString), OntologyConstants.KnoraApiV2Complex.LastModificationDate -> JsonLDUtil.datatypeValueToJsonLDObject( value = lastModificationDate.toString, @@ -1714,11 +1721,11 @@ case class ValueEventBody( } JsonLDObject( Map( - JsonLDKeywords.ID -> JsonLDString(valueIri), - JsonLDKeywords.TYPE -> JsonLDString(valueTypeIri.toString), - OntologyConstants.KnoraApiV2Complex.ResourceIri -> JsonLDString(resourceIri), + JsonLDKeywords.ID -> JsonLDString(valueIri), + JsonLDKeywords.TYPE -> JsonLDString(valueTypeIri.toString), + OntologyConstants.KnoraApiV2Complex.ResourceIri -> JsonLDString(resourceIri), OntologyConstants.KnoraApiV2Complex.ResourceClassIri -> JsonLDString(resourceClassIri.toString), - OntologyConstants.Rdf.Property -> JsonLDString(propertyIri.toString) + OntologyConstants.Rdf.Property -> JsonLDString(propertyIri.toString) ) ++ previousValueAsJsonLD ++ contentAsJsonLD ++ valueUUIDAsJsonLD ++ valueCreationDateAsJsonLD ++ valuePermissionsAsJSONLD ++ deletionInfoAsJsonLD ++ valueHasCommentAsJsonLD ) @@ -1768,7 +1775,7 @@ case class ResourceAndValueVersionHistoryResponseV2(historyEvents: Seq[ResourceA value = historyEntry.versionDate.toString, datatype = OntologyConstants.Xsd.DateTimeStamp.toSmartIri ), - OntologyConstants.KnoraApiV2Complex.Author -> JsonLDUtil.iriToJsonLDObject(historyEntry.author), + OntologyConstants.KnoraApiV2Complex.Author -> JsonLDUtil.iriToJsonLDObject(historyEntry.author), OntologyConstants.KnoraApiV2Complex.EventBody -> eventBodyAsJsonLD ) ) @@ -1778,10 +1785,10 @@ case class ResourceAndValueVersionHistoryResponseV2(historyEvents: Seq[ResourceA val context = JsonLDUtil.makeContext( fixedPrefixes = Map( - "rdf" -> OntologyConstants.Rdf.RdfPrefixExpansion, - "rdfs" -> OntologyConstants.Rdfs.RdfsPrefixExpansion, - "xsd" -> OntologyConstants.Xsd.XsdPrefixExpansion, - OntologyConstants.KnoraApi.KnoraApiOntologyLabel -> OntologyConstants.KnoraApiV2Complex.KnoraApiV2PrefixExpansion, + "rdf" -> OntologyConstants.Rdf.RdfPrefixExpansion, + "rdfs" -> OntologyConstants.Rdfs.RdfsPrefixExpansion, + "xsd" -> OntologyConstants.Xsd.XsdPrefixExpansion, + OntologyConstants.KnoraApi.KnoraApiOntologyLabel -> OntologyConstants.KnoraApiV2Complex.KnoraApiV2PrefixExpansion, OntologyConstants.KnoraBase.KnoraBaseOntologyLabel -> OntologyConstants.KnoraBase.KnoraBasePrefixExpansion ) ) diff --git a/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/resourcemessages/resourceAndValueEventsUtil.scala b/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/resourcemessages/resourceAndValueEventsUtil.scala index b311e948c9..6429e86877 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/resourcemessages/resourceAndValueEventsUtil.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/resourcemessages/resourceAndValueEventsUtil.scala @@ -5,11 +5,11 @@ package org.knora.webapi.messages.v2.responder.resourcemessages */ object ResourceAndValueEventsUtil { - val CREATE_RESOURCE_EVENT = "createdResource" - val DELETE_RESOURCE_EVENT = "deletedResource" + val CREATE_RESOURCE_EVENT = "createdResource" + val DELETE_RESOURCE_EVENT = "deletedResource" val UPDATE_RESOURCE_METADATA_EVENT = "updatedResourceMetadata" - val CREATE_VALUE_EVENT = "createdValue" - val UPDATE_VALUE_CONTENT_EVENT = "updatedValueContent" - val UPDATE_VALUE_PERMISSION_EVENT = "updatedValuePermission" - val DELETE_VALUE_EVENT = "deletedValue" + val CREATE_VALUE_EVENT = "createdValue" + val UPDATE_VALUE_CONTENT_EVENT = "updatedValueContent" + val UPDATE_VALUE_PERMISSION_EVENT = "updatedValuePermission" + val DELETE_VALUE_EVENT = "deletedValue" } diff --git a/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/standoffmessages/StandoffMessagesV2.scala b/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/standoffmessages/StandoffMessagesV2.scala index c64b85b924..65f2e9d9c0 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/standoffmessages/StandoffMessagesV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/standoffmessages/StandoffMessagesV2.scala @@ -112,9 +112,9 @@ case class GetStandoffResponseV2(valueIri: IRI, standoff: Seq[StandoffTagV2], ne val context: JsonLDObject = JsonLDUtil.makeContext( fixedPrefixes = Map( - "rdf" -> OntologyConstants.Rdf.RdfPrefixExpansion, - "rdfs" -> OntologyConstants.Rdfs.RdfsPrefixExpansion, - "xsd" -> OntologyConstants.Xsd.XsdPrefixExpansion, + "rdf" -> OntologyConstants.Rdf.RdfPrefixExpansion, + "rdfs" -> OntologyConstants.Rdfs.RdfsPrefixExpansion, + "xsd" -> OntologyConstants.Xsd.XsdPrefixExpansion, OntologyConstants.KnoraApi.KnoraApiOntologyLabel -> OntologyConstants.KnoraApiV2Complex.KnoraApiV2PrefixExpansion ), knoraOntologiesNeedingPrefixes = projectSpecificOntologiesUsed @@ -241,9 +241,9 @@ case class CreateMappingResponseV2(mappingIri: IRI, label: String, projectIri: S val context = JsonLDObject( Map( "rdfs" -> JsonLDString("http://www.w3.org/2000/01/rdf-schema#"), - "rdf" -> JsonLDString("http://www.w3.org/1999/02/22-rdf-syntax-ns#"), - "owl" -> JsonLDString("http://www.w3.org/2002/07/owl#"), - "xsd" -> JsonLDString("http://www.w3.org/2001/XMLSchema#") + "rdf" -> JsonLDString("http://www.w3.org/1999/02/22-rdf-syntax-ns#"), + "owl" -> JsonLDString("http://www.w3.org/2002/07/owl#"), + "xsd" -> JsonLDString("http://www.w3.org/2001/XMLSchema#") ) ) @@ -689,10 +689,10 @@ case class StandoffTagV2( val attributesAsJsonLD: Map[IRI, JsonLDValue] = attributes.map(_.toJsonLD).toMap val contentMap: Map[IRI, JsonLDValue] = Map( - JsonLDKeywords.TYPE -> JsonLDString(standoffTagClassIri.toString), - OntologyConstants.KnoraApiV2Complex.StandoffTagHasUUID -> JsonLDString(stringFormatter.base64EncodeUuid(uuid)), - OntologyConstants.KnoraApiV2Complex.StandoffTagHasStart -> JsonLDInt(startPosition), - OntologyConstants.KnoraApiV2Complex.StandoffTagHasEnd -> JsonLDInt(endPosition), + JsonLDKeywords.TYPE -> JsonLDString(standoffTagClassIri.toString), + OntologyConstants.KnoraApiV2Complex.StandoffTagHasUUID -> JsonLDString(stringFormatter.base64EncodeUuid(uuid)), + OntologyConstants.KnoraApiV2Complex.StandoffTagHasStart -> JsonLDInt(startPosition), + OntologyConstants.KnoraApiV2Complex.StandoffTagHasEnd -> JsonLDInt(endPosition), OntologyConstants.KnoraApiV2Complex.StandoffTagHasStartIndex -> JsonLDInt(startIndex) ) diff --git a/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/valuemessages/ValueMessagesV2.scala b/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/valuemessages/ValueMessagesV2.scala index ffbcd2868e..79dc42772e 100644 --- a/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/valuemessages/ValueMessagesV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/messages/v2/responder/valuemessages/ValueMessagesV2.scala @@ -90,69 +90,79 @@ object CreateValueRequestV2 extends KnoraJsonLDRequestReaderV2[CreateValueReques resourceIri: SmartIri <- Future(jsonLDDocument.requireIDAsKnoraDataIri) _ = if (!resourceIri.isKnoraResourceIri) { - throw BadRequestException(s"Invalid resource IRI: <$resourceIri>") - } + throw BadRequestException(s"Invalid resource IRI: <$resourceIri>") + } // Get the resource class. resourceClassIri: SmartIri = jsonLDDocument.requireTypeAsKnoraTypeIri // Get the resource property and the value to be created. createValue: CreateValueV2 <- jsonLDDocument.requireResourcePropertyValue match { - case (propertyIri: SmartIri, jsonLDObject: JsonLDObject) => - for { - valueContent: ValueContentV2 <- ValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - // Get and validate the custom value IRI if provided. - maybeCustomValueIri: Option[SmartIri] = jsonLDObject.maybeIDAsKnoraDataIri.map { definedNewIri => - stringFormatter.validateCustomValueIri( - customValueIri = definedNewIri, - projectCode = resourceIri.getProjectCode.get, - resourceID = resourceIri.getResourceID.get - ) - } - - // Get the custom value UUID if provided. - maybeCustomUUID: Option[UUID] = jsonLDObject.maybeUUID(OntologyConstants.KnoraApiV2Complex.ValueHasUUID) - - // Get the value's creation date. - // TODO: creationDate for values is a bug, and will not be supported in future. Use valueCreationDate instead. - maybeCreationDate: Option[Instant] = jsonLDObject - .maybeDatatypeValueInObject( - key = OntologyConstants.KnoraApiV2Complex.ValueCreationDate, - expectedDatatype = OntologyConstants.Xsd.DateTimeStamp.toSmartIri, - validationFun = stringFormatter.xsdDateTimeStampToInstant - ) - .orElse( - jsonLDObject.maybeDatatypeValueInObject( - key = OntologyConstants.KnoraApiV2Complex.CreationDate, - expectedDatatype = OntologyConstants.Xsd.DateTimeStamp.toSmartIri, - validationFun = stringFormatter.xsdDateTimeStampToInstant - ) - ) - - maybePermissions: Option[String] = jsonLDObject.maybeStringWithValidation( - OntologyConstants.KnoraApiV2Complex.HasPermissions, - stringFormatter.toSparqlEncodedString - ) - } yield CreateValueV2( - resourceIri = resourceIri.toString, - resourceClassIri = resourceClassIri, - propertyIri = propertyIri, - valueContent = valueContent, - valueIri = maybeCustomValueIri, - valueUUID = maybeCustomUUID, - valueCreationDate = maybeCreationDate, - permissions = maybePermissions - ) - } + case (propertyIri: SmartIri, jsonLDObject: JsonLDObject) => + for { + valueContent: ValueContentV2 <- ValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + // Get and validate the custom value IRI if provided. + maybeCustomValueIri: Option[SmartIri] = + jsonLDObject.maybeIDAsKnoraDataIri.map { definedNewIri => + stringFormatter.validateCustomValueIri( + customValueIri = definedNewIri, + projectCode = resourceIri.getProjectCode.get, + resourceID = resourceIri.getResourceID.get + ) + } + + // Get the custom value UUID if provided. + maybeCustomUUID: Option[UUID] = + jsonLDObject.maybeUUID(OntologyConstants.KnoraApiV2Complex.ValueHasUUID) + + // Get the value's creation date. + // TODO: creationDate for values is a bug, and will not be supported in future. Use valueCreationDate instead. + maybeCreationDate: Option[Instant] = jsonLDObject + .maybeDatatypeValueInObject( + key = + OntologyConstants.KnoraApiV2Complex.ValueCreationDate, + expectedDatatype = + OntologyConstants.Xsd.DateTimeStamp.toSmartIri, + validationFun = + stringFormatter.xsdDateTimeStampToInstant + ) + .orElse( + jsonLDObject + .maybeDatatypeValueInObject( + key = + OntologyConstants.KnoraApiV2Complex.CreationDate, + expectedDatatype = + OntologyConstants.Xsd.DateTimeStamp.toSmartIri, + validationFun = + stringFormatter.xsdDateTimeStampToInstant + ) + ) + + maybePermissions: Option[String] = + jsonLDObject.maybeStringWithValidation( + OntologyConstants.KnoraApiV2Complex.HasPermissions, + stringFormatter.toSparqlEncodedString + ) + } yield CreateValueV2( + resourceIri = resourceIri.toString, + resourceClassIri = resourceClassIri, + propertyIri = propertyIri, + valueContent = valueContent, + valueIri = maybeCustomValueIri, + valueUUID = maybeCustomUUID, + valueCreationDate = maybeCreationDate, + permissions = maybePermissions + ) + } } yield CreateValueRequestV2( createValue = createValue, featureFactoryConfig = featureFactoryConfig, @@ -193,8 +203,8 @@ case class CreateValueResponseV2( JsonLDDocument( body = JsonLDObject( Map( - JsonLDKeywords.ID -> JsonLDString(valueIri), - JsonLDKeywords.TYPE -> JsonLDString(valueType.toOntologySchema(ApiV2Complex).toString), + JsonLDKeywords.ID -> JsonLDString(valueIri), + JsonLDKeywords.TYPE -> JsonLDString(valueType.toOntologySchema(ApiV2Complex).toString), OntologyConstants.KnoraApiV2Complex.ValueHasUUID -> JsonLDString(stringFormatter.base64EncodeUuid(valueUUID)), OntologyConstants.KnoraApiV2Complex.ValueCreationDate -> JsonLDUtil.datatypeValueToJsonLDObject( value = valueCreationDate.toString, @@ -262,107 +272,116 @@ object UpdateValueRequestV2 extends KnoraJsonLDRequestReaderV2[UpdateValueReques resourceIri: SmartIri <- Future(jsonLDDocument.requireIDAsKnoraDataIri) _ = if (!resourceIri.isKnoraResourceIri) { - throw BadRequestException(s"Invalid resource IRI: <$resourceIri>") - } + throw BadRequestException(s"Invalid resource IRI: <$resourceIri>") + } // Get the resource class. resourceClassIri: SmartIri = jsonLDDocument.requireTypeAsKnoraTypeIri // Get the resource property and the new value version. updateValue: UpdateValueV2 <- jsonLDDocument.requireResourcePropertyValue match { - case (propertyIri: SmartIri, jsonLDObject: JsonLDObject) => - val valueIri: SmartIri = jsonLDObject.requireIDAsKnoraDataIri - - // Get the custom value creation date, if provided. - val maybeValueCreationDate: Option[Instant] = jsonLDObject.maybeDatatypeValueInObject( - key = OntologyConstants.KnoraApiV2Complex.ValueCreationDate, - expectedDatatype = OntologyConstants.Xsd.DateTimeStamp.toSmartIri, - validationFun = stringFormatter.xsdDateTimeStampToInstant - ) - - // Get and validate the custom new value version IRI, if provided. - - val maybeNewIri: Option[SmartIri] = jsonLDObject - .maybeIriInObject( - OntologyConstants.KnoraApiV2Complex.NewValueVersionIri, - stringFormatter.toSmartIriWithErr - ) - .map { definedNewIri => - if (definedNewIri == valueIri) { - throw BadRequestException( - s"The IRI of a new value version cannot be the same as the IRI of the current version" - ) - } - - stringFormatter.validateCustomValueIri( - customValueIri = definedNewIri, - projectCode = valueIri.getProjectCode.get, - resourceID = valueIri.getResourceID.get - ) - } - - // Aside from the value's ID and type and the optional predicates above, does the value object just - // contain knora-api:hasPermissions? - - val otherValuePredicates: Set[IRI] = jsonLDObject.value.keySet -- Set( - JsonLDKeywords.ID, - JsonLDKeywords.TYPE, - OntologyConstants.KnoraApiV2Complex.ValueCreationDate, - OntologyConstants.KnoraApiV2Complex.NewValueVersionIri - ) - - if (otherValuePredicates == Set(OntologyConstants.KnoraApiV2Complex.HasPermissions)) { - // Yes. This is a request to change the value's permissions. - - val valueType: SmartIri = - jsonLDObject.requireStringWithValidation(JsonLDKeywords.TYPE, stringFormatter.toSmartIriWithErr) - val permissions = jsonLDObject.requireStringWithValidation( - OntologyConstants.KnoraApiV2Complex.HasPermissions, - stringFormatter.toSparqlEncodedString - ) - - FastFuture.successful( - UpdateValuePermissionsV2( - resourceIri = resourceIri.toString, - resourceClassIri = resourceClassIri, - propertyIri = propertyIri, - valueIri = valueIri.toString, - valueType = valueType, - permissions = permissions, - valueCreationDate = maybeValueCreationDate, - newValueVersionIri = maybeNewIri - ) - ) - } else { - // No. This is a request to change the value content. - - for { - valueContent: ValueContentV2 <- ValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig: FeatureFactoryConfig, - settings = settings, - log = log - ) - - maybePermissions: Option[String] = jsonLDObject.maybeStringWithValidation( - OntologyConstants.KnoraApiV2Complex.HasPermissions, - stringFormatter.toSparqlEncodedString - ) - } yield UpdateValueContentV2( - resourceIri = resourceIri.toString, - resourceClassIri = resourceClassIri, - propertyIri = propertyIri, - valueIri = valueIri.toString, - valueContent = valueContent, - permissions = maybePermissions, - valueCreationDate = maybeValueCreationDate, - newValueVersionIri = maybeNewIri - ) - } - } + case (propertyIri: SmartIri, jsonLDObject: JsonLDObject) => + val valueIri: SmartIri = jsonLDObject.requireIDAsKnoraDataIri + + // Get the custom value creation date, if provided. + val maybeValueCreationDate: Option[Instant] = + jsonLDObject.maybeDatatypeValueInObject( + key = OntologyConstants.KnoraApiV2Complex.ValueCreationDate, + expectedDatatype = OntologyConstants.Xsd.DateTimeStamp.toSmartIri, + validationFun = stringFormatter.xsdDateTimeStampToInstant + ) + + // Get and validate the custom new value version IRI, if provided. + + val maybeNewIri: Option[SmartIri] = jsonLDObject + .maybeIriInObject( + OntologyConstants.KnoraApiV2Complex.NewValueVersionIri, + stringFormatter.toSmartIriWithErr + ) + .map { definedNewIri => + if (definedNewIri == valueIri) { + throw BadRequestException( + s"The IRI of a new value version cannot be the same as the IRI of the current version" + ) + } + + stringFormatter.validateCustomValueIri( + customValueIri = definedNewIri, + projectCode = valueIri.getProjectCode.get, + resourceID = valueIri.getResourceID.get + ) + } + + // Aside from the value's ID and type and the optional predicates above, does the value object just + // contain knora-api:hasPermissions? + + val otherValuePredicates: Set[IRI] = jsonLDObject.value.keySet -- Set( + JsonLDKeywords.ID, + JsonLDKeywords.TYPE, + OntologyConstants.KnoraApiV2Complex.ValueCreationDate, + OntologyConstants.KnoraApiV2Complex.NewValueVersionIri + ) + + if ( + otherValuePredicates == Set( + OntologyConstants.KnoraApiV2Complex.HasPermissions + ) + ) { + // Yes. This is a request to change the value's permissions. + + val valueType: SmartIri = + jsonLDObject.requireStringWithValidation( + JsonLDKeywords.TYPE, + stringFormatter.toSmartIriWithErr + ) + val permissions = jsonLDObject.requireStringWithValidation( + OntologyConstants.KnoraApiV2Complex.HasPermissions, + stringFormatter.toSparqlEncodedString + ) + + FastFuture.successful( + UpdateValuePermissionsV2( + resourceIri = resourceIri.toString, + resourceClassIri = resourceClassIri, + propertyIri = propertyIri, + valueIri = valueIri.toString, + valueType = valueType, + permissions = permissions, + valueCreationDate = maybeValueCreationDate, + newValueVersionIri = maybeNewIri + ) + ) + } else { + // No. This is a request to change the value content. + + for { + valueContent: ValueContentV2 <- ValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig: FeatureFactoryConfig, + settings = settings, + log = log + ) + + maybePermissions: Option[String] = + jsonLDObject.maybeStringWithValidation( + OntologyConstants.KnoraApiV2Complex.HasPermissions, + stringFormatter.toSparqlEncodedString + ) + } yield UpdateValueContentV2( + resourceIri = resourceIri.toString, + resourceClassIri = resourceClassIri, + propertyIri = propertyIri, + valueIri = valueIri.toString, + valueContent = valueContent, + permissions = maybePermissions, + valueCreationDate = maybeValueCreationDate, + newValueVersionIri = maybeNewIri + ) + } + } } yield UpdateValueRequestV2( updateValue = updateValue, featureFactoryConfig = featureFactoryConfig, @@ -397,8 +416,8 @@ case class UpdateValueResponseV2(valueIri: IRI, valueType: SmartIri, valueUUID: JsonLDDocument( body = JsonLDObject( Map( - JsonLDKeywords.ID -> JsonLDString(valueIri), - JsonLDKeywords.TYPE -> JsonLDString(valueType.toOntologySchema(ApiV2Complex).toString), + JsonLDKeywords.ID -> JsonLDString(valueIri), + JsonLDKeywords.TYPE -> JsonLDString(valueType.toOntologySchema(ApiV2Complex).toString), OntologyConstants.KnoraApiV2Complex.ValueHasUUID -> JsonLDString(stringFormatter.base64EncodeUuid(valueUUID)) ) ), @@ -620,7 +639,7 @@ case class DeletionInfo(deleteDate: Instant, maybeDeleteComment: Option[String]) OntologyConstants.KnoraApiV2Complex.IsDeleted -> JsonLDBoolean(true), OntologyConstants.KnoraApiV2Complex.DeleteDate -> JsonLDObject( Map( - JsonLDKeywords.TYPE -> JsonLDString(OntologyConstants.Xsd.DateTimeStamp), + JsonLDKeywords.TYPE -> JsonLDString(OntologyConstants.Xsd.DateTimeStamp), JsonLDKeywords.VALUE -> JsonLDString(deleteDate.toString) ) ) @@ -719,10 +738,10 @@ sealed trait ReadValueV2 extends IOValueV2 { val valueSmartIri = valueIri.toSmartIri val requiredMetadata = Map( - JsonLDKeywords.ID -> JsonLDString(valueIri), - JsonLDKeywords.TYPE -> JsonLDString(valueContent.valueType.toString), - OntologyConstants.KnoraApiV2Complex.AttachedToUser -> JsonLDUtil.iriToJsonLDObject(attachedToUser), - OntologyConstants.KnoraApiV2Complex.HasPermissions -> JsonLDString(permissions), + JsonLDKeywords.ID -> JsonLDString(valueIri), + JsonLDKeywords.TYPE -> JsonLDString(valueContent.valueType.toString), + OntologyConstants.KnoraApiV2Complex.AttachedToUser -> JsonLDUtil.iriToJsonLDObject(attachedToUser), + OntologyConstants.KnoraApiV2Complex.HasPermissions -> JsonLDString(permissions), OntologyConstants.KnoraApiV2Complex.UserHasPermission -> JsonLDString(userPermission.toString), OntologyConstants.KnoraApiV2Complex.ValueCreationDate -> JsonLDUtil.datatypeValueToJsonLDObject( value = valueCreationDate.toString, @@ -855,7 +874,7 @@ case class ReadTextValueV2( JsonLDObject( valueAsJsonLDObject.value ++ Map( - OntologyConstants.KnoraApiV2Complex.TextValueHasMarkup -> JsonLDBoolean(true), + OntologyConstants.KnoraApiV2Complex.TextValueHasMarkup -> JsonLDBoolean(true), OntologyConstants.KnoraApiV2Complex.TextValueHasMaxStandoffStartIndex -> JsonLDInt(maxStartIndex) ) ) @@ -1206,222 +1225,226 @@ object ValueContentV2 extends ValueContentReaderV2[ValueContentV2] { implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance for { - valueType: SmartIri <- Future( - jsonLDObject.requireStringWithValidation(JsonLDKeywords.TYPE, stringFormatter.toSmartIriWithErr) - ) + valueType: SmartIri <- + Future( + jsonLDObject.requireStringWithValidation(JsonLDKeywords.TYPE, stringFormatter.toSmartIriWithErr) + ) valueContent: ValueContentV2 <- valueType.toString match { - case OntologyConstants.KnoraApiV2Complex.TextValue => - TextValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - case OntologyConstants.KnoraApiV2Complex.IntValue => - IntegerValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - case OntologyConstants.KnoraApiV2Complex.DecimalValue => - DecimalValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - case OntologyConstants.KnoraApiV2Complex.BooleanValue => - BooleanValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - case OntologyConstants.KnoraApiV2Complex.DateValue => - DateValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - case OntologyConstants.KnoraApiV2Complex.GeomValue => - GeomValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - case OntologyConstants.KnoraApiV2Complex.IntervalValue => - IntervalValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - case OntologyConstants.KnoraApiV2Complex.TimeValue => - TimeValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - case OntologyConstants.KnoraApiV2Complex.LinkValue => - LinkValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - case OntologyConstants.KnoraApiV2Complex.ListValue => - HierarchicalListValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - case OntologyConstants.KnoraApiV2Complex.UriValue => - UriValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - case OntologyConstants.KnoraApiV2Complex.GeonameValue => - GeonameValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - case OntologyConstants.KnoraApiV2Complex.ColorValue => - ColorValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - case OntologyConstants.KnoraApiV2Complex.StillImageFileValue => - StillImageFileValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - case OntologyConstants.KnoraApiV2Complex.DocumentFileValue => - DocumentFileValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - case OntologyConstants.KnoraApiV2Complex.TextFileValue => - TextFileValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - case OntologyConstants.KnoraApiV2Complex.AudioFileValue => - AudioFileValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - case OntologyConstants.KnoraApiV2Complex.MovingImageFileValue => - MovingImageFileValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - case OntologyConstants.KnoraApiV2Complex.ArchiveFileValue => - ArchiveFileValueContentV2.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - case other => throw NotImplementedException(s"Parsing of JSON-LD value type not implemented: $other") - } + case OntologyConstants.KnoraApiV2Complex.TextValue => + TextValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + case OntologyConstants.KnoraApiV2Complex.IntValue => + IntegerValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + case OntologyConstants.KnoraApiV2Complex.DecimalValue => + DecimalValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + case OntologyConstants.KnoraApiV2Complex.BooleanValue => + BooleanValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + case OntologyConstants.KnoraApiV2Complex.DateValue => + DateValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + case OntologyConstants.KnoraApiV2Complex.GeomValue => + GeomValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + case OntologyConstants.KnoraApiV2Complex.IntervalValue => + IntervalValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + case OntologyConstants.KnoraApiV2Complex.TimeValue => + TimeValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + case OntologyConstants.KnoraApiV2Complex.LinkValue => + LinkValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + case OntologyConstants.KnoraApiV2Complex.ListValue => + HierarchicalListValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + case OntologyConstants.KnoraApiV2Complex.UriValue => + UriValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + case OntologyConstants.KnoraApiV2Complex.GeonameValue => + GeonameValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + case OntologyConstants.KnoraApiV2Complex.ColorValue => + ColorValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + case OntologyConstants.KnoraApiV2Complex.StillImageFileValue => + StillImageFileValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + case OntologyConstants.KnoraApiV2Complex.DocumentFileValue => + DocumentFileValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + case OntologyConstants.KnoraApiV2Complex.TextFileValue => + TextFileValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + case OntologyConstants.KnoraApiV2Complex.AudioFileValue => + AudioFileValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + case OntologyConstants.KnoraApiV2Complex.MovingImageFileValue => + MovingImageFileValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + case OntologyConstants.KnoraApiV2Complex.ArchiveFileValue => + ArchiveFileValueContentV2.fromJsonLDObject( + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + case other => + throw NotImplementedException( + s"Parsing of JSON-LD value type not implemented: $other" + ) + } } yield valueContent } @@ -1491,7 +1514,7 @@ case class DateValueContentV2( case ApiV2Complex => val startCalendarDate: CalendarDateV2 = asCalendarDateRange.startCalendarDate - val endCalendarDate: CalendarDateV2 = asCalendarDateRange.endCalendarDate + val endCalendarDate: CalendarDateV2 = asCalendarDateRange.endCalendarDate val startDateAssertions = Map(OntologyConstants.KnoraApiV2Complex.DateValueHasStartYear -> JsonLDInt(startCalendarDate.year)) ++ @@ -1519,7 +1542,7 @@ case class DateValueContentV2( JsonLDObject( Map( - OntologyConstants.KnoraApiV2Complex.ValueAsString -> JsonLDString(valueHasString), + OntologyConstants.KnoraApiV2Complex.ValueAsString -> JsonLDString(valueHasString), OntologyConstants.KnoraApiV2Complex.DateValueHasCalendar -> JsonLDString(valueHasCalendar.toString) ) ++ startDateAssertions ++ endDateAssertions ) @@ -1567,7 +1590,7 @@ object DateValueContentV2 extends ValueContentReaderV2[DateValueContentV2] { */ def parse(dateStr: String): DateValueContentV2 = { val dateRange: CalendarDateRangeV2 = CalendarDateRangeV2.parse(dateStr) - val (startJDN: Int, endJDN: Int) = dateRange.toJulianDayRange + val (startJDN: Int, endJDN: Int) = dateRange.toJulianDayRange DateValueContentV2( ontologySchema = ApiV2Simple, @@ -1827,7 +1850,7 @@ case class TextValueContentV2( // the xml was converted to HTML Map( OntologyConstants.KnoraApiV2Complex.TextValueAsHtml -> JsonLDString(xmlTransformed), - OntologyConstants.KnoraApiV2Complex.TextValueAsXml -> JsonLDString(xmlFromStandoff), + OntologyConstants.KnoraApiV2Complex.TextValueAsXml -> JsonLDString(xmlFromStandoff), OntologyConstants.KnoraApiV2Complex.TextValueHasMapping -> JsonLDUtil.iriToJsonLDObject( definedMappingIri ) @@ -1910,7 +1933,7 @@ case class TextValueContentV2( } val startParentIndex: Option[Int] = standoffTag.standoffNode.startParentIndex - val endParentIndex: Option[Int] = standoffTag.standoffNode.endParentIndex + val endParentIndex: Option[Int] = standoffTag.standoffNode.endParentIndex // return standoff tag with updated attributes standoffTag.copy( @@ -2007,75 +2030,77 @@ object TextValueContentV2 extends ValueContentReaderV2[TextValueContentV2] { for { maybeValueAsString: Option[String] <- Future( - jsonLDObject.maybeStringWithValidation( - OntologyConstants.KnoraApiV2Complex.ValueAsString, - stringFormatter.toSparqlEncodedString - ) - ) + jsonLDObject.maybeStringWithValidation( + OntologyConstants.KnoraApiV2Complex.ValueAsString, + stringFormatter.toSparqlEncodedString + ) + ) maybeValueHasLanguage: Option[String] = jsonLDObject.maybeStringWithValidation( - OntologyConstants.KnoraApiV2Complex.TextValueHasLanguage, - stringFormatter.toSparqlEncodedString - ) + OntologyConstants.KnoraApiV2Complex.TextValueHasLanguage, + stringFormatter.toSparqlEncodedString + ) maybeTextValueAsXml: Option[String] = jsonLDObject.maybeString(OntologyConstants.KnoraApiV2Complex.TextValueAsXml) maybeMappingIri: Option[IRI] = jsonLDObject.maybeIriInObject( - OntologyConstants.KnoraApiV2Complex.TextValueHasMapping, - stringFormatter.validateAndEscapeIri - ) + OntologyConstants.KnoraApiV2Complex.TextValueHasMapping, + stringFormatter.validateAndEscapeIri + ) // If the client supplied the IRI of a standoff-to-XML mapping, get the mapping. maybeMappingFuture: Option[Future[GetMappingResponseV2]] = maybeMappingIri.map { mappingIri => - for { - mappingResponse: GetMappingResponseV2 <- (responderManager ? GetMappingRequestV2( - mappingIri = mappingIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - )).mapTo[GetMappingResponseV2] - } yield mappingResponse - } + for { + mappingResponse: GetMappingResponseV2 <- + (responderManager ? GetMappingRequestV2( + mappingIri = mappingIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + )).mapTo[GetMappingResponseV2] + } yield mappingResponse + } maybeMappingResponse: Option[GetMappingResponseV2] <- ActorUtil.optionFuture2FutureOption(maybeMappingFuture) // Did the client submit text with or without standoff markup? textValue: TextValueContentV2 = (maybeValueAsString, maybeTextValueAsXml, maybeMappingResponse) match { - case (Some(valueAsString), None, None) => - // Text without standoff. - TextValueContentV2( - ontologySchema = ApiV2Complex, - maybeValueHasString = Some(valueAsString), - comment = getComment(jsonLDObject) - ) - - case (None, Some(textValueAsXml), Some(mappingResponse)) => - // Text with standoff. TODO: support submitting text with standoff as JSON-LD rather than as XML. - - val textWithStandoffTags: TextWithStandoffTagsV2 = StandoffTagUtilV2.convertXMLtoStandoffTagV2( - xml = textValueAsXml, - mapping = mappingResponse, - acceptStandoffLinksToClientIDs = false, - log = log - ) - - TextValueContentV2( - ontologySchema = ApiV2Complex, - maybeValueHasString = Some( - stringFormatter.toSparqlEncodedString( - textWithStandoffTags.text, - throw BadRequestException("Text value contains invalid characters") - ) - ), - valueHasLanguage = maybeValueHasLanguage, - standoff = textWithStandoffTags.standoffTagV2, - mappingIri = Some(mappingResponse.mappingIri), - mapping = Some(mappingResponse.mapping), - comment = getComment(jsonLDObject) - ) - - case _ => - throw BadRequestException( - s"Invalid combination of knora-api:valueHasString, knora-api:textValueAsXml, and/or knora-api:textValueHasMapping" - ) - } + case (Some(valueAsString), None, None) => + // Text without standoff. + TextValueContentV2( + ontologySchema = ApiV2Complex, + maybeValueHasString = Some(valueAsString), + comment = getComment(jsonLDObject) + ) + + case (None, Some(textValueAsXml), Some(mappingResponse)) => + // Text with standoff. TODO: support submitting text with standoff as JSON-LD rather than as XML. + + val textWithStandoffTags: TextWithStandoffTagsV2 = + StandoffTagUtilV2.convertXMLtoStandoffTagV2( + xml = textValueAsXml, + mapping = mappingResponse, + acceptStandoffLinksToClientIDs = false, + log = log + ) + + TextValueContentV2( + ontologySchema = ApiV2Complex, + maybeValueHasString = Some( + stringFormatter.toSparqlEncodedString( + textWithStandoffTags.text, + throw BadRequestException("Text value contains invalid characters") + ) + ), + valueHasLanguage = maybeValueHasLanguage, + standoff = textWithStandoffTags.standoffTagV2, + mappingIri = Some(mappingResponse.mappingIri), + mapping = Some(mappingResponse.mapping), + comment = getComment(jsonLDObject) + ) + + case _ => + throw BadRequestException( + s"Invalid combination of knora-api:valueHasString, knora-api:textValueAsXml, and/or knora-api:textValueHasMapping" + ) + } } yield textValue } @@ -3173,25 +3198,25 @@ object FileValueWithSipiMetadata { for { // The submitted value provides only Sipi's internal filename for the file. internalFilename <- Future( - jsonLDObject.requireStringWithValidation( - OntologyConstants.KnoraApiV2Complex.FileValueHasFilename, - stringFormatter.toSparqlEncodedString - ) - ) + jsonLDObject.requireStringWithValidation( + OntologyConstants.KnoraApiV2Complex.FileValueHasFilename, + stringFormatter.toSparqlEncodedString + ) + ) // Ask Sipi about the rest of the file's metadata. tempFileUrl = stringFormatter.makeSipiTempFileUrl(settings, internalFilename) fileMetadataResponse: GetFileMetadataResponse <- (storeManager ? GetFileMetadataRequest( - fileUrl = tempFileUrl, - requestingUser = requestingUser - )).mapTo[GetFileMetadataResponse] + fileUrl = tempFileUrl, + requestingUser = requestingUser + )).mapTo[GetFileMetadataResponse] fileValue = FileValueV2( - internalFilename = internalFilename, - internalMimeType = fileMetadataResponse.internalMimeType, - originalFilename = fileMetadataResponse.originalFilename, - originalMimeType = fileMetadataResponse.originalMimeType - ) + internalFilename = internalFilename, + internalMimeType = fileMetadataResponse.internalMimeType, + originalFilename = fileMetadataResponse.originalFilename, + originalMimeType = fileMetadataResponse.originalMimeType + ) } yield FileValueWithSipiMetadata(fileValue, fileMetadataResponse) } } @@ -3317,19 +3342,19 @@ object StillImageFileValueContentV2 extends ValueContentReaderV2[StillImageFileV for { fileValueWithSipiMetadata <- FileValueWithSipiMetadata.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - settings = settings, - log = log - ) + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + settings = settings, + log = log + ) _ = if (!settings.imageMimeTypes.contains(fileValueWithSipiMetadata.fileValue.internalMimeType)) { - throw BadRequestException( - s"File ${fileValueWithSipiMetadata.fileValue.internalFilename} has MIME type ${fileValueWithSipiMetadata.fileValue.internalMimeType}, which is not supported for still image files" - ) - } + throw BadRequestException( + s"File ${fileValueWithSipiMetadata.fileValue.internalFilename} has MIME type ${fileValueWithSipiMetadata.fileValue.internalMimeType}, which is not supported for still image files" + ) + } } yield StillImageFileValueContentV2( ontologySchema = ApiV2Complex, fileValue = fileValueWithSipiMetadata.fileValue, @@ -3498,19 +3523,19 @@ object DocumentFileValueContentV2 extends ValueContentReaderV2[DocumentFileValue for { fileValueWithSipiMetadata <- FileValueWithSipiMetadata.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - settings = settings, - log = log - ) + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + settings = settings, + log = log + ) _ = if (!settings.documentMimeTypes.contains(fileValueWithSipiMetadata.fileValue.internalMimeType)) { - throw BadRequestException( - s"File ${fileValueWithSipiMetadata.fileValue.internalFilename} has MIME type ${fileValueWithSipiMetadata.fileValue.internalMimeType}, which is not supported for document files" - ) - } + throw BadRequestException( + s"File ${fileValueWithSipiMetadata.fileValue.internalFilename} has MIME type ${fileValueWithSipiMetadata.fileValue.internalMimeType}, which is not supported for document files" + ) + } } yield DocumentFileValueContentV2( ontologySchema = ApiV2Complex, fileValue = fileValueWithSipiMetadata.fileValue, @@ -3539,19 +3564,19 @@ object ArchiveFileValueContentV2 extends ValueContentReaderV2[ArchiveFileValueCo for { fileValueWithSipiMetadata <- FileValueWithSipiMetadata.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - settings = settings, - log = log - ) + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + settings = settings, + log = log + ) _ = if (!settings.archiveMimeTypes.contains(fileValueWithSipiMetadata.fileValue.internalMimeType)) { - throw BadRequestException( - s"File ${fileValueWithSipiMetadata.fileValue.internalFilename} has MIME type ${fileValueWithSipiMetadata.fileValue.internalMimeType}, which is not supported for archive files" - ) - } + throw BadRequestException( + s"File ${fileValueWithSipiMetadata.fileValue.internalFilename} has MIME type ${fileValueWithSipiMetadata.fileValue.internalMimeType}, which is not supported for archive files" + ) + } } yield ArchiveFileValueContentV2( ontologySchema = ApiV2Complex, fileValue = fileValueWithSipiMetadata.fileValue, @@ -3635,19 +3660,19 @@ object TextFileValueContentV2 extends ValueContentReaderV2[TextFileValueContentV for { fileValueWithSipiMetadata <- FileValueWithSipiMetadata.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - settings = settings, - log = log - ) + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + settings = settings, + log = log + ) _ = if (!settings.textMimeTypes.contains(fileValueWithSipiMetadata.fileValue.internalMimeType)) { - throw BadRequestException( - s"File ${fileValueWithSipiMetadata.fileValue.internalFilename} has MIME type ${fileValueWithSipiMetadata.fileValue.internalMimeType}, which is not supported for text files" - ) - } + throw BadRequestException( + s"File ${fileValueWithSipiMetadata.fileValue.internalFilename} has MIME type ${fileValueWithSipiMetadata.fileValue.internalMimeType}, which is not supported for text files" + ) + } } yield TextFileValueContentV2( ontologySchema = ApiV2Complex, fileValue = fileValueWithSipiMetadata.fileValue, @@ -3733,19 +3758,19 @@ object AudioFileValueContentV2 extends ValueContentReaderV2[AudioFileValueConten for { fileValueWithSipiMetadata <- FileValueWithSipiMetadata.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - settings = settings, - log = log - ) + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + settings = settings, + log = log + ) _ = if (!settings.audioMimeTypes.contains(fileValueWithSipiMetadata.fileValue.internalMimeType)) { - throw BadRequestException( - s"File ${fileValueWithSipiMetadata.fileValue.internalFilename} has MIME type ${fileValueWithSipiMetadata.fileValue.internalMimeType}, which is not supported for audio files" - ) - } + throw BadRequestException( + s"File ${fileValueWithSipiMetadata.fileValue.internalFilename} has MIME type ${fileValueWithSipiMetadata.fileValue.internalMimeType}, which is not supported for audio files" + ) + } } yield AudioFileValueContentV2( ontologySchema = ApiV2Complex, fileValue = fileValueWithSipiMetadata.fileValue, @@ -3836,19 +3861,19 @@ object MovingImageFileValueContentV2 extends ValueContentReaderV2[MovingImageFil for { fileValueWithSipiMetadata <- FileValueWithSipiMetadata.fromJsonLDObject( - jsonLDObject = jsonLDObject, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - settings = settings, - log = log - ) + jsonLDObject = jsonLDObject, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + settings = settings, + log = log + ) _ = if (!settings.videoMimeTypes.contains(fileValueWithSipiMetadata.fileValue.internalMimeType)) { - throw BadRequestException( - s"File ${fileValueWithSipiMetadata.fileValue.internalFilename} has MIME type ${fileValueWithSipiMetadata.fileValue.internalMimeType}, which is not supported for video files" - ) - } + throw BadRequestException( + s"File ${fileValueWithSipiMetadata.fileValue.internalFilename} has MIME type ${fileValueWithSipiMetadata.fileValue.internalMimeType}, which is not supported for video files" + ) + } } yield MovingImageFileValueContentV2( ontologySchema = ApiV2Complex, fileValue = fileValueWithSipiMetadata.fileValue, diff --git a/webapi/src/main/scala/org/knora/webapi/responders/Responder.scala b/webapi/src/main/scala/org/knora/webapi/responders/Responder.scala index 8ac4352000..7b584dde9f 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/Responder.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/Responder.scala @@ -101,7 +101,7 @@ abstract class Responder(responderData: ResponderData) extends LazyLogging { /** * Provides logging */ - protected val log: Logger = logger + protected val log: Logger = logger protected val loggingAdapter: LoggingAdapter = akka.event.Logging(system, this.getClass) /** @@ -120,17 +120,17 @@ abstract class Responder(responderData: ResponderData) extends LazyLogging { ): Future[Boolean] = for { isEntityUsedSparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .isEntityUsed( - entityIri = entityIri, - ignoreKnoraConstraints = ignoreKnoraConstraints, - ignoreRdfSubjectAndObject = ignoreRdfSubjectAndObject - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v2.txt + .isEntityUsed( + entityIri = entityIri, + ignoreKnoraConstraints = ignoreKnoraConstraints, + ignoreRdfSubjectAndObject = ignoreRdfSubjectAndObject + ) + .toString() + ) isEntityUsedResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(isEntityUsedSparql)) - .mapTo[SparqlSelectResult] + .mapTo[SparqlSelectResult] } yield isEntityUsedResponse.results.bindings.nonEmpty @@ -146,15 +146,15 @@ abstract class Responder(responderData: ResponderData) extends LazyLogging { ): Future[Boolean] = for { isClassUsedInDataSparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .isClassUsedInData( - classIri = classIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v2.txt + .isClassUsedInData( + classIri = classIri + ) + .toString() + ) isClassUsedInDataResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(isClassUsedInDataSparql)) - .mapTo[SparqlSelectResult] + .mapTo[SparqlSelectResult] } yield isClassUsedInDataResponse.results.bindings.nonEmpty @@ -176,8 +176,8 @@ abstract class Responder(responderData: ResponderData) extends LazyLogging { entityIsUsed: Boolean <- isEntityUsed(entityIri, ignoreKnoraConstraints, ignoreRdfSubjectAndObject) _ = if (entityIsUsed) { - errorFun - } + errorFun + } } yield () /** @@ -194,8 +194,8 @@ abstract class Responder(responderData: ResponderData) extends LazyLogging { classIsUsed: Boolean <- isClassUsedInData(classIri) _ = if (classIsUsed) { - errorFun - } + errorFun + } } yield () /** @@ -214,14 +214,14 @@ abstract class Responder(responderData: ResponderData) extends LazyLogging { result <- stringFormatter.checkIriExists(entityIriAsString, storeManager) _ = if (result) { - throw DuplicateValueException(s"IRI: '$entityIriAsString' already exists, try another one.") - } + throw DuplicateValueException(s"IRI: '$entityIriAsString' already exists, try another one.") + } // Check that given entityIRI ends with a UUID ending: String = entityIriAsString.split('/').last _ = stringFormatter.validateBase64EncodedUuid( - ending, - throw BadRequestException(s"IRI: '$entityIriAsString' must end with a valid base 64 UUID.") - ) + ending, + throw BadRequestException(s"IRI: '$entityIriAsString' must end with a valid base 64 UUID.") + ) } yield entityIriAsString diff --git a/webapi/src/main/scala/org/knora/webapi/responders/admin/GroupsResponderADM.scala b/webapi/src/main/scala/org/knora/webapi/responders/admin/GroupsResponderADM.scala index eb9b934225..5c6955d040 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/admin/GroupsResponderADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/admin/GroupsResponderADM.scala @@ -91,87 +91,104 @@ class GroupsResponderADM(responderData: ResponderData) extends Responder(respond for { sparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .getGroups( - maybeIri = None - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .getGroups( + maybeIri = None + ) + .toString() + ) groupsResponse <- (storeManager ? SparqlExtendedConstructRequest( - sparql = sparqlQuery, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + sparql = sparqlQuery, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse] statements = groupsResponse.statements groups: Seq[Future[GroupADM]] = statements.map { - case (groupIri: SubjectV2, propsMap: Map[SmartIri, Seq[LiteralV2]]) => - val projectIri: IRI = propsMap - .getOrElse( - OntologyConstants.KnoraAdmin.BelongsToProject.toSmartIri, - throw InconsistentRepositoryDataException(s"Group $groupIri has no project attached") - ) - .head - .asInstanceOf[IriLiteralV2] - .value - - for { - maybeProjectADM: Option[ProjectADM] <- (responderManager ? ProjectGetADM( - identifier = ProjectIdentifierADM(maybeIri = Some(projectIri)), - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - )).mapTo[Option[ProjectADM]] - - projectADM: ProjectADM = maybeProjectADM match { - case Some(project) => project - case None => - throw InconsistentRepositoryDataException( - s"Project $projectIri was referenced by $groupIri but was not found in the triplestore." - ) - } - - group = GroupADM( - id = groupIri.toString, - name = propsMap - .getOrElse( - OntologyConstants.KnoraAdmin.GroupName.toSmartIri, - throw InconsistentRepositoryDataException(s"Group $groupIri has no name attached") - ) - .head - .asInstanceOf[StringLiteralV2] - .value, - descriptions = propsMap - .getOrElse( - OntologyConstants.KnoraAdmin.GroupDescriptions.toSmartIri, - throw InconsistentRepositoryDataException(s"Group $groupIri has no descriptions attached") - ) - .map(l => - l.asStringLiteral( - throw InconsistentRepositoryDataException(s"Expected StringLiteralV2 but got ${l.getClass}") - ) - ), - project = projectADM, - status = propsMap - .getOrElse( - OntologyConstants.KnoraAdmin.Status.toSmartIri, - throw InconsistentRepositoryDataException(s"Group $groupIri has no status attached") - ) - .head - .asInstanceOf[BooleanLiteralV2] - .value, - selfjoin = propsMap - .getOrElse( - OntologyConstants.KnoraAdmin.HasSelfJoinEnabled.toSmartIri, - throw InconsistentRepositoryDataException(s"Group $groupIri has no status attached") - ) - .head - .asInstanceOf[BooleanLiteralV2] - .value - ) - - } yield group - }.toSeq + case (groupIri: SubjectV2, propsMap: Map[SmartIri, Seq[LiteralV2]]) => + val projectIri: IRI = propsMap + .getOrElse( + OntologyConstants.KnoraAdmin.BelongsToProject.toSmartIri, + throw InconsistentRepositoryDataException( + s"Group $groupIri has no project attached" + ) + ) + .head + .asInstanceOf[IriLiteralV2] + .value + + for { + maybeProjectADM: Option[ProjectADM] <- (responderManager ? ProjectGetADM( + identifier = + ProjectIdentifierADM(maybeIri = + Some(projectIri) + ), + featureFactoryConfig = + featureFactoryConfig, + requestingUser = + KnoraSystemInstances.Users.SystemUser + )).mapTo[Option[ProjectADM]] + + projectADM: ProjectADM = maybeProjectADM match { + case Some(project) => project + case None => + throw InconsistentRepositoryDataException( + s"Project $projectIri was referenced by $groupIri but was not found in the triplestore." + ) + } + + group = GroupADM( + id = groupIri.toString, + name = propsMap + .getOrElse( + OntologyConstants.KnoraAdmin.GroupName.toSmartIri, + throw InconsistentRepositoryDataException( + s"Group $groupIri has no name attached" + ) + ) + .head + .asInstanceOf[StringLiteralV2] + .value, + descriptions = propsMap + .getOrElse( + OntologyConstants.KnoraAdmin.GroupDescriptions.toSmartIri, + throw InconsistentRepositoryDataException( + s"Group $groupIri has no descriptions attached" + ) + ) + .map(l => + l.asStringLiteral( + throw InconsistentRepositoryDataException( + s"Expected StringLiteralV2 but got ${l.getClass}" + ) + ) + ), + project = projectADM, + status = propsMap + .getOrElse( + OntologyConstants.KnoraAdmin.Status.toSmartIri, + throw InconsistentRepositoryDataException( + s"Group $groupIri has no status attached" + ) + ) + .head + .asInstanceOf[BooleanLiteralV2] + .value, + selfjoin = propsMap + .getOrElse( + OntologyConstants.KnoraAdmin.HasSelfJoinEnabled.toSmartIri, + throw InconsistentRepositoryDataException( + s"Group $groupIri has no status attached" + ) + ) + .head + .asInstanceOf[BooleanLiteralV2] + .value + ) + + } yield group + }.toSeq result: Seq[GroupADM] <- Future.sequence(groups) } yield result.sorted } @@ -188,14 +205,14 @@ class GroupsResponderADM(responderData: ResponderData) extends Responder(respond ): Future[GroupsGetResponseADM] = for { maybeGroupsListToReturn <- groupsGetADM( - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) result = maybeGroupsListToReturn match { - case groups: Seq[GroupADM] if groups.nonEmpty => GroupsGetResponseADM(groups = groups) - case _ => throw NotFoundException(s"No groups found") - } + case groups: Seq[GroupADM] if groups.nonEmpty => GroupsGetResponseADM(groups = groups) + case _ => throw NotFoundException(s"No groups found") + } } yield result /** @@ -212,17 +229,17 @@ class GroupsResponderADM(responderData: ResponderData) extends Responder(respond ): Future[Option[GroupADM]] = for { sparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .getGroups( - maybeIri = Some(groupIri) - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .getGroups( + maybeIri = Some(groupIri) + ) + .toString() + ) groupResponse <- (storeManager ? SparqlExtendedConstructRequest( - sparql = sparqlQuery, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + sparql = sparqlQuery, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse] maybeGroup: Option[GroupADM] <- if (groupResponse.statements.isEmpty) { @@ -254,15 +271,15 @@ class GroupsResponderADM(responderData: ResponderData) extends Responder(respond ): Future[GroupGetResponseADM] = for { maybeGroupADM: Option[GroupADM] <- groupGetADM( - groupIri = groupIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + groupIri = groupIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) result = maybeGroupADM match { - case Some(group) => GroupGetResponseADM(group = group) - case None => throw NotFoundException(s"Group <$groupIri> not found") - } + case Some(group) => GroupGetResponseADM(group = group) + case None => throw NotFoundException(s"Group <$groupIri> not found") + } } yield result /** @@ -306,33 +323,33 @@ class GroupsResponderADM(responderData: ResponderData) extends Responder(respond for { maybeGroupADM: Option[GroupADM] <- groupGetADM( - groupIri = groupIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + groupIri = groupIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) _ = maybeGroupADM match { - case Some(group) => - // check if the requesting user is allowed to access the information - if ( - !requestingUser.permissions.isProjectAdmin( - group.project.id - ) && !requestingUser.permissions.isSystemAdmin && !requestingUser.isSystemUser - ) { - // not a project admin and not a system admin - throw ForbiddenException("Project members can only be retrieved by a project or system admin.") + case Some(group) => + // check if the requesting user is allowed to access the information + if ( + !requestingUser.permissions.isProjectAdmin( + group.project.id + ) && !requestingUser.permissions.isSystemAdmin && !requestingUser.isSystemUser + ) { + // not a project admin and not a system admin + throw ForbiddenException("Project members can only be retrieved by a project or system admin.") + } + case None => + throw NotFoundException(s"Group <$groupIri> not found") } - case None => - throw NotFoundException(s"Group <$groupIri> not found") - } sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getGroupMembersByIri( - groupIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getGroupMembersByIri( + groupIri + ) + .toString() + ) //_ = log.debug(s"groupMembersByIRIGetRequestV1 - query: $sparqlQueryString") groupMembersResponse <- (storeManager ? SparqlSelectRequest(sparqlQueryString)).mapTo[SparqlSelectResult] @@ -349,15 +366,15 @@ class GroupsResponderADM(responderData: ResponderData) extends Responder(respond _ = log.debug("groupMembersGetRequestADM - groupMemberIris: {}", groupMemberIris) maybeUsersFutures: Seq[Future[Option[UserADM]]] = groupMemberIris.map { userIri => - (responderManager ? UserGetADM( - UserIdentifierADM(maybeIri = Some(userIri)), - userInformationTypeADM = UserInformationTypeADM.Restricted, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - )).mapTo[Option[UserADM]] - } + (responderManager ? UserGetADM( + UserIdentifierADM(maybeIri = Some(userIri)), + userInformationTypeADM = UserInformationTypeADM.Restricted, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + )).mapTo[Option[UserADM]] + } maybeUsers: Seq[Option[UserADM]] <- Future.sequence(maybeUsersFutures) - users: Seq[UserADM] = maybeUsers.flatten + users: Seq[UserADM] = maybeUsers.flatten _ = log.debug("groupMembersGetRequestADM - users: {}", users) @@ -383,15 +400,15 @@ class GroupsResponderADM(responderData: ResponderData) extends Responder(respond for { maybeMembersListToReturn <- groupMembersGetADM( - groupIri = groupIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + groupIri = groupIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) result = maybeMembersListToReturn match { - case members: Seq[UserADM] if members.nonEmpty => GroupMembersGetResponseADM(members = members) - case _ => throw NotFoundException(s"No members found.") - } + case members: Seq[UserADM] if members.nonEmpty => GroupMembersGetResponseADM(members = members) + case _ => throw NotFoundException(s"No members found.") + } } yield result } @@ -421,81 +438,83 @@ class GroupsResponderADM(responderData: ResponderData) extends Responder(respond for { /* check if the requesting user is allowed to create group */ _ <- Future( - if ( - !requestingUser.permissions - .isProjectAdmin(createRequest.project.value) && !requestingUser.permissions.isSystemAdmin - ) { - // not a project admin and not a system admin - throw ForbiddenException("A new group can only be created by a project or system admin.") - } - ) + if ( + !requestingUser.permissions + .isProjectAdmin(createRequest.project.value) && !requestingUser.permissions.isSystemAdmin + ) { + // not a project admin and not a system admin + throw ForbiddenException("A new group can only be created by a project or system admin.") + } + ) nameExists <- groupByNameAndProjectExists( - name = createRequest.name.value, - projectIri = createRequest.project.value - ) + name = createRequest.name.value, + projectIri = createRequest.project.value + ) _ = if (nameExists) { - throw DuplicateValueException(s"Group with the name '${createRequest.name.value}' already exists") - } + throw DuplicateValueException(s"Group with the name '${createRequest.name.value}' already exists") + } maybeProjectADM: Option[ProjectADM] <- (responderManager ? ProjectGetADM( - identifier = ProjectIdentifierADM(maybeIri = Some(createRequest.project.value)), - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - )).mapTo[Option[ProjectADM]] + identifier = + ProjectIdentifierADM(maybeIri = Some(createRequest.project.value)), + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + )).mapTo[Option[ProjectADM]] projectADM: ProjectADM = maybeProjectADM match { - case Some(p) => p - case None => - throw NotFoundException( - s"Cannot create group inside project <${createRequest.project}>. The project was not found." - ) - } + case Some(p) => p + case None => + throw NotFoundException( + s"Cannot create group inside project <${createRequest.project}>. The project was not found." + ) + } // check the custom IRI; if not given, create an unused IRI customGroupIri: Option[SmartIri] = createRequest.id.map(_.value).map(iri => iri.toSmartIri) groupIri: IRI <- checkOrCreateEntityIri( - customGroupIri, - stringFormatter.makeRandomGroupIri(projectADM.shortcode) - ) + customGroupIri, + stringFormatter.makeRandomGroupIri(projectADM.shortcode) + ) /* create the group */ createNewGroupSparqlString = org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .createNewGroup( - adminNamedGraphIri = OntologyConstants.NamedGraphs.AdminNamedGraph, - groupIri, - groupClassIri = OntologyConstants.KnoraAdmin.UserGroup, - name = createRequest.name.value, - descriptions = createRequest.descriptions.value, - projectIri = createRequest.project.value, - status = createRequest.status.value, - hasSelfJoinEnabled = createRequest.selfjoin.value - ) - .toString + .createNewGroup( + adminNamedGraphIri = OntologyConstants.NamedGraphs.AdminNamedGraph, + groupIri, + groupClassIri = OntologyConstants.KnoraAdmin.UserGroup, + name = createRequest.name.value, + descriptions = createRequest.descriptions.value, + projectIri = createRequest.project.value, + status = createRequest.status.value, + hasSelfJoinEnabled = createRequest.selfjoin.value + ) + .toString _ <- (storeManager ? SparqlUpdateRequest(createNewGroupSparqlString)) - .mapTo[SparqlUpdateResponse] + .mapTo[SparqlUpdateResponse] /* Verify that the group was created and updated */ maybeCreatedGroup <- groupGetADM( - groupIri = groupIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) - - createdGroup: GroupADM = maybeCreatedGroup.getOrElse( - throw UpdateNotPerformedException(s"Group was not created. Please report this as a possible bug.") - ) + groupIri = groupIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) + + createdGroup: GroupADM = + maybeCreatedGroup.getOrElse( + throw UpdateNotPerformedException(s"Group was not created. Please report this as a possible bug.") + ) } yield GroupOperationResponseADM(group = createdGroup) for { // run user creation with an global IRI lock taskResult <- IriLocker.runWithIriLock( - apiRequestID, - GROUPS_GLOBAL_LOCK_IRI, - () => createGroupTask(createRequest, requestingUser, apiRequestID) - ) + apiRequestID, + GROUPS_GLOBAL_LOCK_IRI, + () => createGroupTask(createRequest, requestingUser, apiRequestID) + ) } yield taskResult } @@ -528,53 +547,54 @@ class GroupsResponderADM(responderData: ResponderData) extends Responder(respond for { _ <- Future( - // check if necessary information is present - if (groupIri.isEmpty) throw BadRequestException("Group IRI cannot be empty") - ) + // check if necessary information is present + if (groupIri.isEmpty) throw BadRequestException("Group IRI cannot be empty") + ) /* Get the project IRI which also verifies that the group exists. */ maybeGroupADM <- groupGetADM( - groupIri = groupIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + groupIri = groupIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) groupADM: GroupADM = maybeGroupADM.getOrElse( - throw NotFoundException(s"Group <$groupIri> not found. Aborting update request.") - ) + throw NotFoundException(s"Group <$groupIri> not found. Aborting update request.") + ) /* check if the requesting user is allowed to perform updates */ - _ = if ( - !requestingUser.permissions.isProjectAdmin(groupADM.project.id) && !requestingUser.permissions.isSystemAdmin - ) { - // not a project admin and not a system admin - throw ForbiddenException("Group's information can only be changed by a project or system admin.") - } + _ = + if ( + !requestingUser.permissions.isProjectAdmin(groupADM.project.id) && !requestingUser.permissions.isSystemAdmin + ) { + // not a project admin and not a system admin + throw ForbiddenException("Group's information can only be changed by a project or system admin.") + } /* create the update request */ groupUpdatePayload = GroupUpdatePayloadADM( - name = changeGroupRequest.name, - descriptions = changeGroupRequest.descriptions, - status = changeGroupRequest.status, - selfjoin = changeGroupRequest.selfjoin - ) + name = changeGroupRequest.name, + descriptions = changeGroupRequest.descriptions, + status = changeGroupRequest.status, + selfjoin = changeGroupRequest.selfjoin + ) result <- updateGroupADM( - groupIri = groupIri, - groupUpdatePayload = groupUpdatePayload, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + groupIri = groupIri, + groupUpdatePayload = groupUpdatePayload, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) } yield result for { // run the change status task with an IRI lock taskResult <- IriLocker.runWithIriLock( - apiRequestID, - groupIri, - () => changeGroupTask(groupIri, changeGroupRequest, requestingUser) - ) + apiRequestID, + groupIri, + () => changeGroupTask(groupIri, changeGroupRequest, requestingUser) + ) } yield taskResult } @@ -608,63 +628,65 @@ class GroupsResponderADM(responderData: ResponderData) extends Responder(respond for { _ <- Future( - // check if necessary information is present - if (groupIri.isEmpty) throw BadRequestException("Group IRI cannot be empty") - ) + // check if necessary information is present + if (groupIri.isEmpty) throw BadRequestException("Group IRI cannot be empty") + ) /* Get the project IRI which also verifies that the group exists. */ maybeGroupADM <- groupGetADM( - groupIri = groupIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + groupIri = groupIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) groupADM: GroupADM = maybeGroupADM.getOrElse( - throw NotFoundException(s"Group <$groupIri> not found. Aborting update request.") - ) + throw NotFoundException(s"Group <$groupIri> not found. Aborting update request.") + ) /* check if the requesting user is allowed to perform updates */ - _ = if ( - !requestingUser.permissions.isProjectAdmin(groupADM.project.id) && !requestingUser.permissions.isSystemAdmin - ) { - // not a project admin and not a system admin - throw ForbiddenException("Group's status can only be changed by a project or system admin.") - } + _ = + if ( + !requestingUser.permissions.isProjectAdmin(groupADM.project.id) && !requestingUser.permissions.isSystemAdmin + ) { + // not a project admin and not a system admin + throw ForbiddenException("Group's status can only be changed by a project or system admin.") + } maybeStatus: Option[GroupStatus] = changeGroupRequest.status match { - case Some(value) => Some(GroupStatus.make(value).fold(e => throw e.head, v => v)) - case None => None - } + case Some(value) => + Some(GroupStatus.make(value).fold(e => throw e.head, v => v)) + case None => None + } /* create the update request */ groupUpdatePayload = GroupUpdatePayloadADM( - status = maybeStatus - ) + status = maybeStatus + ) // update group status updateGroupResult: GroupOperationResponseADM <- updateGroupADM( - groupIri = groupIri, - groupUpdatePayload = groupUpdatePayload, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + groupIri = groupIri, + groupUpdatePayload = groupUpdatePayload, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) // remove all members from group if status is false operationResponse <- removeGroupMembersIfNecessary( - changedGroup = updateGroupResult.group, - featureFactoryConfig = featureFactoryConfig, - apiRequestID = apiRequestID - ) + changedGroup = updateGroupResult.group, + featureFactoryConfig = featureFactoryConfig, + apiRequestID = apiRequestID + ) } yield operationResponse for { // run the change status task with an IRI lock taskResult <- IriLocker.runWithIriLock( - apiRequestID, - groupIri, - () => changeGroupStatusTask(groupIri, changeGroupRequest, requestingUser) - ) + apiRequestID, + groupIri, + () => changeGroupStatusTask(groupIri, changeGroupRequest, requestingUser) + ) } yield taskResult } @@ -699,14 +721,14 @@ class GroupsResponderADM(responderData: ResponderData) extends Responder(respond for { /* Verify that the group exists. */ maybeGroupADM <- groupGetADM( - groupIri = groupIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + groupIri = groupIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) groupADM: GroupADM = maybeGroupADM.getOrElse( - throw NotFoundException(s"Group <$groupIri> not found. Aborting update request.") - ) + throw NotFoundException(s"Group <$groupIri> not found. Aborting update request.") + ) /* Verify that the potentially new name is unique */ groupByNameAlreadyExists <- @@ -718,38 +740,40 @@ class GroupsResponderADM(responderData: ResponderData) extends Responder(respond } _ = if (groupByNameAlreadyExists) { - log.debug("updateGroupADM - about to throw an exception. Group with that name already exists.") - throw BadRequestException(s"Group with the name '${groupUpdatePayload.name.get}' already exists.") - } + log.debug("updateGroupADM - about to throw an exception. Group with that name already exists.") + throw BadRequestException(s"Group with the name '${groupUpdatePayload.name.get}' already exists.") + } /* Update group */ updateGroupSparqlString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .updateGroup( - adminNamedGraphIri = "http://www.knora.org/data/admin", - groupIri, - maybeName = groupUpdatePayload.name.map(_.value), - maybeDescriptions = groupUpdatePayload.descriptions.map(_.value), - maybeProject = None, // maybe later we want to allow moving of a group to another project - maybeStatus = groupUpdatePayload.status.map(_.value), - maybeSelfjoin = groupUpdatePayload.selfjoin.map(_.value) - ) - .toString - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .updateGroup( + adminNamedGraphIri = "http://www.knora.org/data/admin", + groupIri, + maybeName = groupUpdatePayload.name.map(_.value), + maybeDescriptions = groupUpdatePayload.descriptions.map(_.value), + maybeProject = + None, // maybe later we want to allow moving of a group to another project + maybeStatus = groupUpdatePayload.status.map(_.value), + maybeSelfjoin = groupUpdatePayload.selfjoin.map(_.value) + ) + .toString + ) //_ = log.debug(s"updateProjectV1 - query: {}",updateProjectSparqlString) _ <- (storeManager ? SparqlUpdateRequest(updateGroupSparqlString)).mapTo[SparqlUpdateResponse] /* Verify that the project was updated. */ maybeUpdatedGroup <- groupGetADM( - groupIri = groupIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) - - updatedGroup: GroupADM = maybeUpdatedGroup.getOrElse( - throw UpdateNotPerformedException("Group was not updated. Please report this as a possible bug.") - ) + groupIri = groupIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) + + updatedGroup: GroupADM = + maybeUpdatedGroup.getOrElse( + throw UpdateNotPerformedException("Group was not updated. Please report this as a possible bug.") + ) //_ = log.debug("updateProjectV1 - projectUpdatePayload: {} / updatedProject: {}", projectUpdatePayload, updatedProject) @@ -777,7 +801,7 @@ class GroupsResponderADM(responderData: ResponderData) extends Responder(respond log.debug("statements2GroupADM - statements: {}", statements) - val groupIri: IRI = statements._1.toString + val groupIri: IRI = statements._1.toString val propsMap: Map[SmartIri, Seq[LiteralV2]] = statements._2 log.debug("statements2GroupADM - groupIri: {}", groupIri) @@ -793,53 +817,61 @@ class GroupsResponderADM(responderData: ResponderData) extends Responder(respond for { projectIri <- projectIriFuture maybeProject: Option[ProjectADM] <- (responderManager ? ProjectGetADM( - identifier = ProjectIdentifierADM(maybeIri = Some(projectIri)), - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - )).mapTo[Option[ProjectADM]] + identifier = ProjectIdentifierADM(maybeIri = Some(projectIri)), + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + )).mapTo[Option[ProjectADM]] project: ProjectADM = maybeProject.getOrElse( - throw InconsistentRepositoryDataException(s"Group $groupIri has no project attached.") - ) + throw InconsistentRepositoryDataException(s"Group $groupIri has no project attached.") + ) groupADM: GroupADM = GroupADM( - id = groupIri, - name = propsMap - .getOrElse( - OntologyConstants.KnoraAdmin.GroupName.toSmartIri, - throw InconsistentRepositoryDataException(s"Group $groupIri has no groupName attached") - ) - .head - .asInstanceOf[StringLiteralV2] - .value, - descriptions = propsMap - .getOrElse( - OntologyConstants.KnoraAdmin.GroupDescriptions.toSmartIri, - throw InconsistentRepositoryDataException(s"Group $groupIri has no descriptions attached") - ) - .map(l => - l.asStringLiteral( - throw InconsistentRepositoryDataException(s"Expected StringLiteralV2 but got ${l.getClass}") - ) - ), - project = project, - status = propsMap - .getOrElse( - OntologyConstants.KnoraAdmin.Status.toSmartIri, - throw InconsistentRepositoryDataException(s"Group $groupIri has no status attached") - ) - .head - .asInstanceOf[BooleanLiteralV2] - .value, - selfjoin = propsMap - .getOrElse( - OntologyConstants.KnoraAdmin.HasSelfJoinEnabled.toSmartIri, - throw InconsistentRepositoryDataException(s"Group $groupIri has no selfJoin attached") - ) - .head - .asInstanceOf[BooleanLiteralV2] - .value - ) + id = groupIri, + name = propsMap + .getOrElse( + OntologyConstants.KnoraAdmin.GroupName.toSmartIri, + throw InconsistentRepositoryDataException( + s"Group $groupIri has no groupName attached" + ) + ) + .head + .asInstanceOf[StringLiteralV2] + .value, + descriptions = propsMap + .getOrElse( + OntologyConstants.KnoraAdmin.GroupDescriptions.toSmartIri, + throw InconsistentRepositoryDataException( + s"Group $groupIri has no descriptions attached" + ) + ) + .map(l => + l.asStringLiteral( + throw InconsistentRepositoryDataException( + s"Expected StringLiteralV2 but got ${l.getClass}" + ) + ) + ), + project = project, + status = propsMap + .getOrElse( + OntologyConstants.KnoraAdmin.Status.toSmartIri, + throw InconsistentRepositoryDataException(s"Group $groupIri has no status attached") + ) + .head + .asInstanceOf[BooleanLiteralV2] + .value, + selfjoin = propsMap + .getOrElse( + OntologyConstants.KnoraAdmin.HasSelfJoinEnabled.toSmartIri, + throw InconsistentRepositoryDataException( + s"Group $groupIri has no selfJoin attached" + ) + ) + .head + .asInstanceOf[BooleanLiteralV2] + .value + ) } yield Some(groupADM) } else { FastFuture.successful(None) @@ -855,12 +887,12 @@ class GroupsResponderADM(responderData: ResponderData) extends Responder(respond private def groupExists(groupIri: IRI): Future[Boolean] = for { askString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt.checkGroupExistsByIri(groupIri).toString - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt.checkGroupExistsByIri(groupIri).toString + ) //_ = log.debug("groupExists - query: {}", askString) checkGroupExistsResponse <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] - result = checkGroupExistsResponse.result + result = checkGroupExistsResponse.result } yield result @@ -874,14 +906,14 @@ class GroupsResponderADM(responderData: ResponderData) extends Responder(respond private def groupByNameAndProjectExists(name: String, projectIri: IRI): Future[Boolean] = for { askString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .checkGroupExistsByName(projectIri, name) - .toString - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .checkGroupExistsByName(projectIri, name) + .toString + ) //_ = log.debug("groupExists - query: {}", askString) checkUserExistsResponse <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] - result = checkUserExistsResponse.result + result = checkUserExistsResponse.result _ = log.debug("groupByNameAndProjectExists - name: {}, projectIri: {}, result: {}", name, projectIri, result) } yield result @@ -909,20 +941,21 @@ class GroupsResponderADM(responderData: ResponderData) extends Responder(respond log.debug("removeGroupMembersIfNecessary - group deactivated. need to remove members.") for { members: Seq[UserADM] <- groupMembersGetADM( - groupIri = changedGroup.id, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + groupIri = changedGroup.id, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) seqOfFutures: Seq[Future[UserOperationResponseADM]] = members.map { user: UserADM => - (responderManager ? UserGroupMembershipRemoveRequestADM( - userIri = user.id, - groupIri = changedGroup.id, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser, - apiRequestID = apiRequestID - )).mapTo[UserOperationResponseADM] - } + (responderManager ? UserGroupMembershipRemoveRequestADM( + userIri = user.id, + groupIri = changedGroup.id, + featureFactoryConfig = featureFactoryConfig, + requestingUser = + KnoraSystemInstances.Users.SystemUser, + apiRequestID = apiRequestID + )).mapTo[UserOperationResponseADM] + } userOperationResults: Seq[UserOperationResponseADM] <- Future.sequence(seqOfFutures) } yield GroupOperationResponseADM(group = changedGroup) diff --git a/webapi/src/main/scala/org/knora/webapi/responders/admin/ListsResponderADM.scala b/webapi/src/main/scala/org/knora/webapi/responders/admin/ListsResponderADM.scala index 4cb5f57b62..8e2aa78c48 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/admin/ListsResponderADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/admin/ListsResponderADM.scala @@ -113,17 +113,17 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde // log.debug("listsGetRequestV2") for { sparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .getLists( - maybeProjectIri = projectIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .getLists( + maybeProjectIri = projectIri + ) + .toString() + ) listsResponse <- (storeManager ? SparqlExtendedConstructRequest( - sparql = sparqlQuery, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + sparql = sparqlQuery, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse] // _ = log.debug("listsGetAdminRequest - listsResponse: {}", listsResponse ) @@ -131,32 +131,40 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde 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)) - ).unescape - } + 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)) + ).unescape + } // _ = log.debug("listsGetAdminRequest - items: {}", items) @@ -186,31 +194,31 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde 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 - ) + ofNodeIri = rootNodeIri, + shallow = false, + featureFactoryConfig = featureFactoryConfig, + KnoraSystemInstances.Users.SystemUser + ) maybeRootNodeInfo <- listNodeInfoGetADM( - nodeIri = rootNodeIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + 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(_: 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." - ) - } + case Some(info: ListRootNodeInfoADM) => info.asInstanceOf[ListRootNodeInfoADM] + case Some(_: 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) @@ -241,23 +249,23 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde ): Future[ListNodeGetResponseADM] = for { maybeNodeInfo <- listNodeInfoGetADM( - nodeIri = nodeIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + nodeIri = nodeIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) nodeinfo = maybeNodeInfo match { - case Some(childNodeInfo: ListChildNodeInfoADM) => childNodeInfo - case _ => throw NotFoundException(s"Information not found for node '$nodeIri'") - } + 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 - ) - ) + node = NodeADM( + nodeinfo = nodeinfo, + children = childNode.children + ) + ) } yield entirenode for { @@ -268,35 +276,35 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde for { // Yes. Get the entire list maybeList <- listGetADM( - rootNodeIri = nodeIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + rootNodeIri = nodeIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) entireList = maybeList match { - case Some(list) => ListGetResponseADM(list = list) - case None => throw NotFoundException(s"List '$nodeIri' not found") - } + 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 - ) + 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) + // 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") - } + case _ => throw NotFoundException(s"Node '$nodeIri' not found") + } } yield entireNode } } yield result @@ -318,19 +326,19 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde ): Future[Option[ListNodeInfoADM]] = { for { sparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .getListNode( - nodeIri = nodeIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .getListNode( + nodeIri = nodeIri + ) + .toString() + ) // _ = log.debug("listNodeInfoGetADM - sparqlQuery: {}", sparqlQuery) listNodeResponse <- (storeManager ? SparqlExtendedConstructRequest( - sparql = sparqlQuery, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + sparql = sparqlQuery, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse] statements: Map[SubjectV2, Map[SmartIri, Seq[LiteralV2]]] = listNodeResponse.statements @@ -456,16 +464,16 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde ): Future[NodeInfoGetResponseADM] = for { maybeListNodeInfoADM <- listNodeInfoGetADM( - nodeIri = nodeIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + 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") - } + case Some(childInfo: ListChildNodeInfoADM) => ChildNodeInfoGetResponseADM(childInfo) + case Some(rootInfo: ListRootNodeInfoADM) => RootNodeInfoGetResponseADM(rootInfo) + case _ => throw NotFoundException(s"List node '$nodeIri' not found") + } } yield result /** @@ -486,17 +494,17 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde 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( - nodeIri = nodeIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .getListNode( + nodeIri = nodeIri + ) + .toString() + ) listInfoResponse <- (storeManager ? SparqlExtendedConstructRequest( - sparql = sparqlQuery, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + sparql = sparqlQuery, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse] // _ = log.debug(s"listGetADM - statements: {}", MessageUtil.toSource(listInfoResponse.statements)) @@ -505,11 +513,11 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde 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 - ) + ofNodeIri = nodeIri, + shallow = shallow, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) // _ = log.debug(s"listGetADM - children count: {}", children.size) @@ -517,97 +525,98 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde 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 = Some(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 - ) - } - } + 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 = Some(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) @@ -700,32 +709,32 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde for { nodeChildrenQuery <- Future { - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .getListNodeWithChildren( - startNodeIri = ofNodeIri - ) - .toString() - } + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .getListNodeWithChildren( + startNodeIri = ofNodeIri + ) + .toString() + } nodeWithChildrenResponse <- (storeManager ? SparqlExtendedConstructRequest( - sparql = nodeChildrenQuery, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + 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) - } + OntologyConstants.KnoraBase.HasSubListNode.toSmartIri + ) match { + case Some(iris: Seq[LiteralV2]) => + iris.map { iri => + createChildNode(iri.toString, statements) + } - case None => Seq.empty[ListChildNodeADM] - } + case None => Seq.empty[ListChildNodeADM] + } sortedChildren = children.sortBy(_.position) map (_.sorted) @@ -789,17 +798,17 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde // TODO: Rewrite using a construct sparql query for { nodePathQuery <- Future { - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .getNodePath( - queryNodeIri = queryNodeIri, - preferredLanguage = requestingUser.lang, - fallbackLanguage = settings.fallbackLanguage - ) - .toString() - } + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .getNodePath( + queryNodeIri = queryNodeIri, + preferredLanguage = requestingUser.lang, + fallbackLanguage = settings.fallbackLanguage + ) + .toString() + } nodePathResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(nodePathQuery)) - .mapTo[SparqlSelectResult] + .mapTo[SparqlSelectResult] /* @@ -817,16 +826,16 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde // 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 - }.toMap + row.rowMap("node") -> row.rowMap + }.toMap // 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 - } - } + row.rowMap.get("child") match { + case Some(child) => acc + (child -> row.rowMap("node")) + case None => acc + } + } } yield NodePathGetResponseADM(elements = makePath(queryNodeIri, nodeMap, parentMap, Nil)) } @@ -886,17 +895,28 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde 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 - ) + 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.") - } + 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) @@ -908,13 +928,13 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde 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 - ) + 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. @@ -929,28 +949,28 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde 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(projectIri.value)), - featureFactoryConfig = featureFactoryConfig, - KnoraSystemInstances.Users.SystemUser - )).mapTo[Option[ProjectADM]] + identifier = ProjectIdentifierADM(maybeIri = Some(projectIri.value)), + featureFactoryConfig = featureFactoryConfig, + KnoraSystemInstances.Users.SystemUser + )).mapTo[Option[ProjectADM]] project: ProjectADM = maybeProject match { - case Some(project: ProjectADM) => project - case None => throw BadRequestException(s"Project '${projectIri}' not found.") - } + case Some(project: ProjectADM) => project + case None => throw BadRequestException(s"Project '${projectIri}' not found.") + } /* verify that the list node name is unique for the project */ projectUniqueNodeName <- listNodeNameIsProjectUnique( - projectIri.value, - name - ) + projectIri.value, + name + ) _ = if (!projectUniqueNodeName) { - val escapedName = name.get.value - val unescapedName = stringFormatter.fromSparqlEncodedString(escapedName) - throw BadRequestException( - s"The node name ${unescapedName} is already used by a list inside the project ${projectIri.value}." - ) - } + val escapedName = name.get.value + val unescapedName = stringFormatter.fromSparqlEncodedString(escapedName) + throw BadRequestException( + s"The node name ${unescapedName} is already used by a list inside the project ${projectIri.value}." + ) + } // calculate the data named graph dataNamedGraph: IRI = stringFormatter.projectDataNamedGraphV2(project) @@ -969,56 +989,56 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde // check the custom IRI; if not given, create an unused IRI customListIri: Option[SmartIri] = id.map(_.value).map(_.toSmartIri) - maybeShortcode: String = project.shortcode - newListNodeIri: IRI <- checkOrCreateEntityIri(customListIri, stringFormatter.makeRandomListIri(maybeShortcode)) + maybeShortcode: String = project.shortcode + newListNodeIri: IRI <- checkOrCreateEntityIri(customListIri, stringFormatter.makeRandomListIri(maybeShortcode)) // Create the new list node depending on type createNewListSparqlString: String = createNodeRequest match { - case ListNodeCreatePayloadADM.ListRootNodeCreatePayloadADM( - _, - projectIri, - name, - labels, - comments - ) => - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .createNewListNode( - dataNamedGraph = dataNamedGraph, - listClassIri = OntologyConstants.KnoraBase.ListNode, - projectIri = projectIri.value, - nodeIri = newListNodeIri, - parentNodeIri = None, - rootNodeIri = rootNodeIri, - position = None, - maybeName = name.map(_.value), - maybeLabels = labels.value, - maybeComments = Some(comments.value) - ) - .toString - case ListNodeCreatePayloadADM.ListChildNodeCreatePayloadADM( - _, - parentNodeIri, - projectIri, - name, - position, - labels, - comments - ) => - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .createNewListNode( - dataNamedGraph = dataNamedGraph, - listClassIri = OntologyConstants.KnoraBase.ListNode, - projectIri = projectIri.value, - nodeIri = newListNodeIri, - parentNodeIri = Some(parentNodeIri.value), - rootNodeIri = rootNodeIri, - position = newPosition, - maybeName = name.map(_.value), - maybeLabels = labels.value, - maybeComments = comments.map(_.value) - ) - .toString - } + case ListNodeCreatePayloadADM.ListRootNodeCreatePayloadADM( + _, + projectIri, + name, + labels, + comments + ) => + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .createNewListNode( + dataNamedGraph = dataNamedGraph, + listClassIri = OntologyConstants.KnoraBase.ListNode, + projectIri = projectIri.value, + nodeIri = newListNodeIri, + parentNodeIri = None, + rootNodeIri = rootNodeIri, + position = None, + maybeName = name.map(_.value), + maybeLabels = labels.value, + maybeComments = Some(comments.value) + ) + .toString + case ListNodeCreatePayloadADM.ListChildNodeCreatePayloadADM( + _, + parentNodeIri, + projectIri, + name, + position, + labels, + comments + ) => + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .createNewListNode( + dataNamedGraph = dataNamedGraph, + listClassIri = OntologyConstants.KnoraBase.ListNode, + projectIri = projectIri.value, + nodeIri = newListNodeIri, + parentNodeIri = Some(parentNodeIri.value), + rootNodeIri = rootNodeIri, + position = newPosition, + maybeName = name.map(_.value), + maybeLabels = labels.value, + maybeComments = comments.map(_.value) + ) + .toString + } _ <- (storeManager ? SparqlUpdateRequest(createNewListSparqlString)).mapTo[SparqlUpdateResponse] } yield newListNodeIri @@ -1053,14 +1073,16 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde // Verify that the list was created. maybeNewListADM <- listGetADM( - rootNodeIri = listRootIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + 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.") - ) + throw UpdateNotPerformedException( + s"List $listRootIri was not created. Please report this as a possible bug." + ) + ) // _ = log.debug(s"listCreateRequestADM - newListADM: $newListADM") @@ -1069,10 +1091,10 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde for { // run list creation with an global IRI lock taskResult <- IriLocker.runWithIriLock( - apiRequestID, - LISTS_GLOBAL_LOCK_IRI, - () => listCreateTask(createRootRequest, featureFactoryConfig, apiRequestID) - ) + apiRequestID, + LISTS_GLOBAL_LOCK_IRI, + () => listCreateTask(createRootRequest, featureFactoryConfig, apiRequestID) + ) } yield taskResult } @@ -1108,39 +1130,41 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde // _ <- Future(println("77777", nodeIri, changeNodeRequest.listIri)) // check if nodeIRI in path and payload match _ <- Future( - if (!nodeIri.equals(changeNodeRequest.listIri.value)) - throw BadRequestException("IRI in path and payload don't match.") - ) + if (!nodeIri.equals(changeNodeRequest.listIri.value)) + throw BadRequestException("IRI in path and payload don't match.") + ) changeNodeInfoSparqlString <- getUpdateNodeInfoSparqlStatement(changeNodeRequest, featureFactoryConfig) changeResourceResponse <- (storeManager ? SparqlUpdateRequest(changeNodeInfoSparqlString)) - .mapTo[SparqlUpdateResponse] + .mapTo[SparqlUpdateResponse] /* Verify that the node info was updated */ maybeNodeADM <- listNodeInfoGetADM( - nodeIri = nodeIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + nodeIri = nodeIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) response = maybeNodeADM match { - case Some(rootNode: ListRootNodeInfoADM) => RootNodeInfoGetResponseADM(listinfo = rootNode) + case Some(rootNode: ListRootNodeInfoADM) => RootNodeInfoGetResponseADM(listinfo = rootNode) - case Some(childNode: ListChildNodeInfoADM) => ChildNodeInfoGetResponseADM(nodeinfo = childNode) + case Some(childNode: ListChildNodeInfoADM) => ChildNodeInfoGetResponseADM(nodeinfo = childNode) - case _ => - throw UpdateNotPerformedException(s"Node $nodeIri was not updated. Please report this as a possible bug.") - } + case _ => + throw UpdateNotPerformedException( + s"Node $nodeIri was not updated. Please report this as a possible bug." + ) + } } yield response for { // run list info update with an local IRI lock taskResult <- IriLocker.runWithIriLock( - apiRequestID, - nodeIri, - () => nodeInfoChangeTask(nodeIri, changeNodeRequest, featureFactoryConfig, apiRequestID) - ) + apiRequestID, + nodeIri, + () => nodeInfoChangeTask(nodeIri, changeNodeRequest, featureFactoryConfig, apiRequestID) + ) } yield taskResult } @@ -1170,31 +1194,31 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde newListNodeIri <- createNode(createChildNodeRequest, featureFactoryConfig) // Verify that the list node was created. maybeNewListNode <- listNodeInfoGetADM( - nodeIri = newListNodeIri, - featureFactoryConfig = featureFactoryConfig, - KnoraSystemInstances.Users.SystemUser - ) + nodeIri = newListNodeIri, + featureFactoryConfig = featureFactoryConfig, + KnoraSystemInstances.Users.SystemUser + ) newListNode = maybeNewListNode match { - case Some(childNode: ListChildNodeInfoADM) => childNode - case Some(_: ListRootNodeInfoADM) => - throw UpdateNotPerformedException( - s"Child node ${createChildNodeRequest.name} could not be created. Probably parent node Iri is missing in payload." - ) - case _ => - throw UpdateNotPerformedException( - s"List node $newListNodeIri was not created. Please report this as a possible bug." - ) - } + case Some(childNode: ListChildNodeInfoADM) => childNode + case Some(_: ListRootNodeInfoADM) => + throw UpdateNotPerformedException( + s"Child node ${createChildNodeRequest.name} could not be created. Probably parent node Iri is missing in payload." + ) + case _ => + throw UpdateNotPerformedException( + s"List node $newListNodeIri was not created. Please report this as a possible bug." + ) + } } yield ChildNodeInfoGetResponseADM(nodeinfo = newListNode) for { // run list node creation with an global IRI lock taskResult <- IriLocker.runWithIriLock( - apiRequestID, - LISTS_GLOBAL_LOCK_IRI, - () => listChildNodeCreateTask(createChildNodeRequest, featureFactoryConfig, apiRequestID) - ) + apiRequestID, + LISTS_GLOBAL_LOCK_IRI, + () => listChildNodeCreateTask(createChildNodeRequest, featureFactoryConfig, apiRequestID) + ) } yield taskResult } @@ -1232,44 +1256,47 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde projectIri <- getProjectIriFromNode(nodeIri, featureFactoryConfig) // check if the requesting user is allowed to perform operation _ = if (!requestingUser.permissions.isProjectAdmin(projectIri) && !requestingUser.permissions.isSystemAdmin) { - // not project or a system admin - throw ForbiddenException(LIST_CHANGE_PERMISSION_ERROR) - } + // not project or a system admin + throw ForbiddenException(LIST_CHANGE_PERMISSION_ERROR) + } changeNodeNameSparqlString <- getUpdateNodeInfoSparqlStatement( - changeNodeInfoRequest = ListNodeChangePayloadADM( - listIri = ListIRI.make(nodeIri).fold(e => throw e.head, v => v), - projectIri = ProjectIRI.make(projectIri).fold(e => throw e.head, v => v), - name = Some(changeNodeNameRequest.name) - ), - featureFactoryConfig = featureFactoryConfig - ) + changeNodeInfoRequest = ListNodeChangePayloadADM( + listIri = ListIRI.make(nodeIri).fold(e => throw e.head, v => v), + projectIri = ProjectIRI.make(projectIri).fold(e => throw e.head, v => v), + name = Some(changeNodeNameRequest.name) + ), + featureFactoryConfig = featureFactoryConfig + ) changeResourceResponse <- (storeManager ? SparqlUpdateRequest(changeNodeNameSparqlString)) - .mapTo[SparqlUpdateResponse] + .mapTo[SparqlUpdateResponse] /* Verify that the node info was updated */ maybeNodeADM <- listNodeInfoGetADM( - nodeIri = nodeIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + nodeIri = nodeIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) response = maybeNodeADM match { - case Some(rootNode: ListRootNodeInfoADM) => RootNodeInfoGetResponseADM(listinfo = rootNode) - case Some(childNode: ListChildNodeInfoADM) => ChildNodeInfoGetResponseADM(nodeinfo = childNode) - case _ => - throw UpdateNotPerformedException(s"Node $nodeIri was not updated. Please report this as a possible bug.") - } + case Some(rootNode: ListRootNodeInfoADM) => RootNodeInfoGetResponseADM(listinfo = rootNode) + case Some(childNode: ListChildNodeInfoADM) => ChildNodeInfoGetResponseADM(nodeinfo = childNode) + case _ => + throw UpdateNotPerformedException( + s"Node $nodeIri was not updated. Please report this as a possible bug." + ) + } } yield response for { // run list info update with an local IRI lock - taskResult <- IriLocker.runWithIriLock( - apiRequestID, - nodeIri, - () => nodeNameChangeTask(nodeIri, changeNodeNameRequest, featureFactoryConfig, requestingUser, apiRequestID) - ) + taskResult <- + IriLocker.runWithIriLock( + apiRequestID, + nodeIri, + () => nodeNameChangeTask(nodeIri, changeNodeNameRequest, featureFactoryConfig, requestingUser, apiRequestID) + ) } yield taskResult } @@ -1308,42 +1335,46 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde // check if the requesting user is allowed to perform operation _ = if (!requestingUser.permissions.isProjectAdmin(projectIri) && !requestingUser.permissions.isSystemAdmin) { - // not project or a system admin - throw ForbiddenException(LIST_CHANGE_PERMISSION_ERROR) - } + // not project or a system admin + throw ForbiddenException(LIST_CHANGE_PERMISSION_ERROR) + } changeNodeLabelsSparqlString <- getUpdateNodeInfoSparqlStatement( - changeNodeInfoRequest = ListNodeChangePayloadADM( - listIri = ListIRI.make(nodeIri).fold(e => throw e.head, v => v), - projectIri = ProjectIRI.make(projectIri).fold(e => throw e.head, v => v), - labels = Some(changeNodeLabelsRequest.labels) - ), - featureFactoryConfig = featureFactoryConfig - ) + changeNodeInfoRequest = ListNodeChangePayloadADM( + listIri = ListIRI.make(nodeIri).fold(e => throw e.head, v => v), + projectIri = ProjectIRI.make(projectIri).fold(e => throw e.head, v => v), + labels = Some(changeNodeLabelsRequest.labels) + ), + featureFactoryConfig = featureFactoryConfig + ) changeResourceResponse <- (storeManager ? SparqlUpdateRequest(changeNodeLabelsSparqlString)) - .mapTo[SparqlUpdateResponse] + .mapTo[SparqlUpdateResponse] /* Verify that the node info was updated */ maybeNodeADM <- listNodeInfoGetADM( - nodeIri = nodeIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + nodeIri = nodeIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) response = maybeNodeADM match { - case Some(rootNode: ListRootNodeInfoADM) => RootNodeInfoGetResponseADM(listinfo = rootNode) - case Some(childNode: ListChildNodeInfoADM) => ChildNodeInfoGetResponseADM(nodeinfo = childNode) - case _ => - throw UpdateNotPerformedException(s"Node $nodeIri was not updated. Please report this as a possible bug.") - } + case Some(rootNode: ListRootNodeInfoADM) => RootNodeInfoGetResponseADM(listinfo = rootNode) + case Some(childNode: ListChildNodeInfoADM) => ChildNodeInfoGetResponseADM(nodeinfo = childNode) + case _ => + throw UpdateNotPerformedException( + s"Node $nodeIri was not updated. Please report this as a possible bug." + ) + } } yield response for { // run list info update with an local IRI lock - taskResult <- IriLocker.runWithIriLock( - apiRequestID, - nodeIri, - () => nodeLabelsChangeTask(nodeIri, changeNodeLabelsRequest, featureFactoryConfig, requestingUser, apiRequestID) - ) + taskResult <- + IriLocker.runWithIriLock( + apiRequestID, + nodeIri, + () => + nodeLabelsChangeTask(nodeIri, changeNodeLabelsRequest, featureFactoryConfig, requestingUser, apiRequestID) + ) } yield taskResult } @@ -1382,43 +1413,51 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde // check if the requesting user is allowed to perform operation _ = if (!requestingUser.permissions.isProjectAdmin(projectIri) && !requestingUser.permissions.isSystemAdmin) { - // not project or a system admin - throw ForbiddenException(LIST_CHANGE_PERMISSION_ERROR) - } + // not project or a system admin + throw ForbiddenException(LIST_CHANGE_PERMISSION_ERROR) + } changeNodeCommentsSparqlString <- getUpdateNodeInfoSparqlStatement( - changeNodeInfoRequest = ListNodeChangePayloadADM( - listIri = ListIRI.make(nodeIri).fold(e => throw e.head, v => v), - projectIri = ProjectIRI.make(projectIri).fold(e => throw e.head, v => v), - comments = Some(changeNodeCommentsRequest.comments) - ), - featureFactoryConfig = featureFactoryConfig - ) + changeNodeInfoRequest = ListNodeChangePayloadADM( + listIri = ListIRI.make(nodeIri).fold(e => throw e.head, v => v), + projectIri = ProjectIRI.make(projectIri).fold(e => throw e.head, v => v), + comments = Some(changeNodeCommentsRequest.comments) + ), + featureFactoryConfig = featureFactoryConfig + ) _ <- (storeManager ? SparqlUpdateRequest(changeNodeCommentsSparqlString)).mapTo[SparqlUpdateResponse] /* Verify that the node info was updated */ maybeNodeADM <- listNodeInfoGetADM( - nodeIri = nodeIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + nodeIri = nodeIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) response = maybeNodeADM match { - case Some(rootNode: ListRootNodeInfoADM) => RootNodeInfoGetResponseADM(listinfo = rootNode) - case Some(childNode: ListChildNodeInfoADM) => ChildNodeInfoGetResponseADM(nodeinfo = childNode) - case _ => - throw UpdateNotPerformedException(s"Node $nodeIri was not updated. Please report this as a possible bug.") - } + case Some(rootNode: ListRootNodeInfoADM) => RootNodeInfoGetResponseADM(listinfo = rootNode) + case Some(childNode: ListChildNodeInfoADM) => ChildNodeInfoGetResponseADM(nodeinfo = childNode) + case _ => + throw UpdateNotPerformedException( + s"Node $nodeIri was not updated. Please report this as a possible bug." + ) + } } yield response for { // run list info update with an local IRI lock taskResult <- IriLocker.runWithIriLock( - apiRequestID, - nodeIri, - () => - nodeCommentsChangeTask(nodeIri, changeNodeCommentsRequest, featureFactoryConfig, requestingUser, apiRequestID) - ) + apiRequestID, + nodeIri, + () => + nodeCommentsChangeTask( + nodeIri, + changeNodeCommentsRequest, + featureFactoryConfig, + requestingUser, + apiRequestID + ) + ) } yield taskResult } @@ -1486,37 +1525,36 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde def verifyParentChildrenUpdate(newPosition: Int): Future[ListNodeADM] = for { maybeParentNode <- listNodeGetADM( - nodeIri = changeNodePositionRequest.parentIri, - shallow = false, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) - updatedParent = maybeParentNode.get + nodeIri = changeNodePositionRequest.parentIri, + shallow = false, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) + updatedParent = maybeParentNode.get updatedChildren: Seq[ListChildNodeADM] = updatedParent.getChildren - (siblingsPositionedBefore: Seq[ListChildNodeADM], rest: Seq[ListChildNodeADM]) = updatedChildren.partition( - node => node.position < newPosition - ) + (siblingsPositionedBefore: Seq[ListChildNodeADM], rest: Seq[ListChildNodeADM]) = + updatedChildren.partition(node => node.position < newPosition) // verify that node is among children of specified parent in correct position updatedNode = rest.head _ = if (updatedNode.id != nodeIri || updatedNode.position != newPosition) { - throw UpdateNotPerformedException( - s"Node is not repositioned correctly in specified parent node. Please report this as a bug." - ) - } + throw UpdateNotPerformedException( + s"Node is not repositioned correctly in specified parent node. Please report this as a bug." + ) + } leftPositions: Seq[Int] = siblingsPositionedBefore.map(child => child.position) _ = if (leftPositions != leftPositions.sorted) { - throw UpdateNotPerformedException( - s"Something has gone wrong with shifting nodes. Please report this as a bug." - ) - } + throw UpdateNotPerformedException( + s"Something has gone wrong with shifting nodes. Please report this as a bug." + ) + } siblingsPositionedAfter = rest.slice(1, rest.length) rightSiblings: Seq[Int] = siblingsPositionedAfter.map(child => child.position) _ = if (rightSiblings != rightSiblings.sorted) { - throw UpdateNotPerformedException( - s"Something has gone wrong with shifting nodes. Please report this as a bug." - ) - } + throw UpdateNotPerformedException( + s"Something has gone wrong with shifting nodes. Please report this as a bug." + ) + } } yield updatedParent @@ -1539,17 +1577,18 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde for { // get parent node with its immediate children maybeParentNode <- listNodeGetADM( - nodeIri = parentIri, - shallow = true, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) - parentNode = maybeParentNode.getOrElse( - throw BadRequestException(s"The parent node ${parentIri} could node be found, report this as a bug.") - ) - _ = isNewPositionValid(parentNode, false) + nodeIri = parentIri, + shallow = true, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) + parentNode = + maybeParentNode.getOrElse( + throw BadRequestException(s"The parent node ${parentIri} could node be found, report this as a bug.") + ) + _ = isNewPositionValid(parentNode, false) parentChildren = parentNode.getChildren - currPosition = node.position + currPosition = node.position // if givenPosition is -1, append the child to the end of the list of children newPosition = @@ -1559,11 +1598,11 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde // update the position of the node itself _ <- updatePositionOfNode( - nodeIri = node.id, - newPosition = newPosition, - dataNamedGraph = dataNamedGraph, - featureFactoryConfig = featureFactoryConfig - ) + nodeIri = node.id, + newPosition = newPosition, + dataNamedGraph = dataNamedGraph, + featureFactoryConfig = featureFactoryConfig + ) // update position of siblings _ <- @@ -1571,25 +1610,25 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde for { // shift siblings to left updatedSiblings <- shiftNodes( - startPos = currPosition + 1, - endPos = newPosition, - nodes = parentChildren, - shiftToLeft = true, - dataNamedGraph = dataNamedGraph, - featureFactoryConfig = featureFactoryConfig - ) + startPos = currPosition + 1, + endPos = newPosition, + nodes = parentChildren, + shiftToLeft = true, + dataNamedGraph = dataNamedGraph, + featureFactoryConfig = featureFactoryConfig + ) } yield updatedSiblings } else if (currPosition > newPosition) { for { // shift siblings to right updatedSiblings <- shiftNodes( - startPos = newPosition, - endPos = currPosition - 1, - nodes = parentChildren, - shiftToLeft = false, - dataNamedGraph = dataNamedGraph, - featureFactoryConfig = featureFactoryConfig - ) + startPos = newPosition, + endPos = currPosition - 1, + nodes = parentChildren, + shiftToLeft = false, + dataNamedGraph = dataNamedGraph, + featureFactoryConfig = featureFactoryConfig + ) } yield updatedSiblings } else { throw UpdateNotPerformedException(s"The given position is the same as node's current position.") @@ -1618,21 +1657,21 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde for { // get current parent node with its immediate children maybeCurrentParentNode <- listNodeGetADM( - nodeIri = currParentIri, - shallow = true, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + nodeIri = currParentIri, + shallow = true, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) currentSiblings = maybeCurrentParentNode.get.getChildren // get new parent node with its immediate children maybeNewParentNode <- listNodeGetADM( - nodeIri = newParentIri, - shallow = true, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) - newParent = maybeNewParentNode.get - _ = isNewPositionValid(newParent, true) + nodeIri = newParentIri, + shallow = true, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) + newParent = maybeNewParentNode.get + _ = isNewPositionValid(newParent, true) newSiblings = newParent.getChildren currentNodePosition = node.position @@ -1645,21 +1684,21 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde // update the position of the node itself _ <- updatePositionOfNode( - nodeIri = node.id, - newPosition = newPosition, - dataNamedGraph = dataNamedGraph, - featureFactoryConfig = featureFactoryConfig - ) + nodeIri = node.id, + newPosition = newPosition, + dataNamedGraph = dataNamedGraph, + featureFactoryConfig = featureFactoryConfig + ) // shift current siblings with a higher position to left as if the node is deleted _ <- shiftNodes( - startPos = currentNodePosition + 1, - endPos = currentSiblings.last.position, - nodes = currentSiblings, - shiftToLeft = true, - dataNamedGraph = dataNamedGraph, - featureFactoryConfig = featureFactoryConfig - ) + startPos = currentNodePosition + 1, + endPos = currentSiblings.last.position, + nodes = currentSiblings, + shiftToLeft = true, + dataNamedGraph = dataNamedGraph, + featureFactoryConfig = featureFactoryConfig + ) // Is node supposed to be added to the end of new parent's children list? _ <- @@ -1671,24 +1710,24 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde // to right, as if the node is inserted in the given position for { updatedSiblings <- shiftNodes( - startPos = newPosition, - endPos = newSiblings.last.position, - nodes = newSiblings, - shiftToLeft = false, - dataNamedGraph = dataNamedGraph, - featureFactoryConfig = featureFactoryConfig - ) + startPos = newPosition, + endPos = newSiblings.last.position, + nodes = newSiblings, + shiftToLeft = false, + dataNamedGraph = dataNamedGraph, + featureFactoryConfig = featureFactoryConfig + ) } yield updatedSiblings } /* update the sublists of parent nodes */ _ <- changeParentNode( - nodeIri = node.id, - oldParentIri = currParentIri, - newParentIri = newParentIri, - dataNamedGraph = dataNamedGraph, - featureFactoryConfig = featureFactoryConfig - ) + nodeIri = node.id, + oldParentIri = currParentIri, + newParentIri = newParentIri, + dataNamedGraph = dataNamedGraph, + featureFactoryConfig = featureFactoryConfig + ) } yield newPosition @@ -1710,22 +1749,22 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde // check if the requesting user is allowed to perform operation _ = if (!requestingUser.permissions.isProjectAdmin(projectIri) && !requestingUser.permissions.isSystemAdmin) { - // not project or a system admin - throw ForbiddenException(LIST_CHANGE_PERMISSION_ERROR) - } + // not project or a system admin + throw ForbiddenException(LIST_CHANGE_PERMISSION_ERROR) + } // get node in its current position maybeNode <- listNodeGetADM( - nodeIri = nodeIri, - shallow = true, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + nodeIri = nodeIri, + shallow = true, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) node = maybeNode match { - case Some(node: ListChildNodeADM) => node - case _ => - throw BadRequestException(s"Update of position is only allowed for child nodes!") - } + case Some(node: ListChildNodeADM) => node + case _ => + throw BadRequestException(s"Update of position is only allowed for child nodes!") + } // get node's current parent currentParentNodeIri: IRI <- getParentNodeIRI(nodeIri, featureFactoryConfig) @@ -1753,11 +1792,17 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde for { // run list info update with an local IRI lock taskResult <- IriLocker.runWithIriLock( - apiRequestID, - nodeIri, - () => - nodePositionChangeTask(nodeIri, changeNodePositionRequest, featureFactoryConfig, requestingUser, apiRequestID) - ) + apiRequestID, + nodeIri, + () => + nodePositionChangeTask( + nodeIri, + changeNodePositionRequest, + featureFactoryConfig, + requestingUser, + apiRequestID + ) + ) } yield taskResult } @@ -1769,15 +1814,15 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde ): Future[CanDeleteListResponseADM] = for { sparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .canDeleteList( - listIri = iri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .canDeleteList( + listIri = iri + ) + .toString() + ) response: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(sparqlQuery)) - .mapTo[SparqlSelectResult] + .mapTo[SparqlSelectResult] canDelete = if (response.results.bindings.isEmpty) true @@ -1815,17 +1860,18 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde for { // Is node itself in use? _ <- isNodeUsed( - nodeIri = nodeIri, - errorFun = throw BadRequestException(s"Node $nodeIri cannot be deleted, because it is in use.") - ) + nodeIri = nodeIri, + errorFun = throw BadRequestException(s"Node $nodeIri cannot be deleted, because it is in use.") + ) errorCheckFutures: Seq[Future[Unit]] = nodeChildren.map { child => - isNodeUsed( - nodeIri = child.id, - errorFun = - throw BadRequestException(s"Node $nodeIri cannot be deleted, because its child ${child.id} is in use.") - ) - } + isNodeUsed( + nodeIri = child.id, + errorFun = throw BadRequestException( + s"Node $nodeIri cannot be deleted, because its child ${child.id} is in use." + ) + ) + } _ <- Future.sequence(errorCheckFutures) @@ -1853,9 +1899,8 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde dataNamedGraph <- getDataNamedGraph(projectIri, featureFactoryConfig) // delete the children - errorCheckFutures: Seq[Future[Unit]] = children.map(child => - deleteNode(dataNamedGraph, child.id, isRootNode = false) - ) + errorCheckFutures: Seq[Future[Unit]] = + children.map(child => deleteNode(dataNamedGraph, child.id, isRootNode = false)) _ <- Future.sequence(errorCheckFutures) // delete the node itself @@ -1884,34 +1929,35 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde ): Future[ListNodeADM] = for { maybeNode <- listNodeGetADM( - nodeIri = parentNodeIri, - shallow = false, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) - - parentNode: ListNodeADM = maybeNode.getOrElse( - throw BadRequestException(s"The parent node of $deletedNodeIri not found, report this as a bug.") - ) + nodeIri = parentNodeIri, + shallow = false, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) + + parentNode: ListNodeADM = + maybeNode.getOrElse( + throw BadRequestException(s"The parent node of $deletedNodeIri not found, report this as a bug.") + ) remainingChildren = parentNode.getChildren _ = if (remainingChildren.exists(child => child.id == deletedNodeIri)) { - throw UpdateNotPerformedException(s"Node $deletedNodeIri is not deleted properly, report this as a bug.") - } + throw UpdateNotPerformedException(s"Node $deletedNodeIri is not deleted properly, report this as a bug.") + } // shift the siblings that were positioned after the deleted node, one place to left. updatedChildren <- if (remainingChildren.size > 0) { for { shiftedChildren <- shiftNodes( - startPos = positionOfDeletedNode + 1, - endPos = remainingChildren.last.position, - nodes = remainingChildren, - shiftToLeft = true, - dataNamedGraph = dataNamedGraph, - featureFactoryConfig = featureFactoryConfig - ) + startPos = positionOfDeletedNode + 1, + endPos = remainingChildren.last.position, + nodes = remainingChildren, + shiftToLeft = true, + dataNamedGraph = dataNamedGraph, + featureFactoryConfig = featureFactoryConfig + ) } yield shiftedChildren } else { Future.successful(remainingChildren) @@ -1919,27 +1965,27 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde // return updated parent node with shifted children. updatedParentNode = parentNode match { - case rootNode: ListRootNodeADM => - ListRootNodeADM( - id = rootNode.id, - projectIri = rootNode.projectIri, - name = rootNode.name, - labels = rootNode.labels, - comments = rootNode.comments, - children = updatedChildren - ) - - case childNode: ListChildNodeADM => - ListChildNodeADM( - id = childNode.id, - name = childNode.name, - labels = childNode.labels, - comments = childNode.comments, - position = childNode.position, - hasRootNode = childNode.hasRootNode, - children = updatedChildren - ) - } + case rootNode: ListRootNodeADM => + ListRootNodeADM( + id = rootNode.id, + projectIri = rootNode.projectIri, + name = rootNode.name, + labels = rootNode.labels, + comments = rootNode.comments, + children = updatedChildren + ) + + case childNode: ListChildNodeADM => + ListChildNodeADM( + id = childNode.id, + name = childNode.name, + labels = childNode.labels, + comments = childNode.comments, + position = childNode.position, + hasRootNode = childNode.hasRootNode, + children = updatedChildren + ) + } } yield updatedParentNode /** @@ -1956,67 +2002,70 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde // check if the requesting user is allowed to perform operation _ = if (!requestingUser.permissions.isProjectAdmin(projectIri) && !requestingUser.permissions.isSystemAdmin) { - // not project or a system admin - throw ForbiddenException(LIST_CHANGE_PERMISSION_ERROR) - } + // not project or a system admin + throw ForbiddenException(LIST_CHANGE_PERMISSION_ERROR) + } maybeNode: Option[ListNodeADM] <- listNodeGetADM( - nodeIri = nodeIri, - shallow = false, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + nodeIri = nodeIri, + shallow = false, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) response: ListItemDeleteResponseADM <- maybeNode match { - case Some(rootNode: ListRootNodeADM) => - for { - _ <- isNodeOrItsChildrenUsed(rootNode.id, rootNode.children) - - _ <- deleteListItem( - nodeIri = rootNode.id, - projectIri = projectIri, - children = rootNode.children, - isRootNode = true - ) - } yield ListDeleteResponseADM(rootNode.id, deleted = true) - - case Some(childNode: ListChildNodeADM) => - for { - _ <- isNodeOrItsChildrenUsed(childNode.id, childNode.children) - - // get parent node IRI before deleting the node - parentNodeIri <- getParentNodeIRI(nodeIri, featureFactoryConfig) - - // delete the node - dataNamedGraph <- deleteListItem( - nodeIri = childNode.id, - projectIri = projectIri, - children = childNode.children, - isRootNode = false - ) - - // update the parent node - updatedParentNode <- updateParentNode( - deletedNodeIri = nodeIri, - positionOfDeletedNode = childNode.position, - parentNodeIri = parentNodeIri, - dataNamedGraph = dataNamedGraph, - featureFactoryConfig = featureFactoryConfig - ) - - } yield ChildNodeDeleteResponseADM(node = updatedParentNode) - - case _ => throw BadRequestException(s"Node $nodeIri was not found. Please verify the given IRI.") - } + case Some(rootNode: ListRootNodeADM) => + for { + _ <- isNodeOrItsChildrenUsed(rootNode.id, rootNode.children) + + _ <- deleteListItem( + nodeIri = rootNode.id, + projectIri = projectIri, + children = rootNode.children, + isRootNode = true + ) + } yield ListDeleteResponseADM(rootNode.id, deleted = true) + + case Some(childNode: ListChildNodeADM) => + for { + _ <- isNodeOrItsChildrenUsed(childNode.id, childNode.children) + + // get parent node IRI before deleting the node + parentNodeIri <- getParentNodeIRI(nodeIri, featureFactoryConfig) + + // delete the node + dataNamedGraph <- deleteListItem( + nodeIri = childNode.id, + projectIri = projectIri, + children = childNode.children, + isRootNode = false + ) + + // update the parent node + updatedParentNode <- updateParentNode( + deletedNodeIri = nodeIri, + positionOfDeletedNode = childNode.position, + parentNodeIri = parentNodeIri, + dataNamedGraph = dataNamedGraph, + featureFactoryConfig = featureFactoryConfig + ) + + } yield ChildNodeDeleteResponseADM(node = updatedParentNode) + + case _ => + throw BadRequestException( + s"Node $nodeIri was not found. Please verify the given IRI." + ) + } } yield response for { // run list info update with an local IRI lock taskResult <- IriLocker.runWithIriLock( - apiRequestID, - nodeIri, - () => nodeDeleteTask(nodeIri, featureFactoryConfig, requestingUser, apiRequestID) - ) + apiRequestID, + nodeIri, + () => nodeDeleteTask(nodeIri, featureFactoryConfig, requestingUser, apiRequestID) + ) } yield taskResult } @@ -2032,13 +2081,14 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde */ private def projectByIriExists(projectIri: IRI): Future[Boolean] = for { - askString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt.checkProjectExistsByIri(projectIri).toString - ) + askString <- + Future( + org.knora.webapi.messages.twirl.queries.sparql.admin.txt.checkProjectExistsByIri(projectIri).toString + ) //_ = log.debug("projectByIriExists - query: {}", askString) askResponse <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] - result = askResponse.result + result = askResponse.result } yield result @@ -2050,13 +2100,14 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde */ private def rootNodeByIriExists(rootNodeIri: IRI): Future[Boolean] = for { - askString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt.checkListRootNodeExistsByIri(rootNodeIri).toString - ) + askString <- + Future( + org.knora.webapi.messages.twirl.queries.sparql.admin.txt.checkListRootNodeExistsByIri(rootNodeIri).toString + ) // _ = log.debug("rootNodeByIriExists - query: {}", askString) askResponse <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] - result = askResponse.result + result = askResponse.result } yield result @@ -2069,12 +2120,12 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde private def nodeByIriExists(nodeIri: IRI): Future[Boolean] = for { askString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt.checkListNodeExistsByIri(nodeIri).toString - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt.checkListNodeExistsByIri(nodeIri).toString + ) // _ = log.debug("rootNodeByIriExists - query: {}", askString) askResponse <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] - result = askResponse.result + result = askResponse.result } yield result @@ -2091,17 +2142,17 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde case Some(name) => for { askString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .checkListNodeNameIsProjectUnique( - projectIri, - listNodeName = name.value - ) - .toString - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .checkListNodeNameIsProjectUnique( + projectIri, + listNodeName = name.value + ) + .toString + ) //_ = log.debug("listNodeNameIsProjectUnique - query: {}", askString) askResponse <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] - result = askResponse.result + result = askResponse.result } yield !result @@ -2125,49 +2176,49 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde /* verify that the list name is unique for the project */ nodeNameUnique: Boolean <- listNodeNameIsProjectUnique( - changeNodeInfoRequest.projectIri.value, - changeNodeInfoRequest.name - ) + changeNodeInfoRequest.projectIri.value, + changeNodeInfoRequest.name + ) _ = if (!nodeNameUnique) { - throw DuplicateValueException( - s"The name ${changeNodeInfoRequest.name.get} is already used by a list inside the project ${changeNodeInfoRequest.projectIri.value}." - ) - } + throw DuplicateValueException( + s"The name ${changeNodeInfoRequest.name.get} is already used by a list inside the project ${changeNodeInfoRequest.projectIri.value}." + ) + } /* Verify that the node with Iri exists. */ maybeNode <- listNodeGetADM( - nodeIri = changeNodeInfoRequest.listIri.value, - shallow = true, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + nodeIri = changeNodeInfoRequest.listIri.value, + shallow = true, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) node = maybeNode.getOrElse( - throw BadRequestException(s"List item with '${changeNodeInfoRequest.listIri}' not found.") - ) + throw BadRequestException(s"List item with '${changeNodeInfoRequest.listIri}' not found.") + ) isRootNode = maybeNode match { - case Some(_: ListRootNodeADM) => true - case Some(_: ListChildNodeADM) => false - case _ => false - } + case Some(_: ListRootNodeADM) => true + case Some(_: ListChildNodeADM) => false + case _ => false + } hasOldName: Boolean = node.getName.nonEmpty // Update the list changeNodeInfoSparqlString: String = org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .updateListInfo( - dataNamedGraph = dataNamedGraph, - nodeIri = changeNodeInfoRequest.listIri.value, - hasOldName = hasOldName, - isRootNode = isRootNode, - maybeName = changeNodeInfoRequest.name.map(_.value), - projectIri = changeNodeInfoRequest.projectIri.value, - listClassIri = OntologyConstants.KnoraBase.ListNode, - maybeLabels = changeNodeInfoRequest.labels.map(_.value), - maybeComments = changeNodeInfoRequest.comments.map(_.value) - ) - .toString + .updateListInfo( + dataNamedGraph = dataNamedGraph, + nodeIri = changeNodeInfoRequest.listIri.value, + hasOldName = hasOldName, + isRootNode = isRootNode, + maybeName = changeNodeInfoRequest.name.map(_.value), + projectIri = changeNodeInfoRequest.projectIri.value, + listClassIri = OntologyConstants.KnoraBase.ListNode, + maybeLabels = changeNodeInfoRequest.labels.map(_.value), + maybeComments = changeNodeInfoRequest.comments.map(_.value) + ) + .toString } yield changeNodeInfoSparqlString /** @@ -2180,31 +2231,34 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde private def getProjectIriFromNode(nodeIri: IRI, featureFactoryConfig: FeatureFactoryConfig): Future[IRI] = for { maybeNode <- listNodeGetADM( - nodeIri = nodeIri, - shallow = true, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + nodeIri = nodeIri, + shallow = true, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) projectIri <- maybeNode match { - case Some(rootNode: ListRootNodeADM) => Future(rootNode.projectIri) - - case Some(childNode: ListChildNodeADM) => - for { - maybeRoot <- listNodeGetADM( - nodeIri = childNode.hasRootNode, - shallow = true, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) - rootProjectIri = maybeRoot match { - case Some(rootNode: ListRootNodeADM) => rootNode.projectIri - case _ => throw BadRequestException(s"Root node of $nodeIri was not found. Please verify the given IRI.") - } - } yield rootProjectIri - - case _ => throw BadRequestException(s"Node $nodeIri was not found. Please verify the given IRI.") - } + case Some(rootNode: ListRootNodeADM) => Future(rootNode.projectIri) + + case Some(childNode: ListChildNodeADM) => + for { + maybeRoot <- listNodeGetADM( + nodeIri = childNode.hasRootNode, + shallow = true, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) + rootProjectIri = maybeRoot match { + case Some(rootNode: ListRootNodeADM) => rootNode.projectIri + case _ => + throw BadRequestException( + s"Root node of $nodeIri was not found. Please verify the given IRI." + ) + } + } yield rootProjectIri + + case _ => throw BadRequestException(s"Node $nodeIri was not found. Please verify the given IRI.") + } } yield projectIri /** @@ -2217,19 +2271,19 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde protected def isNodeUsed(nodeIri: IRI, errorFun: => Nothing): Future[Unit] = for { isNodeUsedSparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .isNodeUsed( - nodeIri = nodeIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .isNodeUsed( + nodeIri = nodeIri + ) + .toString() + ) isNodeUsedResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(isNodeUsedSparql)) - .mapTo[SparqlSelectResult] + .mapTo[SparqlSelectResult] _ = if (isNodeUsedResponse.results.bindings.nonEmpty) { - errorFun - } + errorFun + } } yield () /** @@ -2243,17 +2297,17 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde for { /* Get the project information */ maybeProject <- (responderManager ? ProjectGetADM( - ProjectIdentifierADM( - maybeIri = Some(projectIri) - ), - featureFactoryConfig = featureFactoryConfig, - KnoraSystemInstances.Users.SystemUser - )).mapTo[Option[ProjectADM]] + ProjectIdentifierADM( + maybeIri = Some(projectIri) + ), + featureFactoryConfig = featureFactoryConfig, + KnoraSystemInstances.Users.SystemUser + )).mapTo[Option[ProjectADM]] project: ProjectADM = maybeProject match { - case Some(project: ProjectADM) => project - case None => throw BadRequestException(s"Project '$projectIri' not found.") - } + case Some(project: ProjectADM) => project + case None => throw BadRequestException(s"Project '$projectIri' not found.") + } // Get the IRI of the named graph from which the resource will be erased. dataNamedGraph: IRI = stringFormatter.projectDataNamedGraphV2(project) @@ -2270,21 +2324,21 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde for { // query statement getParentNodeSparqlString: String <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .getParentNode( - nodeIri = nodeIri - ) - .toString - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .getParentNode( + nodeIri = nodeIri + ) + .toString + ) parentNodeResponse <- (storeManager ? SparqlExtendedConstructRequest( - sparql = getParentNodeSparqlString, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + sparql = getParentNodeSparqlString, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse] parentStatements = parentNodeResponse.statements.headOption.getOrElse( - throw BadRequestException(s"The parent node for $nodeIri not found, report this as a bug.") - ) + throw BadRequestException(s"The parent node for $nodeIri not found, report this as a bug.") + ) parentNodeIri = parentStatements._1.toString } yield parentNodeIri @@ -2302,14 +2356,14 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde for { // Generate SPARQL for erasing a node. sparqlDeleteNode: String <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .deleteNode( - dataNamedGraph = dataNamedGraph, - nodeIri = nodeIri, - isRootNode = isRootNode - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .deleteNode( + dataNamedGraph = dataNamedGraph, + nodeIri = nodeIri, + isRootNode = isRootNode + ) + .toString() + ) // Do the update. _ <- (storeManager ? SparqlUpdateRequest(sparqlDeleteNode)).mapTo[SparqlUpdateResponse] @@ -2318,8 +2372,8 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde nodeStillExists: Boolean <- nodeByIriExists(nodeIri) _ = if (nodeStillExists) { - throw UpdateNotPerformedException(s"Node <$nodeIri> was not erased. Please report this as a possible bug.") - } + throw UpdateNotPerformedException(s"Node <$nodeIri> was not erased. Please report this as a possible bug.") + } } yield () /** @@ -2341,34 +2395,35 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde for { // Generate SPARQL for erasing a node. sparqlUpdateNodePosition: String <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .updateNodePosition( - dataNamedGraph = dataNamedGraph, - nodeIri = nodeIri, - newPosition = newPosition - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .updateNodePosition( + dataNamedGraph = dataNamedGraph, + nodeIri = nodeIri, + newPosition = newPosition + ) + .toString() + ) _ <- (storeManager ? SparqlUpdateRequest(sparqlUpdateNodePosition)).mapTo[SparqlUpdateResponse] /* Verify that the node info was updated */ maybeNode <- listNodeGetADM( - nodeIri = nodeIri, - shallow = false, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + nodeIri = nodeIri, + shallow = false, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) - childNode: ListChildNodeADM = maybeNode - .getOrElse(throw BadRequestException(s"Node with $nodeIri could not be found to update its position.")) - .asInstanceOf[ListChildNodeADM] + childNode: ListChildNodeADM = + maybeNode + .getOrElse(throw BadRequestException(s"Node with $nodeIri could not be found to update its position.")) + .asInstanceOf[ListChildNodeADM] _ = if (!childNode.position.equals(newPosition)) { - throw UpdateNotPerformedException( - s"The position of the node $nodeIri could not be updated, report this as a possible bug." - ) - } + throw UpdateNotPerformedException( + s"The position of the node $nodeIri could not be updated, report this as a possible bug." + ) + } } yield childNode @@ -2394,24 +2449,25 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde featureFactoryConfig: FeatureFactoryConfig ): Future[Seq[ListChildNodeADM]] = for { - nodesTobeUpdated: Seq[ListChildNodeADM] <- Future( - nodes.filter(node => node.position >= startPos && node.position <= endPos) - ) + nodesTobeUpdated: Seq[ListChildNodeADM] <- + Future( + nodes.filter(node => node.position >= startPos && node.position <= endPos) + ) staticStartNodes = nodes.filter(node => node.position < startPos) - staticEndNotes = nodes.filter(node => node.position > endPos) + staticEndNotes = nodes.filter(node => node.position > endPos) updatePositionFutures = nodesTobeUpdated.map { child => - val currPos = child.position - val newPos = if (shiftToLeft) { - currPos - 1 - } else currPos + 1 - - updatePositionOfNode( - nodeIri = child.id, - newPosition = newPos, - dataNamedGraph = dataNamedGraph, - featureFactoryConfig = featureFactoryConfig - ) - } + val currPos = child.position + val newPos = if (shiftToLeft) { + currPos - 1 + } else currPos + 1 + + updatePositionOfNode( + nodeIri = child.id, + newPosition = newPos, + dataNamedGraph = dataNamedGraph, + featureFactoryConfig = featureFactoryConfig + ) + } updatedNodes: Seq[ListChildNodeADM] <- Future.sequence(updatePositionFutures) } yield staticStartNodes ++ updatedNodes ++ staticEndNotes @@ -2435,41 +2491,43 @@ class ListsResponderADM(responderData: ResponderData) extends Responder(responde for { // Generate SPARQL for changing the parent node of the node. sparqlChangeParentNode: String <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .changeParentNode( - dataNamedGraph = dataNamedGraph, - nodeIri = nodeIri, - currentParentIri = oldParentIri, - newParentIri = newParentIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .changeParentNode( + dataNamedGraph = dataNamedGraph, + nodeIri = nodeIri, + currentParentIri = oldParentIri, + newParentIri = newParentIri + ) + .toString() + ) _ <- (storeManager ? SparqlUpdateRequest(sparqlChangeParentNode)).mapTo[SparqlUpdateResponse] /* verify that parents were updated */ // get old parent node with its immediate children maybeOldParent <- listNodeGetADM( - nodeIri = oldParentIri, - shallow = true, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + nodeIri = oldParentIri, + shallow = true, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) childrenOfOldParent = maybeOldParent.get.getChildren _ = if (childrenOfOldParent.exists(node => node.id == nodeIri)) { - throw UpdateNotPerformedException(s"Node ${nodeIri} is still a child of ${oldParentIri}. Report this as a bug.") - } + throw UpdateNotPerformedException( + s"Node ${nodeIri} is still a child of ${oldParentIri}. Report this as a bug." + ) + } // get new parent node with its immediate children maybeNewParentNode <- listNodeGetADM( - nodeIri = newParentIri, - shallow = true, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + nodeIri = newParentIri, + shallow = true, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) childrenOfNewParent = maybeNewParentNode.get.getChildren _ = if (!childrenOfNewParent.exists(node => node.id == nodeIri)) { - throw UpdateNotPerformedException(s"Node ${nodeIri} is not added to parent node ${newParentIri}. ") - } + throw UpdateNotPerformedException(s"Node ${nodeIri} is not added to parent node ${newParentIri}. ") + } } yield () } diff --git a/webapi/src/main/scala/org/knora/webapi/responders/admin/PermissionsResponderADM.scala b/webapi/src/main/scala/org/knora/webapi/responders/admin/PermissionsResponderADM.scala index b9e471df4c..42f45aaa7d 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/admin/PermissionsResponderADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/admin/PermissionsResponderADM.scala @@ -219,16 +219,16 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re groupIris.map { groupIri => for { maybeGroup <- (responderManager ? GroupGetADM( - groupIri = groupIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - )).mapTo[Option[GroupADM]] + groupIri = groupIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + )).mapTo[Option[GroupADM]] group = maybeGroup.getOrElse( - throw InconsistentRepositoryDataException( - s"Cannot find information for group: '$groupIri'. Please report as possible bug." - ) - ) + throw InconsistentRepositoryDataException( + s"Cannot find information for group: '$groupIri'. Please report as possible bug." + ) + ) res = (group.project.id, groupIri) } yield res } @@ -247,7 +247,7 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re if (projectIris.nonEmpty) { for { projectIri <- projectIris.toVector - res = (projectIri, OntologyConstants.KnoraAdmin.ProjectMember) + res = (projectIri, OntologyConstants.KnoraAdmin.ProjectMember) } yield res } else { Seq.empty[(IRI, IRI)] @@ -259,7 +259,7 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re if (projectIris.nonEmpty) { for { projectAdminForGroup <- isInProjectAdminGroups - res = (projectAdminForGroup, OntologyConstants.KnoraAdmin.ProjectAdmin) + res = (projectAdminForGroup, OntologyConstants.KnoraAdmin.ProjectAdmin) } yield res } else { Seq.empty[(IRI, IRI)] @@ -278,7 +278,7 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re /* combine explicit groups with materialized implicit groups */ /* here we don't add the KnownUser group, as this would inflate the whole thing. */ /* we instead inject the relevant information in defaultObjectAccessPermissionsStringForEntityGetV1 */ - allGroups = groups ++ projectMembers ++ projectAdmins ++ systemAdmin + allGroups = groups ++ projectMembers ++ projectAdmins ++ systemAdmin groupsPerProject = allGroups.groupBy(_._1).map { case (k, v) => (k, v.map(_._2)) } // _ = log.debug(s"permissionsProfileGetV1 - groupsPerProject: {}", MessageUtil.toSource(groupsPerProject)) @@ -293,9 +293,9 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re /* construct the permission profile from the different parts */ result = PermissionsDataADM( - groupsPerProject = groupsPerProject, - administrativePermissionsPerProject = administrativePermissionsPerProject - ) + groupsPerProject = groupsPerProject, + administrativePermissionsPerProject = administrativePermissionsPerProject + ) //_ = log.debug(s"permissionsDataGetV1 - resulting permissionData: {}", result) } yield result @@ -323,15 +323,16 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re for { /* Get administrative permissions for the knora-base:ProjectAdmin group */ - administrativePermissionsOnProjectAdminGroup: Set[PermissionADM] <- administrativePermissionForGroupsGetADM( - projectIri, - List(OntologyConstants.KnoraAdmin.ProjectAdmin) - ) + administrativePermissionsOnProjectAdminGroup: Set[PermissionADM] <- + administrativePermissionForGroupsGetADM( + projectIri, + List(OntologyConstants.KnoraAdmin.ProjectAdmin) + ) _ = if (administrativePermissionsOnProjectAdminGroup.nonEmpty) { - if (extendedUserGroups.contains(OntologyConstants.KnoraAdmin.ProjectAdmin)) { - permissionsListBuffer += (("ProjectAdmin", administrativePermissionsOnProjectAdminGroup)) - } - } + if (extendedUserGroups.contains(OntologyConstants.KnoraAdmin.ProjectAdmin)) { + permissionsListBuffer += (("ProjectAdmin", administrativePermissionsOnProjectAdminGroup)) + } + } //_ = log.debug(s"userAdministrativePermissionsGetV1 - project: $projectIri, administrativePermissionsOnProjectAdminGroup: $administrativePermissionsOnProjectAdminGroup") /* Get administrative permissions for custom groups (all groups other than the built-in groups) */ @@ -348,53 +349,54 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re } } _ = if (administrativePermissionsOnCustomGroups.nonEmpty) { - if (permissionsListBuffer.isEmpty) { - permissionsListBuffer += (("CustomGroups", administrativePermissionsOnCustomGroups)) - } - } + if (permissionsListBuffer.isEmpty) { + permissionsListBuffer += (("CustomGroups", administrativePermissionsOnCustomGroups)) + } + } //_ = log.debug(s"userAdministrativePermissionsGetV1 - project: $projectIri, administrativePermissionsOnCustomGroups: $administrativePermissionsOnCustomGroups") /* Get administrative permissions for the knora-base:ProjectMember group */ - administrativePermissionsOnProjectMemberGroup: Set[PermissionADM] <- administrativePermissionForGroupsGetADM( - projectIri, - List(OntologyConstants.KnoraAdmin.ProjectMember) - ) + administrativePermissionsOnProjectMemberGroup: Set[PermissionADM] <- + administrativePermissionForGroupsGetADM( + projectIri, + List(OntologyConstants.KnoraAdmin.ProjectMember) + ) _ = if (administrativePermissionsOnProjectMemberGroup.nonEmpty) { - if (permissionsListBuffer.isEmpty) { - if (extendedUserGroups.contains(OntologyConstants.KnoraAdmin.ProjectMember)) { - permissionsListBuffer += (("ProjectMember", administrativePermissionsOnProjectMemberGroup)) + if (permissionsListBuffer.isEmpty) { + if (extendedUserGroups.contains(OntologyConstants.KnoraAdmin.ProjectMember)) { + permissionsListBuffer += (("ProjectMember", administrativePermissionsOnProjectMemberGroup)) + } + } } - } - } //_ = log.debug(s"userAdministrativePermissionsGetV1 - project: $projectIri, administrativePermissionsOnProjectMemberGroup: $administrativePermissionsOnProjectMemberGroup") /* Get administrative permissions for the knora-base:KnownUser group */ administrativePermissionsOnKnownUserGroup: Set[PermissionADM] <- administrativePermissionForGroupsGetADM( - projectIri, - List(OntologyConstants.KnoraAdmin.KnownUser) - ) + projectIri, + List(OntologyConstants.KnoraAdmin.KnownUser) + ) _ = if (administrativePermissionsOnKnownUserGroup.nonEmpty) { - if (permissionsListBuffer.isEmpty) { - if (extendedUserGroups.contains(OntologyConstants.KnoraAdmin.KnownUser)) { - permissionsListBuffer += (("KnownUser", administrativePermissionsOnKnownUserGroup)) + if (permissionsListBuffer.isEmpty) { + if (extendedUserGroups.contains(OntologyConstants.KnoraAdmin.KnownUser)) { + permissionsListBuffer += (("KnownUser", administrativePermissionsOnKnownUserGroup)) + } + } } - } - } //_ = log.debug(s"userAdministrativePermissionsGetV1 - project: $projectIri, administrativePermissionsOnKnownUserGroup: $administrativePermissionsOnKnownUserGroup") projectAdministrativePermissions: (IRI, Set[PermissionADM]) = permissionsListBuffer.length match { - case 1 => - log.debug( - s"userAdministrativePermissionsGetV1 - project: $projectIri, precedence: ${permissionsListBuffer.head._1}, administrativePermissions: ${permissionsListBuffer.head._2}" - ) - (projectIri, permissionsListBuffer.head._2) - - case 0 => (projectIri, Set.empty[PermissionADM]) - case _ => - throw AssertionException( - "The permissions list buffer holding default object permissions should never be larger then 1." - ) - } + case 1 => + log.debug( + s"userAdministrativePermissionsGetV1 - project: $projectIri, precedence: ${permissionsListBuffer.head._1}, administrativePermissions: ${permissionsListBuffer.head._2}" + ) + (projectIri, permissionsListBuffer.head._2) + + case 0 => (projectIri, Set.empty[PermissionADM]) + case _ => + throw AssertionException( + "The permissions list buffer holding default object permissions should never be larger then 1." + ) + } } yield projectAdministrativePermissions } @@ -437,13 +439,14 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re //_ = log.debug(s"administrativePermissionForGroupsGetADM - projectIri: $projectIri, groupIri: $groupIri") groupPermissions: Future[Seq[PermissionADM]] = administrativePermissionForProjectGroupGetADM( - projectIri, - groupIri, - requestingUser = KnoraSystemInstances.Users.SystemUser - ).map { - case Some(ap: AdministrativePermissionADM) => ap.hasPermissions.toSeq - case None => Seq.empty[PermissionADM] - } + projectIri, + groupIri, + requestingUser = KnoraSystemInstances.Users.SystemUser + ).map { + case Some(ap: AdministrativePermissionADM) => + ap.hasPermissions.toSeq + case None => Seq.empty[PermissionADM] + } } yield groupPermissions @@ -458,8 +461,8 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re /* Combine permission sequences */ combined = cleanedAllPermissions.foldLeft(Seq.empty[PermissionADM]) { (acc, seq) => - acc ++ seq - } + acc ++ seq + } /* Remove possible duplicate permissions */ result: Set[PermissionADM] = PermissionUtilADM.removeDuplicatePermissions(combined) @@ -483,12 +486,12 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re ): Future[AdministrativePermissionsForProjectGetResponseADM] = for { sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getAdministrativePermissionsForProject( - projectIri = projectIRI - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getAdministrativePermissionsForProject( + projectIri = projectIRI + ) + .toString() + ) //_ = log.debug(s"administrativePermissionsForProjectGetRequestADM - query: $sparqlQueryString") permissionsQueryResponse <- (storeManager ? SparqlSelectRequest(sparqlQueryString)).mapTo[SparqlSelectResult] @@ -497,15 +500,16 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re /* extract response rows */ permissionsQueryResponseRows: Seq[VariableResultsRow] = permissionsQueryResponse.results.bindings - permissionsWithProperties: Map[String, Map[String, String]] = permissionsQueryResponseRows - .groupBy(_.rowMap("s")) - .map { case (permissionIri: String, rows: Seq[VariableResultsRow]) => - (permissionIri, rows.map(row => (row.rowMap("p"), row.rowMap("o"))).toMap) - } + permissionsWithProperties: Map[String, Map[String, String]] = + permissionsQueryResponseRows + .groupBy(_.rowMap("s")) + .map { case (permissionIri: String, rows: Seq[VariableResultsRow]) => + (permissionIri, rows.map(row => (row.rowMap("p"), row.rowMap("o"))).toMap) + } //_ = log.debug(s"administrativePermissionsForProjectGetRequestADM - permissionsWithProperties: $permissionsWithProperties") - administrativePermissions: Seq[AdministrativePermissionADM] = permissionsWithProperties.map { - case (permissionIri: IRI, propsMap: Map[String, String]) => + administrativePermissions: Seq[AdministrativePermissionADM] = + permissionsWithProperties.map { case (permissionIri: IRI, propsMap: Map[String, String]) => /* parse permissions */ val hasPermissions: Set[PermissionADM] = PermissionUtilADM.parsePermissionsWithType( @@ -530,7 +534,7 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re ), hasPermissions = hasPermissions ) - }.toSeq + }.toSeq /* construct response object */ response = permissionsmessages.AdministrativePermissionsForProjectGetResponseADM(administrativePermissions) @@ -553,10 +557,11 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re for { administrativePermission <- permissionGetADM(administrativePermissionIri, requestingUser) result = administrativePermission match { - case ap: AdministrativePermissionADM => - AdministrativePermissionGetResponseADM(ap) - case _ => throw BadRequestException(s"$administrativePermissionIri is not an administrative permission.") - } + case ap: AdministrativePermissionADM => + AdministrativePermissionGetResponseADM(ap) + case _ => + throw BadRequestException(s"$administrativePermissionIri is not an administrative permission.") + } } yield result /** @@ -574,13 +579,13 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re ): Future[Option[AdministrativePermissionADM]] = for { sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getAdministrativePermissionForProjectAndGroup( - projectIri = projectIri, - groupIri = groupIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getAdministrativePermissionForProjectAndGroup( + projectIri = projectIri, + groupIri = groupIri + ) + .toString() + ) //_ = log.debug(s"administrativePermissionForProjectGroupGetADM - query: $sparqlQueryString") permissionQueryResponse <- (storeManager ? SparqlSelectRequest(sparqlQueryString)).mapTo[SparqlSelectResult] @@ -638,17 +643,17 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re ): Future[AdministrativePermissionGetResponseADM] = for { ap <- administrativePermissionForProjectGroupGetADM( - projectIri, - groupIri, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + projectIri, + groupIri, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) result = ap match { - case Some(ap) => permissionsmessages.AdministrativePermissionGetResponseADM(ap) - case None => - throw NotFoundException( - s"No Administrative Permission found for project: $projectIri, group: $groupIri combination" - ) - } + case Some(ap) => permissionsmessages.AdministrativePermissionGetResponseADM(ap) + case None => + throw NotFoundException( + s"No Administrative Permission found for project: $projectIri, group: $groupIri combination" + ) + } } yield result /** @@ -679,33 +684,35 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re // does the permission already exist checkResult: Option[AdministrativePermissionADM] <- administrativePermissionForProjectGroupGetADM( - createRequest.forProject, - createRequest.forGroup, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + createRequest.forProject, + createRequest.forGroup, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) _ = checkResult match { - case Some(ap: AdministrativePermissionADM) => - throw DuplicateValueException( - s"An administrative permission for project: '${createRequest.forProject}' and group: '${createRequest.forGroup}' combination already exists. " + - s"This permission currently has the scope '${PermissionUtilADM - .formatPermissionADMs(ap.hasPermissions, PermissionType.AP)}'. " + - s"Use its IRI ${ap.iri} to modify it, if necessary." - ) - case None => () - } + case Some(ap: AdministrativePermissionADM) => + throw DuplicateValueException( + s"An administrative permission for project: '${createRequest.forProject}' and group: '${createRequest.forGroup}' combination already exists. " + + s"This permission currently has the scope '${PermissionUtilADM + .formatPermissionADMs(ap.hasPermissions, PermissionType.AP)}'. " + + s"Use its IRI ${ap.iri} to modify it, if necessary." + ) + case None => () + } // get project maybeProject: Option[ProjectADM] <- (responderManager ? ProjectGetADM( - identifier = ProjectIdentifierADM(maybeIri = Some(createRequest.forProject)), - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - )).mapTo[Option[ProjectADM]] + identifier = + ProjectIdentifierADM(maybeIri = Some(createRequest.forProject)), + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + )).mapTo[Option[ProjectADM]] // if it doesnt exist then throw an error - project: ProjectADM = maybeProject.getOrElse( - throw NotFoundException(s"Project '${createRequest.forProject}' not found. Aborting request.") - ) + project: ProjectADM = + maybeProject.getOrElse( + throw NotFoundException(s"Project '${createRequest.forProject}' not found. Aborting request.") + ) // get group groupIri: IRI <- @@ -714,57 +721,63 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re } else { for { maybeGroup <- (responderManager ? GroupGetADM( - groupIri = createRequest.forGroup, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - )).mapTo[Option[GroupADM]] + groupIri = createRequest.forGroup, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + )).mapTo[Option[GroupADM]] // if it does not exist then throw an error - group: GroupADM = maybeGroup.getOrElse( - throw NotFoundException(s"Group '${createRequest.forGroup}' not found. Aborting request.") - ) + group: GroupADM = + maybeGroup.getOrElse( + throw NotFoundException(s"Group '${createRequest.forGroup}' not found. Aborting request.") + ) } yield group.id } customPermissionIri: Option[SmartIri] = createRequest.id.map(iri => iri.toSmartIri) newPermissionIri: IRI <- checkOrCreateEntityIri( - customPermissionIri, - stringFormatter.makeRandomPermissionIri(project.shortcode) - ) + customPermissionIri, + stringFormatter.makeRandomPermissionIri(project.shortcode) + ) // Create the administrative permission. createAdministrativePermissionSparqlString = org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .createNewAdministrativePermission( - namedGraphIri = OntologyConstants.NamedGraphs.PermissionNamedGraph, - permissionClassIri = OntologyConstants.KnoraAdmin.AdministrativePermission, - permissionIri = newPermissionIri, - projectIri = project.id, - groupIri = groupIri, - permissions = PermissionUtilADM.formatPermissionADMs(createRequest.hasPermissions, PermissionType.AP) - ) - .toString + .createNewAdministrativePermission( + namedGraphIri = + OntologyConstants.NamedGraphs.PermissionNamedGraph, + permissionClassIri = + OntologyConstants.KnoraAdmin.AdministrativePermission, + permissionIri = newPermissionIri, + projectIri = project.id, + groupIri = groupIri, + permissions = PermissionUtilADM.formatPermissionADMs( + createRequest.hasPermissions, + PermissionType.AP + ) + ) + .toString // _ = log.debug("projectCreateRequestADM - create query: {}", createNewProjectSparqlString) _ <- (storeManager ? SparqlUpdateRequest(createAdministrativePermissionSparqlString)) - .mapTo[SparqlUpdateResponse] + .mapTo[SparqlUpdateResponse] // try to retrieve the newly created permission maybePermission <- administrativePermissionForIriGetRequestADM( - administrativePermissionIri = newPermissionIri, - requestingUser = requestingUser, - apiRequestID = apiRequestID - ) + administrativePermissionIri = newPermissionIri, + requestingUser = requestingUser, + apiRequestID = apiRequestID + ) newAdminPermission: AdministrativePermissionADM = maybePermission.administrativePermission } yield AdministrativePermissionCreateResponseADM(administrativePermission = newAdminPermission) for { // run the task with an IRI lock taskResult <- IriLocker.runWithIriLock( - apiRequestID, - PERMISSIONS_GLOBAL_LOCK_IRI, - () => createPermissionTask(createRequest, requestingUser) - ) + apiRequestID, + PERMISSIONS_GLOBAL_LOCK_IRI, + () => createPermissionTask(createRequest, requestingUser) + ) } yield taskResult } @@ -788,20 +801,20 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re projectIri <- getProjectOfEntity(resourceIri) // Check user's permission for the operation _ = if ( - !requestingUser.isSystemAdmin - && !requestingUser.permissions.isProjectAdmin(projectIri) - && !requestingUser.isSystemUser - ) { - throw ForbiddenException("Object access permissions can only be queried by system and project admin.") - } + !requestingUser.isSystemAdmin + && !requestingUser.permissions.isProjectAdmin(projectIri) + && !requestingUser.isSystemUser + ) { + throw ForbiddenException("Object access permissions can only be queried by system and project admin.") + } sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getObjectAccessPermission( - resourceIri = Some(resourceIri), - valueIri = None - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getObjectAccessPermission( + resourceIri = Some(resourceIri), + valueIri = None + ) + .toString() + ) //_ = log.debug(s"objectAccessPermissionsForResourceGetV1 - query: $sparqlQueryString") permissionQueryResponse <- (storeManager ? SparqlSelectRequest(sparqlQueryString)).mapTo[SparqlSelectResult] @@ -846,20 +859,20 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re projectIri <- getProjectOfEntity(valueIri) // Check user's permission for the operation _ = if ( - !requestingUser.isSystemAdmin - && !requestingUser.permissions.isProjectAdmin(projectIri) - && !requestingUser.isSystemUser - ) { - throw ForbiddenException("Object access permissions can only be queried by system and project admin.") - } + !requestingUser.isSystemAdmin + && !requestingUser.permissions.isProjectAdmin(projectIri) + && !requestingUser.isSystemUser + ) { + throw ForbiddenException("Object access permissions can only be queried by system and project admin.") + } sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getObjectAccessPermission( - resourceIri = None, - valueIri = Some(valueIri) - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getObjectAccessPermission( + resourceIri = None, + valueIri = Some(valueIri) + ) + .toString() + ) //_ = log.debug(s"objectAccessPermissionsForValueGetV1 - query: $sparqlQueryString") permissionQueryResponse <- (storeManager ? SparqlSelectRequest(sparqlQueryString)).mapTo[SparqlSelectResult] @@ -907,12 +920,12 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re ): Future[DefaultObjectAccessPermissionsForProjectGetResponseADM] = for { sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getDefaultObjectAccessPermissionsForProject( - projectIri = projectIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getDefaultObjectAccessPermissionsForProject( + projectIri = projectIri + ) + .toString() + ) //_ = log.debug(s"defaultObjectAccessPermissionsForProjectGetRequestADM - query: $sparqlQueryString") permissionsQueryResponse <- (storeManager ? SparqlSelectRequest(sparqlQueryString)).mapTo[SparqlSelectResult] @@ -921,35 +934,45 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re /* extract response rows */ permissionsQueryResponseRows: Seq[VariableResultsRow] = permissionsQueryResponse.results.bindings - permissionsWithProperties: Map[String, Map[String, String]] = permissionsQueryResponseRows - .groupBy(_.rowMap("s")) - .map { case (permissionIri: String, rows: Seq[VariableResultsRow]) => - (permissionIri, rows.map(row => (row.rowMap("p"), row.rowMap("o"))).toMap) - } + permissionsWithProperties: Map[String, Map[String, String]] = + permissionsQueryResponseRows + .groupBy(_.rowMap("s")) + .map { case (permissionIri: String, rows: Seq[VariableResultsRow]) => + (permissionIri, rows.map(row => (row.rowMap("p"), row.rowMap("o"))).toMap) + } //_ = log.debug(s"defaultObjectAccessPermissionsForProjectGetRequestADM - permissionsWithProperties: $permissionsWithProperties") permissions: Seq[DefaultObjectAccessPermissionADM] = permissionsWithProperties.map { - case (permissionIri: IRI, propsMap: Map[String, String]) => - /* parse permissions */ - val hasPermissions: Set[PermissionADM] = - PermissionUtilADM.parsePermissionsWithType( - propsMap.get(OntologyConstants.KnoraBase.HasPermissions), - PermissionType.OAP - ) - - /* construct permission object */ - DefaultObjectAccessPermissionADM( - iri = permissionIri, - forProject = propsMap.getOrElse( - OntologyConstants.KnoraAdmin.ForProject, - throw InconsistentRepositoryDataException(s"Permission $permissionIri has no project.") - ), - forGroup = propsMap.get(OntologyConstants.KnoraAdmin.ForGroup), - forResourceClass = propsMap.get(OntologyConstants.KnoraAdmin.ForResourceClass), - forProperty = propsMap.get(OntologyConstants.KnoraAdmin.ForProperty), - hasPermissions = hasPermissions - ) - }.toSeq + case (permissionIri: IRI, propsMap: Map[String, String]) => + /* parse permissions */ + val hasPermissions: Set[PermissionADM] = + PermissionUtilADM.parsePermissionsWithType( + propsMap.get( + OntologyConstants.KnoraBase.HasPermissions + ), + PermissionType.OAP + ) + + /* construct permission object */ + DefaultObjectAccessPermissionADM( + iri = permissionIri, + forProject = propsMap.getOrElse( + OntologyConstants.KnoraAdmin.ForProject, + throw InconsistentRepositoryDataException( + s"Permission $permissionIri has no project." + ) + ), + forGroup = + propsMap.get(OntologyConstants.KnoraAdmin.ForGroup), + forResourceClass = propsMap.get( + OntologyConstants.KnoraAdmin.ForResourceClass + ), + forProperty = propsMap.get( + OntologyConstants.KnoraAdmin.ForProperty + ), + hasPermissions = hasPermissions + ) + }.toSeq /* construct response object */ response = DefaultObjectAccessPermissionsForProjectGetResponseADM(permissions) @@ -972,10 +995,10 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re for { defaultObjectAccessPermission <- permissionGetADM(permissionIri, requestingUser) result = defaultObjectAccessPermission match { - case doap: DefaultObjectAccessPermissionADM => - DefaultObjectAccessPermissionGetResponseADM(doap) - case _ => throw BadRequestException(s"$permissionIri is not a default object access permission.") - } + case doap: DefaultObjectAccessPermissionADM => + DefaultObjectAccessPermissionGetResponseADM(doap) + case _ => throw BadRequestException(s"$permissionIri is not a default object access permission.") + } } yield result /** @@ -1019,15 +1042,15 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re for { sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getDefaultObjectAccessPermission( - projectIri = projectIri, - maybeGroupIri = groupIri, - maybeResourceClassIri = resourceClassIri, - maybePropertyIri = propertyIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getDefaultObjectAccessPermission( + projectIri = projectIri, + maybeGroupIri = groupIri, + maybeResourceClassIri = resourceClassIri, + maybePropertyIri = propertyIri + ) + .toString() + ) // _ = logger.debug(s"defaultObjectAccessPermissionGetADM - query: $sparqlQueryString") @@ -1080,9 +1103,10 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re } else { None } - _ = logger.debug( - s"defaultObjectAccessPermissionGetADM - p: $projectIri, g: $groupIri, r: $resourceClassIri, p: $propertyIri, permission: $permission" - ) + _ = + logger.debug( + s"defaultObjectAccessPermissionGetADM - p: $projectIri, g: $groupIri, r: $resourceClassIri, p: $propertyIri, permission: $permission" + ) } yield permission } @@ -1118,7 +1142,7 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re /* if the query was for a property, then we need to additionally check if it is a system property */ if (propertyIri.isDefined) { val systemProject = OntologyConstants.KnoraAdmin.SystemProject - val doapF = defaultObjectAccessPermissionGetADM(systemProject, groupIri, resourceClassIri, propertyIri) + val doapF = defaultObjectAccessPermissionGetADM(systemProject, groupIri, resourceClassIri, propertyIri) doapF.mapTo[Option[DefaultObjectAccessPermissionADM]].map { case Some(systemDoap) => DefaultObjectAccessPermissionGetResponseADM(systemDoap) case None => @@ -1151,14 +1175,15 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re //_ = log.debug(s"userDefaultObjectAccessPermissionsGetV1 - projectIri: $projectIri, groupIri: $groupIri") groupPermissions: Future[Seq[PermissionADM]] = defaultObjectAccessPermissionGetADM( - projectIri = projectIri, - groupIri = Some(groupIri), - resourceClassIri = None, - propertyIri = None - ).map { - case Some(doap: DefaultObjectAccessPermissionADM) => doap.hasPermissions.toSeq - case None => Seq.empty[PermissionADM] - } + projectIri = projectIri, + groupIri = Some(groupIri), + resourceClassIri = None, + propertyIri = None + ).map { + case Some(doap: DefaultObjectAccessPermissionADM) => + doap.hasPermissions.toSeq + case None => Seq.empty[PermissionADM] + } } yield groupPermissions @@ -1173,14 +1198,15 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re /* Combine permission sequences */ combined = cleanedAllPermissions.foldLeft(Seq.empty[PermissionADM]) { (acc, seq) => - acc ++ seq - } + acc ++ seq + } /* Remove possible duplicate permissions */ result: Set[PermissionADM] = PermissionUtilADM.removeDuplicatePermissions(combined) - _ = logger.debug( - s"defaultObjectAccessPermissionsForGroupsGetADM - INPUT [ projectIri: $projectIri, groups: $groups ], RESULT [ $result ]" - ) + _ = + logger.debug( + s"defaultObjectAccessPermissionsForGroupsGetADM - INPUT [ projectIri: $projectIri, groups: $groups ], RESULT [ $result ]" + ) } yield result result } @@ -1198,15 +1224,15 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re ): Future[Set[PermissionADM]] = for { defaultPermissionsOption: Option[DefaultObjectAccessPermissionADM] <- defaultObjectAccessPermissionGetADM( - projectIri = projectIri, - groupIri = None, - resourceClassIri = Some(resourceClassIri), - propertyIri = None - ) + projectIri = projectIri, + groupIri = None, + resourceClassIri = Some(resourceClassIri), + propertyIri = None + ) defaultPermissions: Set[PermissionADM] = defaultPermissionsOption match { - case Some(doap) => doap.hasPermissions - case None => Set.empty[PermissionADM] - } + case Some(doap) => doap.hasPermissions + case None => Set.empty[PermissionADM] + } } yield defaultPermissions /** @@ -1224,15 +1250,15 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re ): Future[Set[PermissionADM]] = for { defaultPermissionsOption: Option[DefaultObjectAccessPermissionADM] <- defaultObjectAccessPermissionGetADM( - projectIri = projectIri, - groupIri = None, - resourceClassIri = Some(resourceClassIri), - propertyIri = Some(propertyIri) - ) + projectIri = projectIri, + groupIri = None, + resourceClassIri = Some(resourceClassIri), + propertyIri = Some(propertyIri) + ) defaultPermissions: Set[PermissionADM] = defaultPermissionsOption match { - case Some(doap) => doap.hasPermissions - case None => Set.empty[PermissionADM] - } + case Some(doap) => doap.hasPermissions + case None => Set.empty[PermissionADM] + } } yield defaultPermissions /** @@ -1248,15 +1274,15 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re ): Future[Set[PermissionADM]] = for { defaultPermissionsOption: Option[DefaultObjectAccessPermissionADM] <- defaultObjectAccessPermissionGetADM( - projectIri = projectIri, - groupIri = None, - resourceClassIri = None, - propertyIri = Some(propertyIri) - ) + projectIri = projectIri, + groupIri = None, + resourceClassIri = None, + propertyIri = Some(propertyIri) + ) defaultPermissions: Set[PermissionADM] = defaultPermissionsOption match { - case Some(doap) => doap.hasPermissions - case None => Set.empty[PermissionADM] - } + case Some(doap) => doap.hasPermissions + case None => Set.empty[PermissionADM] + } } yield defaultPermissions /** @@ -1284,9 +1310,9 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re /* Get the groups the user is member of. */ userGroupsOption: Option[Seq[IRI]] <- Future(targetUser.permissions.groupsPerProject.get(projectIri)) userGroups: Seq[IRI] = userGroupsOption match { - case Some(groups) => groups - case None => Seq.empty[IRI] - } + case Some(groups) => groups + case None => Seq.empty[IRI] + } /* Explicitly add 'SystemAdmin' and 'KnownUser' groups. */ extendedUserGroups: List[IRI] = @@ -1309,19 +1335,19 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re /////////////////////// /* Get the default object access permissions for the knora-base:ProjectAdmin group */ defaultPermissionsOnProjectAdminGroup: Set[PermissionADM] <- defaultObjectAccessPermissionsForGroupsGetADM( - projectIri, - List(OntologyConstants.KnoraAdmin.ProjectAdmin) - ) + projectIri, + List(OntologyConstants.KnoraAdmin.ProjectAdmin) + ) _ = if (defaultPermissionsOnProjectAdminGroup.nonEmpty) { - if ( - extendedUserGroups.contains(OntologyConstants.KnoraAdmin.ProjectAdmin) || extendedUserGroups.contains( - OntologyConstants.KnoraAdmin.SystemAdmin - ) - ) { - permissionsListBuffer += (("ProjectAdmin", defaultPermissionsOnProjectAdminGroup)) - // log.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnProjectAdminGroup: $defaultPermissionsOnProjectAdminGroup") - } - } + if ( + extendedUserGroups.contains(OntologyConstants.KnoraAdmin.ProjectAdmin) || extendedUserGroups.contains( + OntologyConstants.KnoraAdmin.SystemAdmin + ) + ) { + permissionsListBuffer += (("ProjectAdmin", defaultPermissionsOnProjectAdminGroup)) + // log.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnProjectAdminGroup: $defaultPermissionsOnProjectAdminGroup") + } + } /////////////////////////////// // RESOURCE CLASS / PROPERTY @@ -1339,9 +1365,14 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re } } _ = if (defaultPermissionsOnProjectResourceClassProperty.nonEmpty) { - permissionsListBuffer += (("ProjectResourceClassProperty", defaultPermissionsOnProjectResourceClassProperty)) - // log.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnProjectResourceClassProperty: {}", defaultPermissionsOnProjectResourceClassProperty) - } + permissionsListBuffer += ( + ( + "ProjectResourceClassProperty", + defaultPermissionsOnProjectResourceClassProperty + ) + ) + // log.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnProjectResourceClassProperty: {}", defaultPermissionsOnProjectResourceClassProperty) + } /* system resource class / property combination */ defaultPermissionsOnSystemResourceClassProperty: Set[PermissionADM] <- { @@ -1357,9 +1388,9 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re } } _ = if (defaultPermissionsOnSystemResourceClassProperty.nonEmpty) { - permissionsListBuffer += (("SystemResourceClassProperty", defaultPermissionsOnSystemResourceClassProperty)) - // log.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnSystemResourceClassProperty: {}", defaultPermissionsOnSystemResourceClassProperty) - } + permissionsListBuffer += (("SystemResourceClassProperty", defaultPermissionsOnSystemResourceClassProperty)) + // log.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnSystemResourceClassProperty: {}", defaultPermissionsOnSystemResourceClassProperty) + } /////////////////////// // RESOURCE CLASS @@ -1376,9 +1407,9 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re } } _ = if (defaultPermissionsOnProjectResourceClass.nonEmpty) { - permissionsListBuffer += (("ProjectResourceClass", defaultPermissionsOnProjectResourceClass)) - // log.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnProjectResourceClass: {}", defaultPermissionsOnProjectResourceClass) - } + permissionsListBuffer += (("ProjectResourceClass", defaultPermissionsOnProjectResourceClass)) + // log.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnProjectResourceClass: {}", defaultPermissionsOnProjectResourceClass) + } /* Get the default object access permissions defined on the resource class inside the SystemProject */ defaultPermissionsOnSystemResourceClass: Set[PermissionADM] <- { @@ -1393,9 +1424,9 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re } } _ = if (defaultPermissionsOnSystemResourceClass.nonEmpty) { - permissionsListBuffer += (("SystemResourceClass", defaultPermissionsOnSystemResourceClass)) - // log.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnSystemResourceClass: {}", defaultPermissionsOnSystemResourceClass) - } + permissionsListBuffer += (("SystemResourceClass", defaultPermissionsOnSystemResourceClass)) + // log.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnSystemResourceClass: {}", defaultPermissionsOnSystemResourceClass) + } /////////////////////// // PROPERTY @@ -1412,9 +1443,9 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re } } _ = if (defaultPermissionsOnProjectProperty.nonEmpty) { - permissionsListBuffer += (("ProjectProperty", defaultPermissionsOnProjectProperty)) - // logger.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnProjectProperty: {}", defaultPermissionsOnProjectProperty) - } + permissionsListBuffer += (("ProjectProperty", defaultPermissionsOnProjectProperty)) + // logger.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnProjectProperty: {}", defaultPermissionsOnProjectProperty) + } /* system property */ defaultPermissionsOnSystemProperty: Set[PermissionADM] <- { @@ -1429,9 +1460,9 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re } } _ = if (defaultPermissionsOnSystemProperty.nonEmpty) { - permissionsListBuffer += (("SystemProperty", defaultPermissionsOnSystemProperty)) - // logger.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnSystemProperty: {}", defaultPermissionsOnSystemProperty) - } + permissionsListBuffer += (("SystemProperty", defaultPermissionsOnSystemProperty)) + // logger.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnSystemProperty: {}", defaultPermissionsOnSystemProperty) + } /////////////////////// // CUSTOM GROUPS @@ -1456,9 +1487,9 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re } } _ = if (defaultPermissionsOnCustomGroups.nonEmpty) { - permissionsListBuffer += (("CustomGroups", defaultPermissionsOnCustomGroups)) - // logger.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnCustomGroups: $defaultPermissionsOnCustomGroups") - } + permissionsListBuffer += (("CustomGroups", defaultPermissionsOnCustomGroups)) + // logger.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnCustomGroups: $defaultPermissionsOnCustomGroups") + } /////////////////////// // PROJECT MEMBER @@ -1472,15 +1503,15 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re } } _ = if (defaultPermissionsOnProjectMemberGroup.nonEmpty) { - if ( - extendedUserGroups.contains(OntologyConstants.KnoraAdmin.ProjectMember) || extendedUserGroups.contains( - OntologyConstants.KnoraAdmin.SystemAdmin - ) - ) { - permissionsListBuffer += (("ProjectMember", defaultPermissionsOnProjectMemberGroup)) - } - // logger.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnProjectMemberGroup: $defaultPermissionsOnProjectMemberGroup") - } + if ( + extendedUserGroups.contains(OntologyConstants.KnoraAdmin.ProjectMember) || extendedUserGroups.contains( + OntologyConstants.KnoraAdmin.SystemAdmin + ) + ) { + permissionsListBuffer += (("ProjectMember", defaultPermissionsOnProjectMemberGroup)) + } + // logger.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnProjectMemberGroup: $defaultPermissionsOnProjectMemberGroup") + } /////////////////////// // KNOWN USER @@ -1494,11 +1525,11 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re } } _ = if (defaultPermissionsOnKnownUserGroup.nonEmpty) { - if (extendedUserGroups.contains(OntologyConstants.KnoraAdmin.KnownUser)) { - permissionsListBuffer += (("KnownUser", defaultPermissionsOnKnownUserGroup)) - // logger.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnKnownUserGroup: $defaultPermissionsOnKnownUserGroup") - } - } + if (extendedUserGroups.contains(OntologyConstants.KnoraAdmin.KnownUser)) { + permissionsListBuffer += (("KnownUser", defaultPermissionsOnKnownUserGroup)) + // logger.debug(s"defaultObjectAccessPermissionsStringForEntityGetV1 - defaultPermissionsOnKnownUserGroup: $defaultPermissionsOnKnownUserGroup") + } + } /////////////////////// // FALLBACK PERMISSION IF NONE COULD BE FOUND @@ -1517,15 +1548,16 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re /* Create permissions string */ result = permissionsListBuffer.length match { - case 1 => PermissionUtilADM.formatPermissionADMs(permissionsListBuffer.head._2, PermissionType.OAP) - case _ => - throw AssertionException( - "The permissions list buffer holding default object permissions should never be larger then 1." - ) - } - _ = logger.debug( - s"defaultObjectAccessPermissionsStringForEntityGetADM (result) - project: $projectIri, precedence: ${permissionsListBuffer.head._1}, defaultObjectAccessPermissions: $result" - ) + case 1 => PermissionUtilADM.formatPermissionADMs(permissionsListBuffer.head._2, PermissionType.OAP) + case _ => + throw AssertionException( + "The permissions list buffer holding default object permissions should never be larger then 1." + ) + } + _ = + logger.debug( + s"defaultObjectAccessPermissionsStringForEntityGetADM (result) - project: $projectIri, precedence: ${permissionsListBuffer.head._1}, defaultObjectAccessPermissions: $result" + ) } yield permissionsmessages.DefaultObjectAccessPermissionsStringResponseADM(result) } @@ -1543,13 +1575,15 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re for { permission <- permissionGetADM(permissionIri, requestingUser) result = permission match { - case doap: DefaultObjectAccessPermissionADM => - DefaultObjectAccessPermissionGetResponseADM(doap) - case ap: AdministrativePermissionADM => - AdministrativePermissionGetResponseADM(ap) - case _ => - throw BadRequestException(s"$permissionIri is not a default object access or an administrative permission.") - } + case doap: DefaultObjectAccessPermissionADM => + DefaultObjectAccessPermissionGetResponseADM(doap) + case ap: AdministrativePermissionADM => + AdministrativePermissionGetResponseADM(ap) + case _ => + throw BadRequestException( + s"$permissionIri is not a default object access or an administrative permission." + ) + } } yield result private def defaultObjectAccessPermissionCreateRequestADM( @@ -1568,52 +1602,54 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re ): Future[DefaultObjectAccessPermissionCreateResponseADM] = for { checkResult <- defaultObjectAccessPermissionGetADM( - createRequest.forProject, - createRequest.forGroup, - createRequest.forResourceClass, - createRequest.forProperty - ) + createRequest.forProject, + createRequest.forGroup, + createRequest.forResourceClass, + createRequest.forProperty + ) _ = checkResult match { - case Some(doap: DefaultObjectAccessPermissionADM) => - val errorMessage = if (doap.forGroup.nonEmpty) { - s"and group: '${doap.forGroup.get}' " - } else { - val resourceClassExists = if (doap.forResourceClass.nonEmpty) { - s"and resourceClass: '${doap.forResourceClass.get}' " - } else "" - val propExists = if (doap.forProperty.nonEmpty) { - s"and property: '${doap.forProperty.get}' " - } else "" - resourceClassExists + propExists + case Some(doap: DefaultObjectAccessPermissionADM) => + val errorMessage = if (doap.forGroup.nonEmpty) { + s"and group: '${doap.forGroup.get}' " + } else { + val resourceClassExists = if (doap.forResourceClass.nonEmpty) { + s"and resourceClass: '${doap.forResourceClass.get}' " + } else "" + val propExists = if (doap.forProperty.nonEmpty) { + s"and property: '${doap.forProperty.get}' " + } else "" + resourceClassExists + propExists + } + throw DuplicateValueException( + s"A default object access permission for project: '${createRequest.forProject}' " + + errorMessage + "combination already exists. " + + s"This permission currently has the scope '${PermissionUtilADM + .formatPermissionADMs(doap.hasPermissions, PermissionType.OAP)}'. " + + s"Use its IRI ${doap.iri} to modify it, if necessary." + ) + case None => () } - throw DuplicateValueException( - s"A default object access permission for project: '${createRequest.forProject}' " + - errorMessage + "combination already exists. " + - s"This permission currently has the scope '${PermissionUtilADM - .formatPermissionADMs(doap.hasPermissions, PermissionType.OAP)}'. " + - s"Use its IRI ${doap.iri} to modify it, if necessary." - ) - case None => () - } // get project maybeProject: Option[ProjectADM] <- (responderManager ? ProjectGetADM( - identifier = ProjectIdentifierADM(maybeIri = Some(createRequest.forProject)), - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - )).mapTo[Option[ProjectADM]] + identifier = + ProjectIdentifierADM(maybeIri = Some(createRequest.forProject)), + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + )).mapTo[Option[ProjectADM]] // if it doesnt exist then throw an error - project: ProjectADM = maybeProject.getOrElse( - throw NotFoundException(s"Project '${createRequest.forProject}' not found. Aborting request.") - ) + project: ProjectADM = + maybeProject.getOrElse( + throw NotFoundException(s"Project '${createRequest.forProject}' not found. Aborting request.") + ) customPermissionIri: Option[SmartIri] = createRequest.id.map(iri => iri.toSmartIri) newPermissionIri: IRI <- checkOrCreateEntityIri( - customPermissionIri, - stringFormatter.makeRandomPermissionIri(project.shortcode) - ) + customPermissionIri, + stringFormatter.makeRandomPermissionIri(project.shortcode) + ) // verify group, if any given. // Is a group given that is not a built-in one? maybeGroupIri: Option[IRI] <- @@ -1621,14 +1657,15 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re // Yes. Check if it is a known group. for { maybeGroup <- (responderManager ? GroupGetADM( - groupIri = createRequest.forGroup.get, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - )).mapTo[Option[GroupADM]] - - group: GroupADM = maybeGroup.getOrElse( - throw NotFoundException(s"Group '${createRequest.forGroup}' not found. Aborting request.") - ) + groupIri = createRequest.forGroup.get, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + )).mapTo[Option[GroupADM]] + + group: GroupADM = + maybeGroup.getOrElse( + throw NotFoundException(s"Group '${createRequest.forGroup}' not found. Aborting request.") + ) } yield Some(group.id) } else { // No, return given group as it is. That means: @@ -1639,34 +1676,40 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re // Create the default object access permission. createNewDefaultObjectAccessPermissionSparqlString = org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .createNewDefaultObjectAccessPermission( - namedGraphIri = OntologyConstants.NamedGraphs.PermissionNamedGraph, - permissionIri = newPermissionIri, - permissionClassIri = OntologyConstants.KnoraAdmin.DefaultObjectAccessPermission, - projectIri = project.id, - maybeGroupIri = maybeGroupIri, - maybeResourceClassIri = createRequest.forResourceClass, - maybePropertyIri = createRequest.forProperty, - permissions = PermissionUtilADM.formatPermissionADMs(createRequest.hasPermissions, PermissionType.OAP) - ) - .toString + .createNewDefaultObjectAccessPermission( + namedGraphIri = + OntologyConstants.NamedGraphs.PermissionNamedGraph, + permissionIri = newPermissionIri, + permissionClassIri = + OntologyConstants.KnoraAdmin.DefaultObjectAccessPermission, + projectIri = project.id, + maybeGroupIri = maybeGroupIri, + maybeResourceClassIri = createRequest.forResourceClass, + maybePropertyIri = createRequest.forProperty, + permissions = PermissionUtilADM.formatPermissionADMs( + createRequest.hasPermissions, + PermissionType.OAP + ) + ) + .toString _ <- (storeManager ? SparqlUpdateRequest(createNewDefaultObjectAccessPermissionSparqlString)) - .mapTo[SparqlUpdateResponse] + .mapTo[SparqlUpdateResponse] // try to retrieve the newly created permission maybePermission <- defaultObjectAccessPermissionGetADM( - createRequest.forProject, - createRequest.forGroup, - createRequest.forResourceClass, - createRequest.forProperty - ) - - newDefaultObjectAcessPermission: DefaultObjectAccessPermissionADM = maybePermission.getOrElse( - throw BadRequestException( - "Requested default object access permission could not be created, report this as a possible bug." + createRequest.forProject, + createRequest.forGroup, + createRequest.forResourceClass, + createRequest.forProperty + ) + + newDefaultObjectAcessPermission: DefaultObjectAccessPermissionADM = + maybePermission.getOrElse( + throw BadRequestException( + "Requested default object access permission could not be created, report this as a possible bug." + ) ) - ) } yield DefaultObjectAccessPermissionCreateResponseADM(defaultObjectAccessPermission = newDefaultObjectAcessPermission @@ -1675,10 +1718,10 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re for { // run the task with an IRI lock taskResult <- IriLocker.runWithIriLock( - apiRequestID, - PERMISSIONS_GLOBAL_LOCK_IRI, - () => createPermissionTask(createRequest, requestingUser) - ) + apiRequestID, + PERMISSIONS_GLOBAL_LOCK_IRI, + () => createPermissionTask(createRequest, requestingUser) + ) } yield taskResult } @@ -1699,17 +1742,17 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re ): Future[PermissionsForProjectGetResponseADM] = for { sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .getProjectPermissions( - projectIri = projectIRI - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .getProjectPermissions( + projectIri = projectIRI + ) + .toString() + ) permissionsQueryResponse <- (storeManager ? SparqlConstructRequest( - sparql = sparqlQueryString, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlConstructResponse] + sparql = sparqlQueryString, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlConstructResponse] /* extract response statements */ permissionsQueryResponseStatements: Map[IRI, Seq[(IRI, String)]] = permissionsQueryResponse.statements @@ -1719,7 +1762,7 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re throw NotFoundException(s"No permission could be found for $projectIRI.") } else { permissionsQueryResponseStatements.map { statement => - val permissionIri = statement._1 + val permissionIri = statement._1 val (_, permissionType) = statement._2.filter(_._1 == OntologyConstants.Rdf.Type).head PermissionInfoADM(iri = permissionIri, permissionType = permissionType) }.toSet @@ -1750,27 +1793,27 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re def verifyPermissionGroupUpdate: Future[PermissionItemADM] = for { updatedPermission <- permissionGetADM( - permissionIri = permissionIri, - requestingUser = requestingUser - ) + permissionIri = permissionIri, + requestingUser = requestingUser + ) _ = updatedPermission match { - case ap: AdministrativePermissionADM => - if (ap.forGroup != changePermissionGroupRequest.forGroup) - throw UpdateNotPerformedException( - s"The group of permission $permissionIri was not updated. Please report this as a bug." - ) - case doap: DefaultObjectAccessPermissionADM => - if (doap.forGroup.get != changePermissionGroupRequest.forGroup) { - throw UpdateNotPerformedException( - s"The group of permission $permissionIri was not updated. Please report this as a bug." - ) - } else { - if (doap.forProperty.isDefined || doap.forResourceClass.isDefined) - throw UpdateNotPerformedException( - s"The $permissionIri is not correctly updated. Please report this as a bug." - ) + case ap: AdministrativePermissionADM => + if (ap.forGroup != changePermissionGroupRequest.forGroup) + throw UpdateNotPerformedException( + s"The group of permission $permissionIri was not updated. Please report this as a bug." + ) + case doap: DefaultObjectAccessPermissionADM => + if (doap.forGroup.get != changePermissionGroupRequest.forGroup) { + throw UpdateNotPerformedException( + s"The group of permission $permissionIri was not updated. Please report this as a bug." + ) + } else { + if (doap.forProperty.isDefined || doap.forResourceClass.isDefined) + throw UpdateNotPerformedException( + s"The $permissionIri is not correctly updated. Please report this as a bug." + ) + } } - } } yield updatedPermission /** @@ -1785,32 +1828,40 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re // get permission permission <- permissionGetADM(permissioniri, requestingUser) response <- permission match { - // Is permission an administrative permission? - case ap: AdministrativePermissionADM => - // Yes. Update the group - for { - _ <- updatePermission(permissionIri = ap.iri, maybeGroup = Some(changePermissionGroupRequest.forGroup)) - updatedPermission <- verifyPermissionGroupUpdate - } yield AdministrativePermissionGetResponseADM(updatedPermission.asInstanceOf[AdministrativePermissionADM]) - case doap: DefaultObjectAccessPermissionADM => - //No. It is a default object access permission - for { - // if a doap permission has a group defined, it cannot have either resourceClass or property - _ <- updatePermission(permissionIri = doap.iri, maybeGroup = Some(changePermissionGroupRequest.forGroup)) - updatedPermission <- verifyPermissionGroupUpdate - } yield DefaultObjectAccessPermissionGetResponseADM( - updatedPermission.asInstanceOf[DefaultObjectAccessPermissionADM] - ) - } + // Is permission an administrative permission? + case ap: AdministrativePermissionADM => + // Yes. Update the group + for { + _ <- updatePermission( + permissionIri = ap.iri, + maybeGroup = Some(changePermissionGroupRequest.forGroup) + ) + updatedPermission <- verifyPermissionGroupUpdate + } yield AdministrativePermissionGetResponseADM( + updatedPermission.asInstanceOf[AdministrativePermissionADM] + ) + case doap: DefaultObjectAccessPermissionADM => + //No. It is a default object access permission + for { + // if a doap permission has a group defined, it cannot have either resourceClass or property + _ <- updatePermission( + permissionIri = doap.iri, + maybeGroup = Some(changePermissionGroupRequest.forGroup) + ) + updatedPermission <- verifyPermissionGroupUpdate + } yield DefaultObjectAccessPermissionGetResponseADM( + updatedPermission.asInstanceOf[DefaultObjectAccessPermissionADM] + ) + } } yield response for { // run list info update with an local IRI lock taskResult <- IriLocker.runWithIriLock( - apiRequestID, - permissionIri, - () => permissionGroupChangeTask(permissionIri, changePermissionGroupRequest, requestingUser) - ) + apiRequestID, + permissionIri, + () => permissionGroupChangeTask(permissionIri, changePermissionGroupRequest, requestingUser) + ) } yield taskResult } @@ -1838,19 +1889,19 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re /*Verify that update was successful*/ _ = updatedPermission match { - case ap: AdministrativePermissionADM => - if (!ap.hasPermissions.equals(expectedPermissions)) - throw UpdateNotPerformedException( - s"The hasPermissions set of permission $permissionIri was not updated. Please report this as a bug." - ) - case doap: DefaultObjectAccessPermissionADM => - if (!doap.hasPermissions.equals(expectedPermissions)) { - throw UpdateNotPerformedException( - s"The hasPermissions set of permission $permissionIri was not updated. Please report this as a bug." - ) + case ap: AdministrativePermissionADM => + if (!ap.hasPermissions.equals(expectedPermissions)) + throw UpdateNotPerformedException( + s"The hasPermissions set of permission $permissionIri was not updated. Please report this as a bug." + ) + case doap: DefaultObjectAccessPermissionADM => + if (!doap.hasPermissions.equals(expectedPermissions)) { + throw UpdateNotPerformedException( + s"The hasPermissions set of permission $permissionIri was not updated. Please report this as a bug." + ) + } + case _ => None } - case _ => None - } } yield updatedPermission /** @@ -1865,45 +1916,54 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re // get permission permission <- permissionGetADM(permissionIri, requestingUser) response <- permission match { - // Is permission an administrative permission? - case ap: AdministrativePermissionADM => - // Yes. - val verifiedPermissions = - PermissionsMessagesUtilADM.verifyHasPermissionsAP(changeHasPermissionsRequest.hasPermissions) - for { - formattedPermissions <- Future( - PermissionUtilADM.formatPermissionADMs(verifiedPermissions, PermissionType.AP) - ) - _ <- updatePermission(permissionIri = ap.iri, maybeHasPermissions = Some(formattedPermissions)) - updatedPermission <- verifyUpdateOfHasPermissions(verifiedPermissions) - } yield AdministrativePermissionGetResponseADM(updatedPermission.asInstanceOf[AdministrativePermissionADM]) - case doap: DefaultObjectAccessPermissionADM => - //No. It is a default object access permission. - val verifiedPermissions = - PermissionsMessagesUtilADM.verifyHasPermissionsDOAP(changeHasPermissionsRequest.hasPermissions) - for { - formattedPermissions <- Future( - PermissionUtilADM.formatPermissionADMs(verifiedPermissions, PermissionType.OAP) - ) - _ <- updatePermission(permissionIri = doap.iri, maybeHasPermissions = Some(formattedPermissions)) - updatedPermission <- verifyUpdateOfHasPermissions(verifiedPermissions) - } yield DefaultObjectAccessPermissionGetResponseADM( - updatedPermission.asInstanceOf[DefaultObjectAccessPermissionADM] - ) - case _ => - throw UpdateNotPerformedException( - s"Permission $permissionIri was not updated. Please report this as a bug." - ) - } + // Is permission an administrative permission? + case ap: AdministrativePermissionADM => + // Yes. + val verifiedPermissions = + PermissionsMessagesUtilADM.verifyHasPermissionsAP(changeHasPermissionsRequest.hasPermissions) + for { + formattedPermissions <- + Future( + PermissionUtilADM.formatPermissionADMs(verifiedPermissions, PermissionType.AP) + ) + _ <- + updatePermission(permissionIri = ap.iri, maybeHasPermissions = Some(formattedPermissions)) + updatedPermission <- verifyUpdateOfHasPermissions(verifiedPermissions) + } yield AdministrativePermissionGetResponseADM( + updatedPermission.asInstanceOf[AdministrativePermissionADM] + ) + case doap: DefaultObjectAccessPermissionADM => + //No. It is a default object access permission. + val verifiedPermissions = + PermissionsMessagesUtilADM.verifyHasPermissionsDOAP( + changeHasPermissionsRequest.hasPermissions + ) + for { + formattedPermissions <- + Future( + PermissionUtilADM.formatPermissionADMs(verifiedPermissions, PermissionType.OAP) + ) + _ <- + updatePermission(permissionIri = doap.iri, maybeHasPermissions = Some(formattedPermissions)) + updatedPermission <- verifyUpdateOfHasPermissions(verifiedPermissions) + } yield DefaultObjectAccessPermissionGetResponseADM( + updatedPermission.asInstanceOf[DefaultObjectAccessPermissionADM] + ) + case _ => + throw UpdateNotPerformedException( + s"Permission $permissionIri was not updated. Please report this as a bug." + ) + } } yield response for { // run list info update with an local IRI lock - taskResult <- IriLocker.runWithIriLock( - apiRequestID, - permissionIri, - () => permissionHasPermissionsChangeTask(permissionIri, changeHasPermissionsRequest, requestingUser) - ) + taskResult <- + IriLocker.runWithIriLock( + apiRequestID, + permissionIri, + () => permissionHasPermissionsChangeTask(permissionIri, changeHasPermissionsRequest, requestingUser) + ) } yield taskResult } @@ -1931,22 +1991,22 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re /*Verify that update was successful*/ _ = updatedPermission match { - case doap: DefaultObjectAccessPermissionADM => - if (doap.forResourceClass.get != changePermissionResourceClass.forResourceClass) - throw UpdateNotPerformedException( - s"The resource class of ${doap.iri} was not updated. Please report this as a bug." - ) + case doap: DefaultObjectAccessPermissionADM => + if (doap.forResourceClass.get != changePermissionResourceClass.forResourceClass) + throw UpdateNotPerformedException( + s"The resource class of ${doap.iri} was not updated. Please report this as a bug." + ) - if (doap.forGroup.isDefined) - throw UpdateNotPerformedException( - s"The $permissionIri is not correctly updated. Please report this as a bug." - ) + if (doap.forGroup.isDefined) + throw UpdateNotPerformedException( + s"The $permissionIri is not correctly updated. Please report this as a bug." + ) - case _ => - throw UpdateNotPerformedException( - s"Incorrect permission type returned for $permissionIri. Please report this as a bug." - ) - } + case _ => + throw UpdateNotPerformedException( + s"Incorrect permission type returned for $permissionIri. Please report this as a bug." + ) + } } yield updatedPermission /** @@ -1961,38 +2021,39 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re // get permission permission <- permissionGetADM(permissionIri, requestingUser) response <- permission match { - // Is permission an administrative permission? - case ap: AdministrativePermissionADM => - // Yes. - throw BadRequestException( - s"Permission ${ap.iri} is of type administrative permission. " + - s"Only a default object access permission defined for a resource class can be updated." - ) - case doap: DefaultObjectAccessPermissionADM => - //No. It is a default object access permission. - for { - _ <- updatePermission( - permissionIri = doap.iri, - maybeResourceClass = Some(changePermissionResourceClass.forResourceClass) - ) - updatedPermission <- verifyUpdateOfResourceClass - } yield DefaultObjectAccessPermissionGetResponseADM( - updatedPermission.asInstanceOf[DefaultObjectAccessPermissionADM] - ) - case _ => - throw UpdateNotPerformedException( - s"Permission $permissionIri was not updated. Please report this as a bug." - ) - } + // Is permission an administrative permission? + case ap: AdministrativePermissionADM => + // Yes. + throw BadRequestException( + s"Permission ${ap.iri} is of type administrative permission. " + + s"Only a default object access permission defined for a resource class can be updated." + ) + case doap: DefaultObjectAccessPermissionADM => + //No. It is a default object access permission. + for { + _ <- updatePermission( + permissionIri = doap.iri, + maybeResourceClass = Some(changePermissionResourceClass.forResourceClass) + ) + updatedPermission <- verifyUpdateOfResourceClass + } yield DefaultObjectAccessPermissionGetResponseADM( + updatedPermission.asInstanceOf[DefaultObjectAccessPermissionADM] + ) + case _ => + throw UpdateNotPerformedException( + s"Permission $permissionIri was not updated. Please report this as a bug." + ) + } } yield response for { // run list info update with an local IRI lock - taskResult <- IriLocker.runWithIriLock( - apiRequestID, - permissionIri, - () => permissionResourceClassChangeTask(permissionIri, changePermissionResourceClass, requestingUser) - ) + taskResult <- + IriLocker.runWithIriLock( + apiRequestID, + permissionIri, + () => permissionResourceClassChangeTask(permissionIri, changePermissionResourceClass, requestingUser) + ) } yield taskResult } @@ -2020,22 +2081,22 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re /*Verify that update was successful*/ _ = updatedPermission match { - case doap: DefaultObjectAccessPermissionADM => - if (doap.forProperty.get != changePermissionPropertyRequest.forProperty) - throw UpdateNotPerformedException( - s"The property of ${doap.iri} was not updated. Please report this as a bug." - ) + case doap: DefaultObjectAccessPermissionADM => + if (doap.forProperty.get != changePermissionPropertyRequest.forProperty) + throw UpdateNotPerformedException( + s"The property of ${doap.iri} was not updated. Please report this as a bug." + ) - if (doap.forGroup.isDefined) - throw UpdateNotPerformedException( - s"The $permissionIri is not correctly updated. Please report this as a bug." - ) + if (doap.forGroup.isDefined) + throw UpdateNotPerformedException( + s"The $permissionIri is not correctly updated. Please report this as a bug." + ) - case _ => - throw UpdateNotPerformedException( - s"Incorrect permission type returned for $permissionIri. Please report this as a bug." - ) - } + case _ => + throw UpdateNotPerformedException( + s"Incorrect permission type returned for $permissionIri. Please report this as a bug." + ) + } } yield updatedPermission /** @@ -2050,38 +2111,38 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re // get permission permission <- permissionGetADM(permissionIri, requestingUser) response <- permission match { - // Is permission an administrative permission? - case ap: AdministrativePermissionADM => - // Yes. - throw BadRequestException( - s"Permission ${ap.iri} is of type administrative permission. " + - s"Only a default object access permission defined for a property can be updated." - ) - case doap: DefaultObjectAccessPermissionADM => - //No. It is a default object access permission. - for { - _ <- updatePermission( - permissionIri = doap.iri, - maybeProperty = Some(changePermissionPropertyRequest.forProperty) - ) - updatedPermission <- verifyUpdateOfProperty - } yield DefaultObjectAccessPermissionGetResponseADM( - updatedPermission.asInstanceOf[DefaultObjectAccessPermissionADM] - ) - case _ => - throw UpdateNotPerformedException( - s"Permission $permissionIri was not updated. Please report this as a bug." - ) - } + // Is permission an administrative permission? + case ap: AdministrativePermissionADM => + // Yes. + throw BadRequestException( + s"Permission ${ap.iri} is of type administrative permission. " + + s"Only a default object access permission defined for a property can be updated." + ) + case doap: DefaultObjectAccessPermissionADM => + //No. It is a default object access permission. + for { + _ <- updatePermission( + permissionIri = doap.iri, + maybeProperty = Some(changePermissionPropertyRequest.forProperty) + ) + updatedPermission <- verifyUpdateOfProperty + } yield DefaultObjectAccessPermissionGetResponseADM( + updatedPermission.asInstanceOf[DefaultObjectAccessPermissionADM] + ) + case _ => + throw UpdateNotPerformedException( + s"Permission $permissionIri was not updated. Please report this as a bug." + ) + } } yield response for { // run permission update with an local IRI lock taskResult <- IriLocker.runWithIriLock( - apiRequestID, - permissionIri, - () => permissionPropertyChangeTask(permissionIri, changePermissionPropertyRequest, requestingUser) - ) + apiRequestID, + permissionIri, + () => permissionPropertyChangeTask(permissionIri, changePermissionPropertyRequest, requestingUser) + ) } yield taskResult } @@ -2107,10 +2168,11 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re _ <- permissionGetADM(permissionIri, requestingUser) // Is permission in use? _ <- isPermissionUsed( - permissionIri = permissionIri, - errorFun = - throw UpdateNotPerformedException(s"Permission $permissionIri cannot be deleted, because it is in use.") - ) + permissionIri = permissionIri, + errorFun = throw UpdateNotPerformedException( + s"Permission $permissionIri cannot be deleted, because it is in use." + ) + ) _ <- deletePermission(permissionIri) @@ -2119,10 +2181,10 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re for { // run list info update with an local IRI lock taskResult <- IriLocker.runWithIriLock( - apiRequestID, - permissionIri, - () => permissionDeleteTask() - ) + apiRequestID, + permissionIri, + () => permissionDeleteTask() + ) } yield taskResult } @@ -2160,82 +2222,88 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re for { // SPARQL query statement to get permission by IRI. sparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .getPermissionByIRI( - permissionIri = permissionIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .getPermissionByIRI( + permissionIri = permissionIri + ) + .toString() + ) permissionQueryResponse <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] /* extract response rows */ permissionQueryResponseRows: Seq[VariableResultsRow] = permissionQueryResponse.results.bindings groupedPermissionsQueryResponse: Map[String, Seq[String]] = permissionQueryResponseRows - .groupBy(_.rowMap("p")) - .map { case (predicate, rows) => - predicate -> rows.map(_.rowMap("o")) - } + .groupBy(_.rowMap("p")) + .map { case (predicate, rows) => + predicate -> rows.map(_.rowMap("o")) + } /* check if we have found something */ _ = if (groupedPermissionsQueryResponse.isEmpty) - throw NotFoundException(s"Permission with given IRI: $permissionIri not found.") + throw NotFoundException(s"Permission with given IRI: $permissionIri not found.") projectIri = groupedPermissionsQueryResponse - .getOrElse( - OntologyConstants.KnoraAdmin.ForProject, - throw InconsistentRepositoryDataException(s"Permission $permissionIri has no project attached") - ) - .head + .getOrElse( + OntologyConstants.KnoraAdmin.ForProject, + throw InconsistentRepositoryDataException(s"Permission $permissionIri has no project attached") + ) + .head // Before returning the permission check that the requesting user has permission to see it _ = verifyUsersRightForOperation( - requestingUser = requestingUser, - projectIri = projectIri, - permissionIri = permissionIri - ) + requestingUser = requestingUser, + projectIri = projectIri, + permissionIri = permissionIri + ) permissionType: Option[String] = groupedPermissionsQueryResponse - .getOrElse(OntologyConstants.Rdf.Type, throw InconsistentRepositoryDataException(s"RDF type is not returned.")) - .headOption + .getOrElse( + OntologyConstants.Rdf.Type, + throw InconsistentRepositoryDataException(s"RDF type is not returned.") + ) + .headOption permission = permissionType match { - case Some(OntologyConstants.KnoraAdmin.DefaultObjectAccessPermission) => - val hasPermissions = PermissionUtilADM.parsePermissionsWithType( - groupedPermissionsQueryResponse.get(OntologyConstants.KnoraBase.HasPermissions).map(_.head), - PermissionType.OAP - ) - val forGroup = groupedPermissionsQueryResponse.get(OntologyConstants.KnoraAdmin.ForGroup).map(_.head) - val forResourceClass = - groupedPermissionsQueryResponse.get(OntologyConstants.KnoraAdmin.ForResourceClass).map(_.head) - val forProperty = groupedPermissionsQueryResponse.get(OntologyConstants.KnoraAdmin.ForProperty).map(_.head) - DefaultObjectAccessPermissionADM( - iri = permissionIri, - forProject = projectIri, - forGroup = forGroup, - forResourceClass = forResourceClass, - forProperty = forProperty, - hasPermissions = hasPermissions - ) - case Some(OntologyConstants.KnoraAdmin.AdministrativePermission) => - val forGroup = groupedPermissionsQueryResponse - .getOrElse( - OntologyConstants.KnoraAdmin.ForGroup, - throw InconsistentRepositoryDataException(s"Permission $permissionIri has no group attached") - ) - .head - val hasPermissions = PermissionUtilADM.parsePermissionsWithType( - groupedPermissionsQueryResponse.get(OntologyConstants.KnoraBase.HasPermissions).map(_.head), - PermissionType.AP - ) - - AdministrativePermissionADM( - iri = permissionIri, - forProject = projectIri, - forGroup = forGroup, - hasPermissions = hasPermissions - ) - case _ => throw BadRequestException(s"Invalid permission type returned, please report this as a bug.") - } + case Some(OntologyConstants.KnoraAdmin.DefaultObjectAccessPermission) => + val hasPermissions = PermissionUtilADM.parsePermissionsWithType( + groupedPermissionsQueryResponse.get(OntologyConstants.KnoraBase.HasPermissions).map(_.head), + PermissionType.OAP + ) + val forGroup = + groupedPermissionsQueryResponse.get(OntologyConstants.KnoraAdmin.ForGroup).map(_.head) + val forResourceClass = + groupedPermissionsQueryResponse.get(OntologyConstants.KnoraAdmin.ForResourceClass).map(_.head) + val forProperty = + groupedPermissionsQueryResponse.get(OntologyConstants.KnoraAdmin.ForProperty).map(_.head) + DefaultObjectAccessPermissionADM( + iri = permissionIri, + forProject = projectIri, + forGroup = forGroup, + forResourceClass = forResourceClass, + forProperty = forProperty, + hasPermissions = hasPermissions + ) + case Some(OntologyConstants.KnoraAdmin.AdministrativePermission) => + val forGroup = groupedPermissionsQueryResponse + .getOrElse( + OntologyConstants.KnoraAdmin.ForGroup, + throw InconsistentRepositoryDataException(s"Permission $permissionIri has no group attached") + ) + .head + val hasPermissions = PermissionUtilADM.parsePermissionsWithType( + groupedPermissionsQueryResponse.get(OntologyConstants.KnoraBase.HasPermissions).map(_.head), + PermissionType.AP + ) + + AdministrativePermissionADM( + iri = permissionIri, + forProject = projectIri, + forGroup = forGroup, + hasPermissions = hasPermissions + ) + case _ => + throw BadRequestException(s"Invalid permission type returned, please report this as a bug.") + } } yield permission /** @@ -2258,17 +2326,17 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re // Generate SPARQL for changing the permission. sparqlChangePermission: String <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .updatePermission( - namedGraphIri = OntologyConstants.NamedGraphs.PermissionNamedGraph, - permissionIri = permissionIri, - maybeGroup = maybeGroup, - maybeHasPermissions = maybeHasPermissions, - maybeResourceClass = maybeResourceClass, - maybeProperty = maybeProperty - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .updatePermission( + namedGraphIri = OntologyConstants.NamedGraphs.PermissionNamedGraph, + permissionIri = permissionIri, + maybeGroup = maybeGroup, + maybeHasPermissions = maybeHasPermissions, + maybeResourceClass = maybeResourceClass, + maybeProperty = maybeProperty + ) + .toString() + ) _ <- (storeManager ? SparqlUpdateRequest(sparqlChangePermission)).mapTo[SparqlUpdateResponse] } yield () @@ -2282,29 +2350,29 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re for { // Generate SPARQL for erasing a permission. sparqlDeletePermission: String <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .deletePermission( - namedGraphIri = OntologyConstants.NamedGraphs.PermissionNamedGraph, - permissionIri = permissionIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .deletePermission( + namedGraphIri = OntologyConstants.NamedGraphs.PermissionNamedGraph, + permissionIri = permissionIri + ) + .toString() + ) // Do the update. _ <- (storeManager ? SparqlUpdateRequest(sparqlDeletePermission)).mapTo[SparqlUpdateResponse] // Verify that the permission was deleted correctly. askString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt.checkIriExists(permissionIri).toString - ) - askResponse <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] + org.knora.webapi.messages.twirl.queries.sparql.admin.txt.checkIriExists(permissionIri).toString + ) + askResponse <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] permissionStillExists: Boolean = askResponse.result _ = if (permissionStillExists) { - throw UpdateNotPerformedException( - s"Permission <$permissionIri> was not erased. Please report this as a possible bug." - ) - } + throw UpdateNotPerformedException( + s"Permission <$permissionIri> was not erased. Please report this as a possible bug." + ) + } } yield () /** @@ -2317,31 +2385,31 @@ class PermissionsResponderADM(responderData: ResponderData) extends Responder(re protected def isPermissionUsed(permissionIri: IRI, errorFun: => Nothing): Future[Unit] = for { isPermissionUsedSparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .isEntityUsed( - entityIri = permissionIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .isEntityUsed( + entityIri = permissionIri + ) + .toString() + ) isPermissionUsedResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(isPermissionUsedSparql)) - .mapTo[SparqlSelectResult] + .mapTo[SparqlSelectResult] _ = if (isPermissionUsedResponse.results.bindings.nonEmpty) { - errorFun - } + errorFun + } } yield () def getProjectOfEntity(entityIri: IRI): Future[IRI] = for { sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .getProjectOfEntity( - entityIri = entityIri - ) - .toString() - ) - response <- (storeManager ? SparqlSelectRequest(sparqlQueryString)).mapTo[SparqlSelectResult] + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .getProjectOfEntity( + entityIri = entityIri + ) + .toString() + ) + response <- (storeManager ? SparqlSelectRequest(sparqlQueryString)).mapTo[SparqlSelectResult] rows: Seq[VariableResultsRow] = response.results.bindings projectIri = if (rows.size == 0) { diff --git a/webapi/src/main/scala/org/knora/webapi/responders/admin/ProjectsResponderADM.scala b/webapi/src/main/scala/org/knora/webapi/responders/admin/ProjectsResponderADM.scala index 0b4b799c9e..0ec381ff1a 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/admin/ProjectsResponderADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/admin/ProjectsResponderADM.scala @@ -53,7 +53,7 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo // 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 ADMIN_DATA_GRAPH = "http://www.knora.org/data/admin" private val PERMISSIONS_DATA_GRAPH = "http://www.knora.org/data/permissions" /** @@ -113,36 +113,40 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo ): Future[Seq[ProjectADM]] = for { sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .getProjects( - maybeIri = None, - maybeShortname = None, - maybeShortcode = None - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .getProjects( + maybeIri = None, + maybeShortname = None, + maybeShortcode = None + ) + .toString() + ) // _ = log.debug(s"getProjectsResponseV1 - query: $sparqlQueryString") projectsResponse <- (storeManager ? SparqlExtendedConstructRequest( - sparql = sparqlQueryString, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + sparql = sparqlQueryString, + featureFactoryConfig = featureFactoryConfig + )).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 + 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) - } + 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 @@ -156,9 +160,9 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo private def getOntologiesForProjects(projectIris: Set[IRI], requestingUser: UserADM): Future[Map[IRI, Seq[IRI]]] = for { ontologyMetadataResponse: ReadOntologyMetadataV2 <- (responderManager ? OntologyMetadataGetByProjectRequestV2( - projectIris = projectIris.map(_.toSmartIri), - requestingUser = requestingUser - )).mapTo[ReadOntologyMetadataV2] + projectIris = projectIris.map(_.toSmartIri), + requestingUser = requestingUser + )).mapTo[ReadOntologyMetadataV2] } yield ontologyMetadataResponse.ontologies.map { ontology => val ontologyIri: IRI = ontology.ontologyIri.toString val projectIri: IRI = ontology.projectIri @@ -188,9 +192,9 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo // ToDo: What permissions should be required, if any? for { projects <- projectsGetADM( - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) result = if (projects.nonEmpty) { @@ -266,15 +270,15 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo // log.debug("getSingleProjectADMRequest - maybeIri: {}, maybeShortname: {}, maybeShortcode: {}", maybeIri, maybeShortname, maybeShortcode) for { maybeProject: Option[ProjectADM] <- getSingleProjectADM( - identifier = identifier, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + identifier = identifier, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) project = maybeProject match { - case Some(p) => p - case None => throw NotFoundException(s"Project '${identifier.value}' not found") - } + case Some(p) => p + case None => throw NotFoundException(s"Project '${identifier.value}' not found") + } } yield ProjectGetResponseADM( project = project ) @@ -298,10 +302,10 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo /* Get project and verify permissions. */ project <- getSingleProjectADM( - identifier = identifier, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + identifier = identifier, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) _ = if (project.isEmpty) { @@ -317,20 +321,20 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo } sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .getProjectMembers( - maybeIri = identifier.toIriOption, - maybeShortname = identifier.toShortnameOption, - maybeShortcode = identifier.toShortcodeOption - ) - .toString() - ) + 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 <- (storeManager ? SparqlExtendedConstructRequest( - sparql = sparqlQueryString, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + sparql = sparqlQueryString, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse] statements = projectMembersResponse.statements.toList @@ -345,15 +349,15 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo } maybeUserFutures: Seq[Future[Option[UserADM]]] = userIris.map { userIri => - (responderManager ? UserGetADM( - identifier = UserIdentifierADM(maybeIri = Some(userIri)), - userInformationTypeADM = UserInformationTypeADM.Restricted, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - )).mapTo[Option[UserADM]] - } + (responderManager ? UserGetADM( + identifier = UserIdentifierADM(maybeIri = Some(userIri)), + userInformationTypeADM = UserInformationTypeADM.Restricted, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + )).mapTo[Option[UserADM]] + } maybeUsers: Seq[Option[UserADM]] <- Future.sequence(maybeUserFutures) - users: Seq[UserADM] = maybeUsers.flatten + users: Seq[UserADM] = maybeUsers.flatten // _ = log.debug(s"projectMembersGetRequestADM - users: {}", users) @@ -377,10 +381,10 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo for { /* Get project and verify permissions. */ project <- getSingleProjectADM( - identifier = identifier, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + identifier = identifier, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) _ = if (project.isEmpty) { @@ -392,20 +396,20 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo } sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .getProjectAdminMembers( - maybeIri = identifier.toIriOption, - maybeShortname = identifier.toShortnameOption, - maybeShortcode = identifier.toShortcodeOption - ) - .toString() - ) + 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 <- (storeManager ? SparqlExtendedConstructRequest( - sparql = sparqlQueryString, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + sparql = sparqlQueryString, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse] //_ = log.debug(s"projectAdminMembersByIRIGetRequestV1 - result: ${MessageUtil.toSource(projectMembersResponse)}") statements = projectAdminMembersResponse.statements.toList @@ -419,15 +423,15 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo } maybeUserFutures: Seq[Future[Option[UserADM]]] = userIris.map { userIri => - (responderManager ? UserGetADM( - identifier = UserIdentifierADM(maybeIri = Some(userIri)), - userInformationTypeADM = UserInformationTypeADM.Restricted, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - )).mapTo[Option[UserADM]] - } + (responderManager ? UserGetADM( + identifier = UserIdentifierADM(maybeIri = Some(userIri)), + userInformationTypeADM = UserInformationTypeADM.Restricted, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + )).mapTo[Option[UserADM]] + } maybeUsers: Seq[Option[UserADM]] <- Future.sequence(maybeUserFutures) - users: Seq[UserADM] = maybeUsers.flatten + users: Seq[UserADM] = maybeUsers.flatten //_ = log.debug(s"projectMembersGetRequestADM - users: $users") @@ -446,9 +450,9 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo ): Future[ProjectsKeywordsGetResponseADM] = for { projects <- projectsGetADM( - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) keywords: Seq[String] = projects.flatMap(_.keywords).distinct.sorted @@ -469,15 +473,15 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo ): Future[ProjectKeywordsGetResponseADM] = for { maybeProject <- getSingleProjectADM( - identifier = ProjectIdentifierADM(maybeIri = Some(projectIri)), - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + identifier = ProjectIdentifierADM(maybeIri = Some(projectIri)), + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) keywords: Seq[String] = maybeProject match { - case Some(p) => p.keywords - case None => throw NotFoundException(s"Project '$projectIri' not found.") - } + case Some(p) => p.keywords + case None => throw NotFoundException(s"Project '$projectIri' not found.") + } } yield ProjectKeywordsGetResponseADM(keywords = keywords) @@ -535,7 +539,7 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo * @param resultFile the output file. */ def combineGraphs(namedGraphTrigFiles: Seq[NamedGraphTrigFile], resultFile: Path): Unit = { - val rdfFormatUtil: RdfFormatUtil = RdfFeatureFactory.getRdfFormatUtil(featureFactoryConfig) + val rdfFormatUtil: RdfFormatUtil = RdfFeatureFactory.getRdfFormatUtil(featureFactoryConfig) var maybeBufferedFileOutputStream: Option[BufferedOutputStream] = None val trigFileTry: Try[Unit] = Try { @@ -581,46 +585,45 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo for { // Get the project info. maybeProject: Option[ProjectADM] <- getSingleProjectADM( - identifier = projectIdentifier, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + identifier = projectIdentifier, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) project: ProjectADM = maybeProject.getOrElse( - throw NotFoundException(s"Project '${projectIdentifier.value}' not found.") - ) + 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" - ) - } + 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) + _ = 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) - ) + projectSpecificNamedGraphTrigFiles: Seq[NamedGraphTrigFile] = + graphsToDownload.map(graphIri => NamedGraphTrigFile(graphIri = graphIri, tempDir = tempDir)) projectSpecificNamedGraphTrigFileWriteFutures: Seq[Future[FileWrittenResponse]] = projectSpecificNamedGraphTrigFiles.map { trigFile => for { fileWrittenResponse: FileWrittenResponse <- ( - storeManager ? - NamedGraphFileRequest( - graphIri = trigFile.graphIri, - outputFile = trigFile.dataFile, - outputFormat = TriG, - featureFactoryConfig = featureFactoryConfig - ) - ).mapTo[FileWrittenResponse] + storeManager ? + NamedGraphFileRequest( + graphIri = trigFile.graphIri, + outputFile = trigFile.dataFile, + outputFormat = TriG, + featureFactoryConfig = featureFactoryConfig + ) + ).mapTo[FileWrittenResponse] } yield fileWrittenResponse } @@ -631,43 +634,43 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo adminDataNamedGraphTrigFile = NamedGraphTrigFile(graphIri = ADMIN_DATA_GRAPH, tempDir = tempDir) adminDataSparql: String = org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .getProjectAdminData( - projectIri = project.id - ) - .toString() + .getProjectAdminData( + projectIri = project.id + ) + .toString() _: FileWrittenResponse <- (storeManager ? SparqlConstructFileRequest( - sparql = adminDataSparql, - graphIri = adminDataNamedGraphTrigFile.graphIri, - outputFile = adminDataNamedGraphTrigFile.dataFile, - outputFormat = TriG, - featureFactoryConfig = featureFactoryConfig - )).mapTo[FileWrittenResponse] + sparql = adminDataSparql, + graphIri = adminDataNamedGraphTrigFile.graphIri, + outputFile = adminDataNamedGraphTrigFile.dataFile, + outputFormat = TriG, + featureFactoryConfig = featureFactoryConfig + )).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() + .getProjectPermissions( + projectIri = project.id + ) + .toString() _: FileWrittenResponse <- (storeManager ? SparqlConstructFileRequest( - sparql = permissionDataSparql, - graphIri = permissionDataNamedGraphTrigFile.graphIri, - outputFile = permissionDataNamedGraphTrigFile.dataFile, - outputFormat = TriG, - featureFactoryConfig = featureFactoryConfig - )).mapTo[FileWrittenResponse] + sparql = permissionDataSparql, + graphIri = permissionDataNamedGraphTrigFile.graphIri, + outputFile = permissionDataNamedGraphTrigFile.dataFile, + outputFormat = TriG, + featureFactoryConfig = featureFactoryConfig + )).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) + _ = combineGraphs(namedGraphTrigFiles = namedGraphTrigFiles, resultFile = resultFile) } yield ProjectDataGetResponseADM(resultFile) } @@ -688,19 +691,19 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo // 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() - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .getProjects( + maybeIri = identifier.toIriOption, + maybeShortname = identifier.toShortnameOption, + maybeShortcode = identifier.toShortcodeOption + ) + .toString() + ) projectResponse <- (storeManager ? SparqlExtendedConstructRequest( - sparql = sparqlQuery, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + sparql = sparqlQuery, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse] restrictedViewSettings = if (projectResponse.statements.nonEmpty) { @@ -736,22 +739,24 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo requestingUser: UserADM ): Future[ProjectRestrictedViewSettingsGetResponseADM] = { - val maybeIri = identifier.toIriOption + val maybeIri = identifier.toIriOption val maybeShortname = identifier.toShortnameOption val maybeShortcode = identifier.toShortcodeOption for { maybeSettings: Option[ProjectRestrictedViewSettingsADM] <- projectRestrictedViewSettingsGetADM( - identifier = identifier, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + identifier = identifier, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) settings = maybeSettings match { - case Some(s) => s - case None => - throw NotFoundException(s"Project '${Seq(maybeIri, maybeShortname, maybeShortcode).flatten.head}' not found.") - } + case Some(s) => s + case None => + throw NotFoundException( + s"Project '${Seq(maybeIri, maybeShortname, maybeShortcode).flatten.head}' not found." + ) + } } yield ProjectRestrictedViewSettingsGetResponseADM(settings) @@ -789,42 +794,42 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo for { _ <- Future( - // check if necessary information is present - if (projectIri.isEmpty) throw BadRequestException("Project IRI cannot be empty") - ) + // 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.") - } + // 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 - ) + longname = changeProjectRequest.longname, + description = changeProjectRequest.description, + keywords = changeProjectRequest.keywords, + logo = changeProjectRequest.logo, + status = changeProjectRequest.status, + selfjoin = changeProjectRequest.selfjoin + ) result <- updateProjectADM( - projectIri = projectIri, - projectUpdatePayload = projectUpdatePayload, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + projectIri = projectIri, + projectUpdatePayload = projectUpdatePayload, + featureFactoryConfig = featureFactoryConfig, + 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) - ) + apiRequestID, + projectIri, + () => changeProjectTask(projectIri, changeProjectRequest, requestingUser) + ) } yield taskResult } @@ -863,106 +868,112 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo for { maybeCurrentProject: Option[ProjectADM] <- getSingleProjectADM( - identifier = ProjectIdentifierADM(maybeIri = Some(projectIri)), - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser, - skipCache = true - ) + identifier = ProjectIdentifierADM(maybeIri = Some(projectIri)), + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser, + skipCache = true + ) _ = if (maybeCurrentProject.isEmpty) { - throw NotFoundException(s"Project '$projectIri' not found. Aborting update request.") - } + throw NotFoundException(s"Project '$projectIri' not found. Aborting update request.") + } // we are changing the project, so lets get rid of the cached copy _ = storeManager ? 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 - ) + 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) _ <- (storeManager ? SparqlUpdateRequest(updateProjectSparqlString)) - .mapTo[SparqlUpdateResponse] + .mapTo[SparqlUpdateResponse] /* Verify that the project was updated. */ maybeUpdatedProject <- getSingleProjectADM( - identifier = ProjectIdentifierADM(maybeIri = Some(projectIri)), - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser, - skipCache = true - ) - - updatedProject: ProjectADM = maybeUpdatedProject.getOrElse( - throw UpdateNotPerformedException("Project was not updated. Please report this as a possible bug.") - ) + identifier = ProjectIdentifierADM(maybeIri = Some(projectIri)), + featureFactoryConfig = featureFactoryConfig, + 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 - ) + "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." - ) - } + 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." - ) - } + 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." - ) - } + 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." - ) - } + 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.") - } + 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 (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." - ) - } + 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) @@ -1000,60 +1011,60 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo for { // Give the admins of the new project rights for any operation in project level, and rights to create resources. _ <- (responderManager ? AdministrativePermissionCreateRequestADM( - createRequest = CreateAdministrativePermissionAPIRequestADM( - forProject = projectIri, - forGroup = OntologyConstants.KnoraAdmin.ProjectAdmin, - hasPermissions = - Set(PermissionADM.ProjectAdminAllPermission, PermissionADM.ProjectResourceCreateAllPermission) - ).prepareHasPermissions, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser, - apiRequestID = UUID.randomUUID() - )).mapTo[AdministrativePermissionCreateResponseADM] + createRequest = CreateAdministrativePermissionAPIRequestADM( + forProject = projectIri, + forGroup = OntologyConstants.KnoraAdmin.ProjectAdmin, + hasPermissions = + Set(PermissionADM.ProjectAdminAllPermission, PermissionADM.ProjectResourceCreateAllPermission) + ).prepareHasPermissions, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser, + apiRequestID = UUID.randomUUID() + )).mapTo[AdministrativePermissionCreateResponseADM] // Give the members of the new project rights to create resources. _ <- (responderManager ? AdministrativePermissionCreateRequestADM( - createRequest = CreateAdministrativePermissionAPIRequestADM( - forProject = projectIri, - forGroup = OntologyConstants.KnoraAdmin.ProjectMember, - hasPermissions = Set(PermissionADM.ProjectResourceCreateAllPermission) - ).prepareHasPermissions, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser, - apiRequestID = UUID.randomUUID() - )).mapTo[AdministrativePermissionCreateResponseADM] + createRequest = CreateAdministrativePermissionAPIRequestADM( + forProject = projectIri, + forGroup = OntologyConstants.KnoraAdmin.ProjectMember, + hasPermissions = Set(PermissionADM.ProjectResourceCreateAllPermission) + ).prepareHasPermissions, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser, + apiRequestID = UUID.randomUUID() + )).mapTo[AdministrativePermissionCreateResponseADM] // Give the admins of the new project rights to change rights, modify, delete, view, // and restricted view of all resources and values that belong to the project. _ <- (responderManager ? DefaultObjectAccessPermissionCreateRequestADM( - createRequest = CreateDefaultObjectAccessPermissionAPIRequestADM( - forProject = projectIri, - forGroup = Some(OntologyConstants.KnoraAdmin.ProjectAdmin), - hasPermissions = Set( - PermissionADM.changeRightsPermission(OntologyConstants.KnoraAdmin.ProjectAdmin), - PermissionADM.modifyPermission(OntologyConstants.KnoraAdmin.ProjectMember) - ) - ).prepareHasPermissions, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser, - apiRequestID = UUID.randomUUID() - )).mapTo[DefaultObjectAccessPermissionCreateResponseADM] + createRequest = CreateDefaultObjectAccessPermissionAPIRequestADM( + forProject = projectIri, + forGroup = Some(OntologyConstants.KnoraAdmin.ProjectAdmin), + hasPermissions = Set( + PermissionADM.changeRightsPermission(OntologyConstants.KnoraAdmin.ProjectAdmin), + PermissionADM.modifyPermission(OntologyConstants.KnoraAdmin.ProjectMember) + ) + ).prepareHasPermissions, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser, + apiRequestID = UUID.randomUUID() + )).mapTo[DefaultObjectAccessPermissionCreateResponseADM] // Give the members of the new project rights to modify, view, and restricted view of all resources and values // that belong to the project. _ <- (responderManager ? DefaultObjectAccessPermissionCreateRequestADM( - createRequest = CreateDefaultObjectAccessPermissionAPIRequestADM( - forProject = projectIri, - forGroup = Some(OntologyConstants.KnoraAdmin.ProjectMember), - hasPermissions = Set( - PermissionADM.changeRightsPermission(OntologyConstants.KnoraAdmin.ProjectAdmin), - PermissionADM.modifyPermission(OntologyConstants.KnoraAdmin.ProjectMember) - ) - ).prepareHasPermissions, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser, - apiRequestID = UUID.randomUUID() - )).mapTo[DefaultObjectAccessPermissionCreateResponseADM] + createRequest = CreateDefaultObjectAccessPermissionAPIRequestADM( + forProject = projectIri, + forGroup = Some(OntologyConstants.KnoraAdmin.ProjectMember), + hasPermissions = Set( + PermissionADM.changeRightsPermission(OntologyConstants.KnoraAdmin.ProjectAdmin), + PermissionADM.modifyPermission(OntologyConstants.KnoraAdmin.ProjectMember) + ) + ).prepareHasPermissions, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser, + apiRequestID = UUID.randomUUID() + )).mapTo[DefaultObjectAccessPermissionCreateResponseADM] } yield () def projectCreateTask( @@ -1064,80 +1075,80 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo // check if the supplied shortname is unique shortnameExists <- projectByShortnameExists(createProjectRequest.shortname.value) _ = if (shortnameExists) { - throw DuplicateValueException( - s"Project with the shortname: '${createProjectRequest.shortname.value}' already exists" - ) - } + throw DuplicateValueException( + s"Project with the shortname: '${createProjectRequest.shortname.value}' already exists" + ) + } // check if the optionally supplied shortcode is valid and unique shortcodeExists <- projectByShortcodeExists(createProjectRequest.shortcode.value) _ = if (shortcodeExists) { - throw DuplicateValueException( - s"Project with the shortcode: '${createProjectRequest.shortcode.value}' already exists" - ) - } + throw DuplicateValueException( + s"Project with the shortcode: '${createProjectRequest.shortcode.value}' already exists" + ) + } // check if the requesting user is allowed to create project _ = if (!requestingUser.permissions.isSystemAdmin) { - // not a system admin - throw ForbiddenException("A new project can only be created by a system admin.") - } + // not a system admin + throw ForbiddenException("A new project can only be created by a system admin.") + } // check the custom IRI; if not given, create an unused IRI customProjectIri: Option[SmartIri] = createProjectRequest.id.map(_.value).map(_.toSmartIri) newProjectIRI: IRI <- checkOrCreateEntityIri( - customProjectIri, - stringFormatter.makeRandomProjectIri(createProjectRequest.shortcode.value) - ) + customProjectIri, + stringFormatter.makeRandomProjectIri(createProjectRequest.shortcode.value) + ) maybeLongname = createProjectRequest.longname match { - case Some(value) => Some(value.value) - case None => None - } + case Some(value) => Some(value.value) + case None => None + } maybeLogo = createProjectRequest.logo match { - case Some(value) => Some(value.value) - case None => None - } + case Some(value) => Some(value.value) + case None => None + } createNewProjectSparqlString = org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .createNewProject( - adminNamedGraphIri = OntologyConstants.NamedGraphs.AdminNamedGraph, - projectIri = newProjectIRI, - projectClassIri = OntologyConstants.KnoraAdmin.KnoraProject, - shortname = createProjectRequest.shortname.value, - shortcode = createProjectRequest.shortcode.value, - maybeLongname = maybeLongname, - maybeDescriptions = if (createProjectRequest.description.value.nonEmpty) { - Some(createProjectRequest.description.value) - } else None, - maybeKeywords = if (createProjectRequest.keywords.value.nonEmpty) { - Some(createProjectRequest.keywords.value) - } else None, - maybeLogo = maybeLogo, - status = createProjectRequest.status.value, - hasSelfJoinEnabled = createProjectRequest.selfjoin.value - ) - .toString + .createNewProject( + adminNamedGraphIri = OntologyConstants.NamedGraphs.AdminNamedGraph, + projectIri = newProjectIRI, + projectClassIri = OntologyConstants.KnoraAdmin.KnoraProject, + shortname = createProjectRequest.shortname.value, + shortcode = createProjectRequest.shortcode.value, + maybeLongname = maybeLongname, + maybeDescriptions = if (createProjectRequest.description.value.nonEmpty) { + Some(createProjectRequest.description.value) + } else None, + maybeKeywords = if (createProjectRequest.keywords.value.nonEmpty) { + Some(createProjectRequest.keywords.value) + } else None, + maybeLogo = maybeLogo, + status = createProjectRequest.status.value, + hasSelfJoinEnabled = createProjectRequest.selfjoin.value + ) + .toString _ <- (storeManager ? SparqlUpdateRequest(createNewProjectSparqlString)) - .mapTo[SparqlUpdateResponse] + .mapTo[SparqlUpdateResponse] // try to retrieve newly created project (will also add to cache) maybeNewProjectADM <- getSingleProjectADM( - identifier = ProjectIdentifierADM(maybeIri = Some(newProjectIRI)), - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser, - skipCache = true - ) + identifier = ProjectIdentifierADM(maybeIri = Some(newProjectIRI)), + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser, + skipCache = true + ) // check to see if we could retrieve the new project newProjectADM = maybeNewProjectADM.getOrElse( - throw UpdateNotPerformedException( - s"Project $newProjectIRI was not created. Please report this as a possible bug." - ) - ) + throw UpdateNotPerformedException( + s"Project $newProjectIRI was not created. Please report this as a possible bug." + ) + ) // create permissions for admins and members of the new group _ <- createPermissionsForAdminsAndMembersOfNewProject(newProjectIRI, newProjectADM.shortcode) @@ -1146,10 +1157,10 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo for { // run user creation with an global IRI lock taskResult <- IriLocker.runWithIriLock( - apiRequestID, - PROJECTS_GLOBAL_LOCK_IRI, - () => projectCreateTask(createProjectRequest, requestingUser) - ) + apiRequestID, + PROJECTS_GLOBAL_LOCK_IRI, + () => projectCreateTask(createProjectRequest, requestingUser) + ) } yield taskResult } @@ -1207,19 +1218,19 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo for { sparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .getProjects( - maybeIri = identifier.toIriOption, - maybeShortname = identifier.toShortnameOption, - maybeShortcode = identifier.toShortcodeOption - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .getProjects( + maybeIri = identifier.toIriOption, + maybeShortname = identifier.toShortnameOption, + maybeShortcode = identifier.toShortcodeOption + ) + .toString() + ) projectResponse <- (storeManager ? SparqlExtendedConstructRequest( - sparql = sparqlQuery, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + sparql = sparqlQuery, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse] projectIris = projectResponse.statements.keySet.map(_.toString) @@ -1256,7 +1267,7 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo // log.debug("statements2ProjectADM - statements: {}", statements) - val projectIri: IRI = statements._1.toString + val projectIri: IRI = statements._1.toString val propsMap: Map[SmartIri, Seq[LiteralV2]] = statements._2 ProjectADM( @@ -1345,14 +1356,14 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo private def projectByIriExists(projectIri: IRI): Future[Boolean] = for { askString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .checkProjectExistsByIri(projectIri = projectIri) - .toString - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .checkProjectExistsByIri(projectIri = projectIri) + .toString + ) //_ = log.debug("projectExists - query: {}", askString) checkProjectExistsResponse <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] - result = checkProjectExistsResponse.result + result = checkProjectExistsResponse.result } yield result @@ -1365,14 +1376,14 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo private def projectByShortnameExists(shortname: String): Future[Boolean] = for { askString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .checkProjectExistsByShortname(shortname = shortname) - .toString - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .checkProjectExistsByShortname(shortname = shortname) + .toString + ) //_ = log.debug("projectExists - query: {}", askString) checkProjectExistsResponse <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] - result = checkProjectExistsResponse.result + result = checkProjectExistsResponse.result } yield result @@ -1385,14 +1396,14 @@ class ProjectsResponderADM(responderData: ResponderData) extends Responder(respo private def projectByShortcodeExists(shortcode: String): Future[Boolean] = for { askString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .checkProjectExistsByShortcode(shortcode = shortcode) - .toString - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .checkProjectExistsByShortcode(shortcode = shortcode) + .toString + ) //_ = log.debug("projectExists - query: {}", askString) checkProjectExistsResponse <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] - result = checkProjectExistsResponse.result + result = checkProjectExistsResponse.result } yield result diff --git a/webapi/src/main/scala/org/knora/webapi/responders/admin/SipiResponderADM.scala b/webapi/src/main/scala/org/knora/webapi/responders/admin/SipiResponderADM.scala index c66f446263..1d0a037689 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/admin/SipiResponderADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/admin/SipiResponderADM.scala @@ -63,69 +63,73 @@ class SipiResponderADM(responderData: ResponderData) extends Responder(responder for { sparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .getFileValue( - filename = request.filename - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .getFileValue( + filename = request.filename + ) + .toString() + ) queryResponse: SparqlExtendedConstructResponse <- (storeManager ? SparqlExtendedConstructRequest( - sparql = sparqlQuery, - featureFactoryConfig = request.featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + sparql = sparqlQuery, + featureFactoryConfig = request.featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse] _ = if (queryResponse.statements.isEmpty) - throw NotFoundException(s"No file value was found for filename ${request.filename}") + throw NotFoundException(s"No file value was found for filename ${request.filename}") _ = if (queryResponse.statements.size > 1) - throw InconsistentRepositoryDataException(s"Filename ${request.filename} is used in more than one file value") + throw InconsistentRepositoryDataException( + s"Filename ${request.filename} is used in more than one file value" + ) fileValueIriSubject: IriSubjectV2 = queryResponse.statements.keys.head match { - case iriSubject: IriSubjectV2 => iriSubject - case _ => - throw InconsistentRepositoryDataException( - s"The subject of the file value with filename ${request.filename} is not an IRI" - ) - } + case iriSubject: IriSubjectV2 => iriSubject + case _ => + throw InconsistentRepositoryDataException( + s"The subject of the file value with filename ${request.filename} is not an IRI" + ) + } assertions: Seq[(String, String)] = queryResponse.statements(fileValueIriSubject).toSeq.flatMap { - case (predicate: SmartIri, values: Seq[LiteralV2]) => - values.map { value => - predicate.toString -> value.toString - } - } + case (predicate: SmartIri, values: Seq[LiteralV2]) => + values.map { value => + predicate.toString -> value.toString + } + } maybeEntityPermission: Option[EntityPermission] = PermissionUtilADM.getUserPermissionFromAssertionsADM( - entityIri = fileValueIriSubject.toString, - assertions = assertions, - requestingUser = request.requestingUser - ) + entityIri = fileValueIriSubject.toString, + assertions = assertions, + requestingUser = request.requestingUser + ) - _ = log.debug( - s"SipiResponderADM - getFileInfoForSipiADM - maybePermissionCode: $maybeEntityPermission, requestingUser: ${request.requestingUser.username}" - ) + _ = + log.debug( + s"SipiResponderADM - getFileInfoForSipiADM - maybePermissionCode: $maybeEntityPermission, requestingUser: ${request.requestingUser.username}" + ) permissionCode: Int = maybeEntityPermission - .map(_.toInt) - .getOrElse(0) // Sipi expects a permission code from 0 to 8 + .map(_.toInt) + .getOrElse(0) // Sipi expects a permission code from 0 to 8 response <- permissionCode match { - case 1 => - for { - maybeRVSettings <- ( - responderManager ? ProjectRestrictedViewSettingsGetADM( - identifier = ProjectIdentifierADM(maybeShortcode = Some(request.projectID)), - featureFactoryConfig = request.featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) - ).mapTo[Option[ProjectRestrictedViewSettingsADM]] - } yield SipiFileInfoGetResponseADM(permissionCode = permissionCode, maybeRVSettings) - - case _ => - FastFuture.successful( - SipiFileInfoGetResponseADM(permissionCode = permissionCode, restrictedViewSettings = None) - ) - } + case 1 => + for { + maybeRVSettings <- ( + responderManager ? ProjectRestrictedViewSettingsGetADM( + identifier = + ProjectIdentifierADM(maybeShortcode = Some(request.projectID)), + featureFactoryConfig = request.featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) + ).mapTo[Option[ProjectRestrictedViewSettingsADM]] + } yield SipiFileInfoGetResponseADM(permissionCode = permissionCode, maybeRVSettings) + + case _ => + FastFuture.successful( + SipiFileInfoGetResponseADM(permissionCode = permissionCode, restrictedViewSettings = None) + ) + } _ = log.info(s"filename ${request.filename}, permission code: $permissionCode") } yield response diff --git a/webapi/src/main/scala/org/knora/webapi/responders/admin/StoresResponderADM.scala b/webapi/src/main/scala/org/knora/webapi/responders/admin/StoresResponderADM.scala index 896f658cbe..28ad2dd78d 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/admin/StoresResponderADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/admin/StoresResponderADM.scala @@ -69,23 +69,23 @@ class StoresResponderADM(responderData: ResponderData) extends Responder(respond for { value: Boolean <- (appActor ? GetAllowReloadOverHTTPState()).mapTo[Boolean] _ = if (!value) { - throw ForbiddenException( - "The ResetTriplestoreContent operation is not allowed. Did you start the server with the right flag?" - ) - } + throw ForbiddenException( + "The ResetTriplestoreContent operation is not allowed. Did you start the server with the right flag?" + ) + } resetResponse <- (storeManager ? ResetRepositoryContent(rdfDataObjects, prependDefaults)) - .mapTo[ResetRepositoryContentACK] + .mapTo[ResetRepositoryContentACK] _ = log.debug(s"resetTriplestoreContent - triplestore reset done - {}", resetResponse.toString) loadOntologiesResponse <- (responderManager ? LoadOntologiesRequestV2( - featureFactoryConfig = featureFactoryConfig, - requestingUser = systemUser - )).mapTo[SuccessResponseV2] + featureFactoryConfig = featureFactoryConfig, + requestingUser = systemUser + )).mapTo[SuccessResponseV2] _ = log.debug(s"resetTriplestoreContent - load ontology done - {}", loadOntologiesResponse.toString) _ <- (storeManager ? CacheServiceFlushDB(systemUser)) - _ = log.debug(s"resetTriplestoreContent - flushing Redis store done.") + _ = log.debug(s"resetTriplestoreContent - flushing Redis store done.") result = ResetTriplestoreContentResponseADM(message = "success") diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v1/CkanResponderV1.scala b/webapi/src/main/scala/org/knora/webapi/responders/v1/CkanResponderV1.scala index 807d582a90..2262cda1bb 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/v1/CkanResponderV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v1/CkanResponderV1.scala @@ -94,29 +94,29 @@ class CkanResponderV1(responderData: ResponderData) extends Responder(responderD for { projects <- selectedProjectsFuture ckanProjects: Seq[Future[CkanProjectV1]] = projects flatMap { - case ("dokubib", projectFullInfo) => - Some( - getDokubibCkanProject( - pinfo = projectFullInfo, - limit = limit, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) - ) - - case ("incunabula", projectFullInfo) => - Some( - getIncunabulaCkanProject( - pinfo = projectFullInfo, - limit = limit, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) - ) - - case _ => None - } - result <- Future.sequence(ckanProjects) + case ("dokubib", projectFullInfo) => + Some( + getDokubibCkanProject( + pinfo = projectFullInfo, + limit = limit, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) + ) + + case ("incunabula", projectFullInfo) => + Some( + getIncunabulaCkanProject( + pinfo = projectFullInfo, + limit = limit, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) + ) + + case _ => None + } + result <- Future.sequence(ckanProjects) response = CkanResponseV1(projects = result) } yield response } @@ -148,7 +148,7 @@ class CkanResponderV1(responderData: ResponderData) extends Responder(responderD - bild 2 */ - val pIri = pinfo.id + val pIri = pinfo.id val resType = "http://www.knora.org/ontology/0804/dokubib#bild" val ckanPInfo = @@ -163,35 +163,35 @@ class CkanResponderV1(responderData: ResponderData) extends Responder(responderD bilder <- getDokubibBilderIRIs(pIri, limit) bilderMitPropsFuture = getResources( - iris = bilder, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + iris = bilder, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) bilderMitProps <- bilderMitPropsFuture dataset = bilderMitProps.map { case (iri, info, props) => - val infoMap = flattenInfo(info) - val propsMap = flattenProps(props) - CkanProjectDatasetV1( - ckan_title = propsMap.getOrElse("Description", ""), - ckan_tags = propsMap.getOrElse("Title", "").split("/").toIndexedSeq.map(_.trim), - files = Vector( - CkanProjectDatasetFileV1( - ckan_title = propsMap.getOrElse("preview_loc_origname", ""), - data_url = "http://localhost:3333/v1/assets/" + URLEncoder.encode(iri, "UTF-8"), - data_mimetype = "", - source_url = "http://salsah.org/resources/" + URLEncoder.encode(iri, "UTF-8"), - source_mimetype = "" - ) - ), - other_props = propsMap - ) - } + val infoMap = flattenInfo(info) + val propsMap = flattenProps(props) + CkanProjectDatasetV1( + ckan_title = propsMap.getOrElse("Description", ""), + ckan_tags = propsMap.getOrElse("Title", "").split("/").toIndexedSeq.map(_.trim), + files = Vector( + CkanProjectDatasetFileV1( + ckan_title = propsMap.getOrElse("preview_loc_origname", ""), + data_url = "http://localhost:3333/v1/assets/" + URLEncoder.encode(iri, "UTF-8"), + data_mimetype = "", + source_url = "http://salsah.org/resources/" + URLEncoder.encode(iri, "UTF-8"), + source_mimetype = "" + ) + ), + other_props = propsMap + ) + } } yield dataset for { datasets <- datasetsFuture - result = CkanProjectV1(project_info = ckanPInfo, project_datasets = Some(datasets)) + result = CkanProjectV1(project_info = ckanPInfo, project_datasets = Some(datasets)) } yield result } @@ -209,19 +209,19 @@ class CkanResponderV1(responderData: ResponderData) extends Responder(responderD for { sparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .ckanDokubib(projectIri, limit) - .toString() - ) - response <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .ckanDokubib(projectIri, limit) + .toString() + ) + response <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] responseRows: Seq[VariableResultsRow] = response.results.bindings bilder: Seq[String] = responseRows.groupBy(_.rowMap("bild")).keys.toVector result = limit match { - case Some(n) if n > 0 => bilder.take(n) - case _ => bilder - } + case Some(n) if n > 0 => bilder.take(n) + case _ => bilder + } } yield result @@ -279,7 +279,7 @@ class CkanResponderV1(responderData: ResponderData) extends Responder(responderD ) bookResourceFuture flatMap { case (bIri, bInfo, bProps) => - val bInfoMap = flattenInfo(bInfo) + val bInfoMap = flattenInfo(bInfo) val bPropsMap = flattenProps(bProps) val files = pageIris map { pageIri => getResource( @@ -287,7 +287,7 @@ class CkanResponderV1(responderData: ResponderData) extends Responder(responderD featureFactoryConfig = featureFactoryConfig, userProfile = userProfile ) map { case (pIri, pInfo, pProps) => - val pInfoMap = flattenInfo(pInfo) + val pInfoMap = flattenInfo(pInfo) val pPropsMap = flattenProps(pProps) CkanProjectDatasetFileV1( ckan_title = pPropsMap.getOrElse("Page identifier", ""), @@ -315,7 +315,7 @@ class CkanResponderV1(responderData: ResponderData) extends Responder(responderD for { bookDatasets <- bookDatasetsFuture - result = CkanProjectV1(project_info = ckanPInfo, project_datasets = Some(bookDatasets)) + result = CkanProjectV1(project_info = ckanPInfo, project_datasets = Some(bookDatasets)) } yield result } @@ -329,27 +329,27 @@ class CkanResponderV1(responderData: ResponderData) extends Responder(responderD private def getIncunabulaBooksWithPagesIRIs(projectIri: IRI, limit: Option[Int]): Future[Map[IRI, Seq[IRI]]] = for { sparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .ckanIncunabula(projectIri, limit) - .toString() - ) - response <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .ckanIncunabula(projectIri, limit) + .toString() + ) + response <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] responseRows: Seq[VariableResultsRow] = response.results.bindings - booksWithPages: Map[String, Seq[String]] = responseRows.groupBy(_.rowMap("book")).map { - case (bookIri: String, rows: Seq[VariableResultsRow]) => + booksWithPages: Map[String, Seq[String]] = + responseRows.groupBy(_.rowMap("book")).map { case (bookIri: String, rows: Seq[VariableResultsRow]) => ( bookIri, rows.map { case row => row.rowMap("page") } ) - } + } result = limit match { - case Some(n) if n > 0 => booksWithPages.take(n) - case _ => booksWithPages - } + case Some(n) if n > 0 => booksWithPages.take(n) + case _ => booksWithPages + } } yield result @@ -375,14 +375,14 @@ class CkanResponderV1(responderData: ResponderData) extends Responder(responderD pName <- projectNames projectInfoResponseFuture = (responderManager ? ProjectInfoByShortnameGetRequestV1( - shortname = pName, - featureFactoryConfig = featureFactoryConfig, - userProfileV1 = Some(userProfile.asUserProfileV1) - )).mapTo[ProjectInfoResponseV1] + shortname = pName, + featureFactoryConfig = featureFactoryConfig, + userProfileV1 = Some(userProfile.asUserProfileV1) + )).mapTo[ProjectInfoResponseV1] result = projectInfoResponseFuture.map(_.project_info) map { pInfo => - (pName, pInfo) - } + (pName, pInfo) + } } yield result } @@ -403,20 +403,20 @@ class CkanResponderV1(responderData: ResponderData) extends Responder(responderD ): Future[Seq[IRI]] = for { sparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getResourcesByProjectAndType( - projectIri = projectIri, - resType = resType - ) - .toString() - ) - resourcesResponse <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getResourcesByProjectAndType( + projectIri = projectIri, + resType = resType + ) + .toString() + ) + resourcesResponse <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] resourcesResponseRows: Seq[VariableResultsRow] = resourcesResponse.results.bindings - resIri = resourcesResponseRows.groupBy(_.rowMap("s")).keys.toVector + resIri = resourcesResponseRows.groupBy(_.rowMap("s")).keys.toVector result = limit match { - case Some(n) if n > 0 => resIri.take(n) - case _ => resIri - } + case Some(n) if n > 0 => resIri.take(n) + case _ => resIri + } } yield result /** @@ -437,10 +437,10 @@ class CkanResponderV1(responderData: ResponderData) extends Responder(responderD iri <- iris resource = getResource( - iri = iri, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + iri = iri, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) } yield resource } @@ -548,7 +548,7 @@ class CkanResponderV1(responderData: ResponderData) extends Responder(responderD private def listValue2String(list: HierarchicalListValueV1, responderManager: ActorRef): String = { val resultFuture = responderManager ? NodePathGetRequestV1(list.hierarchicalListIri, systemUser) - val nodePath = Await.result(resultFuture, Duration(3, SECONDS)).asInstanceOf[NodePathGetResponseV1] + val nodePath = Await.result(resultFuture, Duration(3, SECONDS)).asInstanceOf[NodePathGetResponseV1] val labels = nodePath.nodelist map { case element => element.label.getOrElse("") diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v1/ListsResponderV1.scala b/webapi/src/main/scala/org/knora/webapi/responders/v1/ListsResponderV1.scala index 513822061c..da0c63e19d 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/v1/ListsResponderV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v1/ListsResponderV1.scala @@ -54,15 +54,15 @@ class ListsResponderV1(responderData: ResponderData) extends Responder(responder maybeChildren <- listGetV1(rootNodeIri, userProfile) children = maybeChildren match { - case children: Seq[ListNodeV1] if children.nonEmpty => children - case _ => throw NotFoundException(s"List not found: $rootNodeIri") - } + case children: Seq[ListNodeV1] if children.nonEmpty => children + case _ => throw NotFoundException(s"List not found: $rootNodeIri") + } // consider routing path here ("hlists" | "selections") and return the correct case class result = pathType match { - case PathType.HList => HListGetResponseV1(hlist = children) - case PathType.Selection => SelectionGetResponseV1(selection = children) - } + case PathType.HList => HListGetResponseV1(hlist = children) + case PathType.Selection => SelectionGetResponseV1(selection = children) + } } yield result @@ -142,20 +142,19 @@ class ListsResponderV1(responderData: ResponderData) extends Responder(responder for { listQuery <- Future { - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getList( - rootNodeIri = rootNodeIri, - preferredLanguage = userProfile.userData.lang, - fallbackLanguage = settings.fallbackLanguage - ) - .toString() - } + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getList( + rootNodeIri = rootNodeIri, + preferredLanguage = userProfile.userData.lang, + fallbackLanguage = settings.fallbackLanguage + ) + .toString() + } listQueryResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(listQuery)).mapTo[SparqlSelectResult] // Group the results to map each node to the SPARQL query results representing its children. - groupedByNodeIri: Map[IRI, Seq[VariableResultsRow]] = listQueryResponse.results.bindings.groupBy(row => - row.rowMap("node") - ) + groupedByNodeIri: Map[IRI, Seq[VariableResultsRow]] = + listQueryResponse.results.bindings.groupBy(row => row.rowMap("node")) rootNodeChildren = groupedByNodeIri.getOrElse(rootNodeIri, Seq.empty[VariableResultsRow]) @@ -225,16 +224,16 @@ class ListsResponderV1(responderData: ResponderData) extends Responder(responder for { nodePathQuery <- Future { - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getNodePath( - queryNodeIri = queryNodeIri, - preferredLanguage = userProfile.userData.lang, - fallbackLanguage = settings.fallbackLanguage - ) - .toString() - } + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getNodePath( + queryNodeIri = queryNodeIri, + preferredLanguage = userProfile.userData.lang, + fallbackLanguage = settings.fallbackLanguage + ) + .toString() + } nodePathResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(nodePathQuery)) - .mapTo[SparqlSelectResult] + .mapTo[SparqlSelectResult] /* @@ -252,16 +251,16 @@ class ListsResponderV1(responderData: ResponderData) extends Responder(responder // 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 - }.toMap + row.rowMap("node") -> row.rowMap + }.toMap // 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 - } - } + row.rowMap.get("child") match { + case Some(child) => acc + (child -> row.rowMap("node")) + case None => acc + } + } } yield NodePathGetResponseV1( nodelist = makePath(queryNodeIri, nodeMap, parentMap, Nil) ) diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v1/OntologyResponderV1.scala b/webapi/src/main/scala/org/knora/webapi/responders/v1/OntologyResponderV1.scala index 52d7668102..0ed7b10e16 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/v1/OntologyResponderV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v1/OntologyResponderV1.scala @@ -80,9 +80,9 @@ class OntologyResponderV1(responderData: ResponderData) extends Responder(respon for { // forward the request to the v2 ontologies responder _: SuccessResponseV2 <- (responderManager ? LoadOntologiesRequestV2( - featureFactoryConfig = featureFactoryConfig, - requestingUser = userProfile - )).mapTo[SuccessResponseV2] + featureFactoryConfig = featureFactoryConfig, + requestingUser = userProfile + )).mapTo[SuccessResponseV2] } yield LoadOntologiesResponse() /** @@ -100,10 +100,10 @@ class OntologyResponderV1(responderData: ResponderData) extends Responder(respon ): Future[EntityInfoGetResponseV1] = for { response: EntityInfoGetResponseV2 <- (responderManager ? EntityInfoGetRequestV2( - resourceClassIris.map(_.toSmartIri), - propertyIris.map(_.toSmartIri), - userProfile - )).mapTo[EntityInfoGetResponseV2] + resourceClassIris.map(_.toSmartIri), + propertyIris.map(_.toSmartIri), + userProfile + )).mapTo[EntityInfoGetResponseV2] } yield EntityInfoGetResponseV1( resourceClassInfoMap = ConvertOntologyClassV2ToV1.classInfoMapV2ToV1(response.classInfoMap), propertyInfoMap = ConvertOntologyClassV2ToV1.propertyInfoMapV2ToV1(response.propertyInfoMap) @@ -124,10 +124,10 @@ class OntologyResponderV1(responderData: ResponderData) extends Responder(respon ): Future[StandoffEntityInfoGetResponseV1] = for { response: StandoffEntityInfoGetResponseV2 <- (responderManager ? StandoffEntityInfoGetRequestV2( - standoffClassIris.map(_.toSmartIri), - standoffPropertyIris.map(_.toSmartIri), - userProfile - )).mapTo[StandoffEntityInfoGetResponseV2] + standoffClassIris.map(_.toSmartIri), + standoffPropertyIris.map(_.toSmartIri), + userProfile + )).mapTo[StandoffEntityInfoGetResponseV2] } yield StandoffEntityInfoGetResponseV1( standoffClassInfoMap = ConvertOntologyClassV2ToV1.classInfoMapV2ToV1(response.standoffClassInfoMap), @@ -145,8 +145,8 @@ class OntologyResponderV1(responderData: ResponderData) extends Responder(respon ): Future[StandoffClassesWithDataTypeGetResponseV1] = for { response: StandoffClassesWithDataTypeGetResponseV2 <- (responderManager ? StandoffClassesWithDataTypeGetRequestV2( - userProfile - )).mapTo[StandoffClassesWithDataTypeGetResponseV2] + userProfile + )).mapTo[StandoffClassesWithDataTypeGetResponseV2] } yield StandoffClassesWithDataTypeGetResponseV1( standoffClassInfoMap = ConvertOntologyClassV2ToV1.classInfoMapV2ToV1(response.standoffClassInfoMap) ) @@ -160,8 +160,8 @@ class OntologyResponderV1(responderData: ResponderData) extends Responder(respon private def getAllStandoffPropertyEntities(userProfile: UserADM): Future[StandoffAllPropertiesGetResponseV1] = for { response: StandoffAllPropertyEntitiesGetResponseV2 <- (responderManager ? StandoffAllPropertyEntitiesGetRequestV2( - userProfile - )).mapTo[StandoffAllPropertyEntitiesGetResponseV2] + userProfile + )).mapTo[StandoffAllPropertyEntitiesGetResponseV2] } yield StandoffAllPropertiesGetResponseV1( standoffAllPropertiesInfoMap = ConvertOntologyClassV2ToV1.propertyInfoMapV2ToV1(response.standoffAllPropertiesEntityInfoMap) @@ -183,121 +183,156 @@ class OntologyResponderV1(responderData: ResponderData) extends Responder(respon for { // Get all information about the resource type, including its property cardinalities. resourceClassInfoResponse: EntityInfoGetResponseV1 <- getEntityInfoResponseV1( - resourceClassIris = Set(resourceTypeIri), - userProfile = userProfile - ) - resourceClassInfo: ClassInfoV1 = resourceClassInfoResponse.resourceClassInfoMap - .getOrElse(resourceTypeIri, throw NotFoundException(s"Resource class $resourceTypeIri not found")) + resourceClassIris = Set(resourceTypeIri), + userProfile = userProfile + ) + resourceClassInfo: ClassInfoV1 = + resourceClassInfoResponse.resourceClassInfoMap + .getOrElse(resourceTypeIri, throw NotFoundException(s"Resource class $resourceTypeIri not found")) // Get all information about those properties. propertyInfo: EntityInfoGetResponseV1 <- getEntityInfoResponseV1( - propertyIris = resourceClassInfo.knoraResourceCardinalities.keySet, - userProfile = userProfile - ) + propertyIris = resourceClassInfo.knoraResourceCardinalities.keySet, + userProfile = userProfile + ) // Build the property definitions. propertyDefinitions: Vector[PropertyDefinitionV1] = resourceClassInfo.knoraResourceCardinalities.filterNot { - // filter out the properties that point to LinkValue objects - case (propertyIri, _) => - resourceClassInfo.linkValueProperties( - propertyIri - ) || propertyIri == OntologyConstants.KnoraBase.HasStandoffLinkTo - }.map { case (propertyIri: IRI, cardinalityInfo: KnoraCardinalityInfo) => - propertyInfo.propertyInfoMap.get(propertyIri) match { - case Some(entityInfo: PropertyInfoV1) => - if (entityInfo.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. - - PropertyDefinitionV1( - id = propertyIri, - name = propertyIri, - label = entityInfo.getPredicateObject( - predicateIri = OntologyConstants.Rdfs.Label, - preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) - ), - description = entityInfo.getPredicateObject( - predicateIri = OntologyConstants.Rdfs.Comment, - preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) - ), - vocabulary = entityInfo.ontologyIri, - occurrence = cardinalityInfo.cardinality.toString, - valuetype_id = OntologyConstants.KnoraBase.LinkValue, - attributes = valueUtilV1.makeAttributeString( - entityInfo - .getPredicateStringObjectsWithoutLang(OntologyConstants.SalsahGui.GuiAttribute) + valueUtilV1 - .makeAttributeRestype( - entityInfo - .getPredicateObject(OntologyConstants.KnoraBase.ObjectClassConstraint) - .getOrElse( - throw InconsistentRepositoryDataException( - s"Property $propertyIri has no knora-base:objectClassConstraint" - ) - ) - ) - ), - gui_name = entityInfo - .getPredicateObject(OntologyConstants.SalsahGui.GuiElementProp) - .map(iri => SalsahGuiConversions.iri2SalsahGuiElement(iri)), - guiorder = cardinalityInfo.guiOrder - ) - - } else { - - PropertyDefinitionV1( - id = propertyIri, - name = propertyIri, - label = entityInfo.getPredicateObject( - predicateIri = OntologyConstants.Rdfs.Label, - preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) - ), - description = entityInfo.getPredicateObject( - predicateIri = OntologyConstants.Rdfs.Comment, - preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) - ), - vocabulary = entityInfo.ontologyIri, - occurrence = cardinalityInfo.cardinality.toString, - valuetype_id = entityInfo - .getPredicateObject(OntologyConstants.KnoraBase.ObjectClassConstraint) - .getOrElse( - throw InconsistentRepositoryDataException( - s"Property $propertyIri has no knora-base:objectClassConstraint" - ) - ), - attributes = valueUtilV1.makeAttributeString( - entityInfo.getPredicateStringObjectsWithoutLang(OntologyConstants.SalsahGui.GuiAttribute) - ), - gui_name = entityInfo - .getPredicateObject(OntologyConstants.SalsahGui.GuiElementProp) - .map(iri => SalsahGuiConversions.iri2SalsahGuiElement(iri)), - guiorder = cardinalityInfo.guiOrder - ) - } - case None => - throw new InconsistentRepositoryDataException( - s"Resource type $resourceTypeIri is defined as having property $propertyIri, which doesn't exist" - ) - } - }.toVector - .sortBy(_.guiorder) + // filter out the properties that point to LinkValue objects + case (propertyIri, _) => + resourceClassInfo.linkValueProperties( + propertyIri + ) || propertyIri == OntologyConstants.KnoraBase.HasStandoffLinkTo + }.map { + case ( + propertyIri: IRI, + cardinalityInfo: KnoraCardinalityInfo + ) => + propertyInfo.propertyInfoMap.get(propertyIri) match { + case Some(entityInfo: PropertyInfoV1) => + if (entityInfo.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. + + PropertyDefinitionV1( + id = propertyIri, + name = propertyIri, + label = entityInfo.getPredicateObject( + predicateIri = OntologyConstants.Rdfs.Label, + preferredLangs = Some( + userProfile.lang, + settings.fallbackLanguage + ) + ), + description = entityInfo.getPredicateObject( + predicateIri = OntologyConstants.Rdfs.Comment, + preferredLangs = Some( + userProfile.lang, + settings.fallbackLanguage + ) + ), + vocabulary = entityInfo.ontologyIri, + occurrence = cardinalityInfo.cardinality.toString, + valuetype_id = + OntologyConstants.KnoraBase.LinkValue, + attributes = valueUtilV1.makeAttributeString( + entityInfo + .getPredicateStringObjectsWithoutLang( + OntologyConstants.SalsahGui.GuiAttribute + ) + valueUtilV1 + .makeAttributeRestype( + entityInfo + .getPredicateObject( + OntologyConstants.KnoraBase.ObjectClassConstraint + ) + .getOrElse( + throw InconsistentRepositoryDataException( + s"Property $propertyIri has no knora-base:objectClassConstraint" + ) + ) + ) + ), + gui_name = entityInfo + .getPredicateObject( + OntologyConstants.SalsahGui.GuiElementProp + ) + .map(iri => + SalsahGuiConversions.iri2SalsahGuiElement(iri) + ), + guiorder = cardinalityInfo.guiOrder + ) + + } else { + + PropertyDefinitionV1( + id = propertyIri, + name = propertyIri, + label = entityInfo.getPredicateObject( + predicateIri = OntologyConstants.Rdfs.Label, + preferredLangs = Some( + userProfile.lang, + settings.fallbackLanguage + ) + ), + description = entityInfo.getPredicateObject( + predicateIri = OntologyConstants.Rdfs.Comment, + preferredLangs = Some( + userProfile.lang, + settings.fallbackLanguage + ) + ), + vocabulary = entityInfo.ontologyIri, + occurrence = cardinalityInfo.cardinality.toString, + valuetype_id = entityInfo + .getPredicateObject( + OntologyConstants.KnoraBase.ObjectClassConstraint + ) + .getOrElse( + throw InconsistentRepositoryDataException( + s"Property $propertyIri has no knora-base:objectClassConstraint" + ) + ), + attributes = valueUtilV1.makeAttributeString( + entityInfo.getPredicateStringObjectsWithoutLang( + OntologyConstants.SalsahGui.GuiAttribute + ) + ), + gui_name = entityInfo + .getPredicateObject( + OntologyConstants.SalsahGui.GuiElementProp + ) + .map(iri => + SalsahGuiConversions.iri2SalsahGuiElement(iri) + ), + guiorder = cardinalityInfo.guiOrder + ) + } + case None => + throw new InconsistentRepositoryDataException( + s"Resource type $resourceTypeIri is defined as having property $propertyIri, which doesn't exist" + ) + } + }.toVector + .sortBy(_.guiorder) // Build the API response. resourceTypeResponse = ResourceTypeResponseV1( - restype_info = ResTypeInfoV1( - name = resourceTypeIri, - label = resourceClassInfo.getPredicateObject( - predicateIri = OntologyConstants.Rdfs.Label, - preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) - ), - description = resourceClassInfo.getPredicateObject( - predicateIri = OntologyConstants.Rdfs.Comment, - preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) - ), - iconsrc = resourceClassInfo.getPredicateObject(OntologyConstants.KnoraBase.ResourceIcon), - properties = propertyDefinitions - ) - ) + restype_info = ResTypeInfoV1( + name = resourceTypeIri, + label = resourceClassInfo.getPredicateObject( + predicateIri = OntologyConstants.Rdfs.Label, + preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) + ), + description = resourceClassInfo.getPredicateObject( + predicateIri = OntologyConstants.Rdfs.Comment, + preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) + ), + iconsrc = + resourceClassInfo.getPredicateObject(OntologyConstants.KnoraBase.ResourceIcon), + properties = propertyDefinitions + ) + ) } yield resourceTypeResponse } @@ -310,10 +345,10 @@ class OntologyResponderV1(responderData: ResponderData) extends Responder(respon private def checkSubClass(checkSubClassRequest: CheckSubClassRequestV1): Future[CheckSubClassResponseV1] = for { response: CheckSubClassResponseV2 <- (responderManager ? CheckSubClassRequestV2( - subClassIri = checkSubClassRequest.subClassIri.toSmartIri, - superClassIri = checkSubClassRequest.superClassIri.toSmartIri, - checkSubClassRequest.userProfile - )).mapTo[CheckSubClassResponseV2] + subClassIri = checkSubClassRequest.subClassIri.toSmartIri, + superClassIri = checkSubClassRequest.superClassIri.toSmartIri, + checkSubClassRequest.userProfile + )).mapTo[CheckSubClassResponseV2] } yield CheckSubClassResponseV1(response.isSubClass) @@ -326,16 +361,16 @@ class OntologyResponderV1(responderData: ResponderData) extends Responder(respon private def getSubClasses(getSubClassesRequest: SubClassesGetRequestV1): Future[SubClassesGetResponseV1] = for { response: SubClassesGetResponseV2 <- (responderManager ? SubClassesGetRequestV2( - getSubClassesRequest.resourceClassIri.toSmartIri, - getSubClassesRequest.userADM - )).mapTo[SubClassesGetResponseV2] + getSubClassesRequest.resourceClassIri.toSmartIri, + getSubClassesRequest.userADM + )).mapTo[SubClassesGetResponseV2] subClasses = response.subClasses.map { subClassInfoV2 => - SubClassInfoV1( - id = subClassInfoV2.id.toString, - label = subClassInfoV2.label - ) - } + SubClassInfoV1( + id = subClassInfoV2.id.toString, + label = subClassInfoV2.label + ) + } } yield SubClassesGetResponseV1(subClasses) @@ -354,47 +389,55 @@ class OntologyResponderV1(responderData: ResponderData) extends Responder(respon ): Future[NamedGraphsResponseV1] = for { projectsResponse <- (responderManager ? ProjectsGetRequestADM( - featureFactoryConfig = featureFactoryConfig, - requestingUser = userProfile - )).mapTo[ProjectsGetResponseADM] + featureFactoryConfig = featureFactoryConfig, + requestingUser = userProfile + )).mapTo[ProjectsGetResponseADM] readOntologyMetadataV2 <- (responderManager ? OntologyMetadataGetByProjectRequestV2( - projectIris = projectIris.map(_.toSmartIri), - requestingUser = userProfile - )).mapTo[ReadOntologyMetadataV2] + projectIris = projectIris.map(_.toSmartIri), + requestingUser = userProfile + )).mapTo[ReadOntologyMetadataV2] projectsMap: Map[IRI, ProjectADM] = projectsResponse.projects.map { project => - project.id -> project - }.toMap + project.id -> project + }.toMap namedGraphs: Seq[NamedGraphV1] = readOntologyMetadataV2.ontologies.toVector - .map(_.toOntologySchema(InternalSchema)) - .filter { ontologyMetadata => - // In V1, the only built-in ontology we show is knora-base. - val ontologyLabel = ontologyMetadata.ontologyIri.getOntologyName - ontologyLabel == OntologyConstants.KnoraBase.KnoraBaseOntologyLabel || !OntologyConstants.BuiltInOntologyLabels - .contains(ontologyLabel) - } - .map { ontologyMetadata => - val project = projectsMap(ontologyMetadata.projectIri.get.toString) - - NamedGraphV1( - id = ontologyMetadata.ontologyIri.toString, - shortname = project.shortname, - longname = project.longname - .getOrElse(throw InconsistentRepositoryDataException(s"Project ${project.id} has no longname")), - description = project.description.headOption - .getOrElse(throw InconsistentRepositoryDataException(s"Project ${project.id} has no description")) - .toString, - project_id = project.id, - uri = ontologyMetadata.ontologyIri.toString, - active = project.status - ) - } + .map(_.toOntologySchema(InternalSchema)) + .filter { ontologyMetadata => + // In V1, the only built-in ontology we show is knora-base. + val ontologyLabel = ontologyMetadata.ontologyIri.getOntologyName + ontologyLabel == OntologyConstants.KnoraBase.KnoraBaseOntologyLabel || !OntologyConstants.BuiltInOntologyLabels + .contains(ontologyLabel) + } + .map { ontologyMetadata => + val project = projectsMap(ontologyMetadata.projectIri.get.toString) + + NamedGraphV1( + id = ontologyMetadata.ontologyIri.toString, + shortname = project.shortname, + longname = project.longname + .getOrElse( + throw InconsistentRepositoryDataException( + s"Project ${project.id} has no longname" + ) + ), + description = project.description.headOption + .getOrElse( + throw InconsistentRepositoryDataException( + s"Project ${project.id} has no description" + ) + ) + .toString, + project_id = project.id, + uri = ontologyMetadata.ontologyIri.toString, + active = project.status + ) + } response = NamedGraphsResponseV1( - vocabularies = namedGraphs - ) + vocabularies = namedGraphs + ) } yield response /** @@ -407,11 +450,11 @@ class OntologyResponderV1(responderData: ResponderData) extends Responder(respon def getNamedGraphEntityInfoV1ForNamedGraph(namedGraphIri: IRI, userProfile: UserADM): Future[NamedGraphEntityInfoV1] = for { response: OntologyKnoraEntitiesIriInfoV2 <- (responderManager ? OntologyKnoraEntityIrisGetRequestV2( - namedGraphIri.toSmartIri, - userProfile - )).mapTo[OntologyKnoraEntitiesIriInfoV2] + namedGraphIri.toSmartIri, + userProfile + )).mapTo[OntologyKnoraEntitiesIriInfoV2] - classIrisForV1 = response.classIris.map(_.toString) -- OntologyConstants.KnoraBase.AbstractResourceClasses + classIrisForV1 = response.classIris.map(_.toString) -- OntologyConstants.KnoraBase.AbstractResourceClasses propertyIrisForV1 = response.propertyIris.map(_.toString) - OntologyConstants.KnoraBase.ResourceProperty } yield NamedGraphEntityInfoV1( @@ -440,9 +483,9 @@ class OntologyResponderV1(responderData: ResponderData) extends Responder(respon // get NamedGraphEntityInfoV1 for the given named graph namedGraphEntityInfo: NamedGraphEntityInfoV1 <- getNamedGraphEntityInfoV1ForNamedGraph( - namedGraphIri, - userProfile - ) + namedGraphIri, + userProfile + ) // get resinfo for each resource class in namedGraphEntityInfo resInfosForNamedGraphFuture: Set[Future[(String, ResourceTypeResponseV1)]] = @@ -455,21 +498,27 @@ class OntologyResponderV1(responderData: ResponderData) extends Responder(respon resInfosForNamedGraph: Set[(IRI, ResourceTypeResponseV1)] <- Future.sequence(resInfosForNamedGraphFuture) resourceTypes: Vector[ResourceTypeV1] = resInfosForNamedGraph.map { case (resClassIri, resInfo) => - val properties = resInfo.restype_info.properties.map { prop => - PropertyTypeV1( - id = prop.id, - label = prop.label.getOrElse(throw InconsistentRepositoryDataException(s"No label given for ${prop.id}")) - ) - }.toVector - - ResourceTypeV1( - id = resClassIri, - label = resInfo.restype_info.label.getOrElse( - throw InconsistentRepositoryDataException(s"No label given for $resClassIri") - ), - properties = properties - ) - }.toVector + val properties = resInfo.restype_info.properties.map { prop => + PropertyTypeV1( + id = prop.id, + label = prop.label.getOrElse( + throw InconsistentRepositoryDataException( + s"No label given for ${prop.id}" + ) + ) + ) + }.toVector + + ResourceTypeV1( + id = resClassIri, + label = resInfo.restype_info.label.getOrElse( + throw InconsistentRepositoryDataException( + s"No label given for $resClassIri" + ) + ), + properties = properties + ) + }.toVector } yield resourceTypes @@ -483,14 +532,13 @@ class OntologyResponderV1(responderData: ResponderData) extends Responder(respon case None => // map over all named graphs and collect the resource types for { projectNamedGraphsResponse: NamedGraphsResponseV1 <- getNamedGraphs( - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) projectNamedGraphIris: Seq[IRI] = projectNamedGraphsResponse.vocabularies.map(_.uri) - resourceTypesPerProject: Seq[Future[Seq[ResourceTypeV1]]] = projectNamedGraphIris.map(iri => - getResourceTypes(iri) - ) + resourceTypesPerProject: Seq[Future[Seq[ResourceTypeV1]]] = + projectNamedGraphIris.map(iri => getResourceTypes(iri)) resourceTypes: Seq[Seq[ResourceTypeV1]] <- Future.sequence(resourceTypesPerProject) } yield ResourceTypesForNamedGraphResponseV1(resourcetypes = resourceTypes.flatten) } @@ -516,18 +564,19 @@ class OntologyResponderV1(responderData: ResponderData) extends Responder(respon userProfile: UserADM ): Future[Seq[PropertyDefinitionInNamedGraphV1]] = for { - namedGraphEntityInfo <- getNamedGraphEntityInfoV1ForNamedGraph(namedGraphIri, userProfile) + namedGraphEntityInfo <- getNamedGraphEntityInfoV1ForNamedGraph(namedGraphIri, userProfile) propertyIris: Set[IRI] = namedGraphEntityInfo.propertyIris entities: EntityInfoGetResponseV1 <- getEntityInfoResponseV1( - propertyIris = propertyIris, - userProfile = userProfile - ) - propertyInfoMap: Map[IRI, PropertyInfoV1] = entities.propertyInfoMap.filterNot { - case (propertyIri, propertyEntityInfo) => propertyEntityInfo.isLinkValueProp - } - - propertyDefinitions: Vector[PropertyDefinitionInNamedGraphV1] = propertyInfoMap.map { - case (propertyIri: IRI, entityInfo: PropertyInfoV1) => + propertyIris = propertyIris, + userProfile = userProfile + ) + propertyInfoMap: Map[IRI, PropertyInfoV1] = + entities.propertyInfoMap.filterNot { case (propertyIri, propertyEntityInfo) => + propertyEntityInfo.isLinkValueProp + } + + propertyDefinitions: Vector[PropertyDefinitionInNamedGraphV1] = + propertyInfoMap.map { case (propertyIri: IRI, entityInfo: PropertyInfoV1) => if (entityInfo.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 @@ -594,7 +643,7 @@ class OntologyResponderV1(responderData: ResponderData) extends Responder(respon } - }.toVector + }.toVector } yield propertyDefinitions namedGraphIriOption match { @@ -607,14 +656,13 @@ class OntologyResponderV1(responderData: ResponderData) extends Responder(respon for { projectNamedGraphsResponse: NamedGraphsResponseV1 <- getNamedGraphs( - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) projectNamedGraphIris: Seq[IRI] = projectNamedGraphsResponse.vocabularies.map(_.uri) - propertyTypesPerProject: Seq[Future[Seq[PropertyDefinitionInNamedGraphV1]]] = projectNamedGraphIris.map(iri => - getPropertiesForNamedGraph(iri, userProfile) - ) + propertyTypesPerProject: Seq[Future[Seq[PropertyDefinitionInNamedGraphV1]]] = + projectNamedGraphIris.map(iri => getPropertiesForNamedGraph(iri, userProfile)) propertyTypes: Seq[Seq[PropertyDefinitionInNamedGraphV1]] <- Future.sequence(propertyTypesPerProject) } yield PropertyTypesForNamedGraphResponseV1(properties = propertyTypes.flatten) } @@ -634,7 +682,7 @@ class OntologyResponderV1(responderData: ResponderData) extends Responder(respon ): Future[PropertyTypesForResourceTypeResponseV1] = for { resInfo: ResourceTypeResponseV1 <- getResourceTypeResponseV1(resourceClassIri, userProfile) - propertyTypes = resInfo.restype_info.properties.toVector + propertyTypes = resInfo.restype_info.properties.toVector } yield PropertyTypesForResourceTypeResponseV1(properties = propertyTypes) diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v1/ProjectsResponderV1.scala b/webapi/src/main/scala/org/knora/webapi/responders/v1/ProjectsResponderV1.scala index 41ca6be05c..5ea34fd003 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/v1/ProjectsResponderV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v1/ProjectsResponderV1.scala @@ -70,9 +70,9 @@ class ProjectsResponderV1(responderData: ResponderData) extends Responder(respon //log.debug("projectsGetRequestV1") for { projects <- projectsGetV1( - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) result = if (projects.nonEmpty) { @@ -98,10 +98,10 @@ class ProjectsResponderV1(responderData: ResponderData) extends Responder(respon ): Future[Seq[ProjectInfoV1]] = for { sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getProjects() - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getProjects() + .toString() + ) //_ = log.debug(s"getProjectsResponseV1 - query: $sparqlQueryString") projectsResponse <- (storeManager ? SparqlSelectRequest(sparqlQueryString)).mapTo[SparqlSelectResult] @@ -109,70 +109,72 @@ class ProjectsResponderV1(responderData: ResponderData) extends Responder(respon projectsResponseRows: Seq[VariableResultsRow] = projectsResponse.results.bindings - projectsWithProperties: Map[IRI, Map[IRI, Seq[String]]] = projectsResponseRows.groupBy(_.rowMap("s")).map { - case (projIri: String, rows: Seq[VariableResultsRow]) => + projectsWithProperties: Map[IRI, Map[IRI, Seq[String]]] = + projectsResponseRows.groupBy(_.rowMap("s")).map { case (projIri: String, rows: Seq[VariableResultsRow]) => ( projIri, rows.groupBy(_.rowMap("p")).map { case (predicate: IRI, literals: Seq[VariableResultsRow]) => predicate -> literals.map(_.rowMap("o")) } ) - } + } //_ = log.debug(s"getProjectsResponseV1 - projectsWithProperties: $projectsWithProperties") ontologiesForProjects <- getOntologiesForProjects( - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) projects = projectsWithProperties.map { case (projectIri: String, propsMap: Map[String, Seq[String]]) => - val keywordsSeq: Seq[String] = - propsMap.getOrElse(OntologyConstants.KnoraAdmin.ProjectKeyword, Seq.empty[String]).sorted - - val maybeKeywords: Option[String] = if (keywordsSeq.nonEmpty) { - Some(keywordsSeq.mkString(", ")) - } else { - None - } - - val ontologies = ontologiesForProjects.getOrElse(projectIri, Seq.empty[IRI]) - - ProjectInfoV1( - id = projectIri, - shortname = propsMap - .getOrElse( - OntologyConstants.KnoraAdmin.ProjectShortname, - throw InconsistentRepositoryDataException(s"Project: $projectIri has no shortname defined.") - ) - .head, - shortcode = propsMap - .getOrElse( - OntologyConstants.KnoraAdmin.ProjectShortcode, - throw InconsistentRepositoryDataException(s"Project: $projectIri has no shortcode defined.") - ) - .head, - longname = propsMap.get(OntologyConstants.KnoraAdmin.ProjectLongname).map(_.head), - description = propsMap.get(OntologyConstants.KnoraAdmin.ProjectDescription).map(_.head), - keywords = maybeKeywords, - logo = propsMap.get(OntologyConstants.KnoraAdmin.ProjectLogo).map(_.head), - institution = propsMap.get(OntologyConstants.KnoraAdmin.BelongsToInstitution).map(_.head), - ontologies = ontologies, - status = propsMap - .getOrElse( - OntologyConstants.KnoraAdmin.Status, - throw InconsistentRepositoryDataException(s"Project: $projectIri has no status defined.") - ) - .head - .toBoolean, - selfjoin = propsMap - .getOrElse( - OntologyConstants.KnoraAdmin.HasSelfJoinEnabled, - throw InconsistentRepositoryDataException(s"Project: $projectIri has no hasSelfJoinEnabled defined.") - ) - .head - .toBoolean - ) - }.toSeq + val keywordsSeq: Seq[String] = + propsMap.getOrElse(OntologyConstants.KnoraAdmin.ProjectKeyword, Seq.empty[String]).sorted + + val maybeKeywords: Option[String] = if (keywordsSeq.nonEmpty) { + Some(keywordsSeq.mkString(", ")) + } else { + None + } + + val ontologies = ontologiesForProjects.getOrElse(projectIri, Seq.empty[IRI]) + + ProjectInfoV1( + id = projectIri, + shortname = propsMap + .getOrElse( + OntologyConstants.KnoraAdmin.ProjectShortname, + throw InconsistentRepositoryDataException(s"Project: $projectIri has no shortname defined.") + ) + .head, + shortcode = propsMap + .getOrElse( + OntologyConstants.KnoraAdmin.ProjectShortcode, + throw InconsistentRepositoryDataException(s"Project: $projectIri has no shortcode defined.") + ) + .head, + longname = propsMap.get(OntologyConstants.KnoraAdmin.ProjectLongname).map(_.head), + description = propsMap.get(OntologyConstants.KnoraAdmin.ProjectDescription).map(_.head), + keywords = maybeKeywords, + logo = propsMap.get(OntologyConstants.KnoraAdmin.ProjectLogo).map(_.head), + institution = propsMap.get(OntologyConstants.KnoraAdmin.BelongsToInstitution).map(_.head), + ontologies = ontologies, + status = propsMap + .getOrElse( + OntologyConstants.KnoraAdmin.Status, + throw InconsistentRepositoryDataException(s"Project: $projectIri has no status defined.") + ) + .head + .toBoolean, + selfjoin = propsMap + .getOrElse( + OntologyConstants.KnoraAdmin.HasSelfJoinEnabled, + throw InconsistentRepositoryDataException( + s"Project: $projectIri has no hasSelfJoinEnabled defined." + ) + ) + .head + .toBoolean + ) + }.toSeq } yield projects @@ -192,28 +194,28 @@ class ProjectsResponderV1(responderData: ResponderData) extends Responder(respon for { // Get a UserADM for the UserProfileV1, because we need it to send a message to OntologyResponderV1. userADM: UserADM <- userProfile match { - case Some(profile) => - profile.userData.user_id match { - case Some(user_iri) => - (responderManager ? UserGetRequestADM( - identifier = UserIdentifierADM(maybeIri = Some(user_iri)), - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - )).mapTo[UserResponseADM].map(_.user) - - case None => FastFuture.successful(KnoraSystemInstances.Users.AnonymousUser) - } - - case None => FastFuture.successful(KnoraSystemInstances.Users.AnonymousUser) - } + case Some(profile) => + profile.userData.user_id match { + case Some(user_iri) => + (responderManager ? UserGetRequestADM( + identifier = UserIdentifierADM(maybeIri = Some(user_iri)), + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + )).mapTo[UserResponseADM].map(_.user) + + case None => FastFuture.successful(KnoraSystemInstances.Users.AnonymousUser) + } + + case None => FastFuture.successful(KnoraSystemInstances.Users.AnonymousUser) + } // Get the ontologies per project. namedGraphsResponse <- (responderManager ? NamedGraphsGetRequestV1( - projectIris = projectIris, - featureFactoryConfig = featureFactoryConfig, - userADM = userADM - )).mapTo[NamedGraphsResponseV1] + projectIris = projectIris, + featureFactoryConfig = featureFactoryConfig, + userADM = userADM + )).mapTo[NamedGraphsResponseV1] } yield namedGraphsResponse.vocabularies.map { namedGraph: NamedGraphV1 => namedGraph.project_id -> namedGraph.id @@ -240,15 +242,15 @@ class ProjectsResponderV1(responderData: ResponderData) extends Responder(respon //log.debug("projectInfoByIRIGetRequestV1 - projectIRI: {}", projectIRI) for { maybeProjectInfo: Option[ProjectInfoV1] <- projectInfoByIRIGetV1( - projectIri = projectIri, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + projectIri = projectIri, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) projectInfo = maybeProjectInfo match { - case Some(pi) => pi - case None => throw NotFoundException(s"Project '$projectIri' not found") - } + case Some(pi) => pi + case None => throw NotFoundException(s"Project '$projectIri' not found") + } } yield ProjectInfoResponseV1( project_info = projectInfo ) @@ -269,20 +271,20 @@ class ProjectsResponderV1(responderData: ResponderData) extends Responder(respon //log.debug("projectInfoByIRIGetV1 - projectIRI: {}", projectIri) for { sparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getProjectByIri( - projectIri = projectIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getProjectByIri( + projectIri = projectIri + ) + .toString() + ) projectResponse <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] ontologiesForProjects: Map[IRI, Seq[IRI]] <- getOntologiesForProjects( - projectIris = Set(projectIri), - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + projectIris = Set(projectIri), + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) projectOntologies = ontologiesForProjects.getOrElse(projectIri, Seq.empty[IRI]) @@ -321,12 +323,12 @@ class ProjectsResponderV1(responderData: ResponderData) extends Responder(respon //log.debug("projectInfoByShortnameGetRequestV1 - shortName: {}", shortName) for { sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getProjectByShortname( - shortname = shortName - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getProjectByShortname( + shortname = shortName + ) + .toString() + ) //_ = log.debug(s"getProjectInfoByShortnameGetRequest - query: $sparqlQueryString") projectResponse <- (storeManager ? SparqlSelectRequest(sparqlQueryString)).mapTo[SparqlSelectResult] @@ -341,19 +343,19 @@ class ProjectsResponderV1(responderData: ResponderData) extends Responder(respon } ontologiesForProjects: Map[IRI, Seq[IRI]] <- getOntologiesForProjects( - projectIris = Set(projectIri), - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + projectIris = Set(projectIri), + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) projectOntologies = ontologiesForProjects(projectIri) projectInfo = createProjectInfoV1( - projectResponse = projectResponse.results.bindings, - projectIri = projectIri, - ontologies = projectOntologies, - userProfile - ) + projectResponse = projectResponse.results.bindings, + projectIri = projectIri, + ontologies = projectOntologies, + userProfile + ) } yield ProjectInfoResponseV1( project_info = projectInfo @@ -446,14 +448,14 @@ class ProjectsResponderV1(responderData: ResponderData) extends Responder(respon def projectByIriExists(projectIri: IRI): Future[Boolean] = for { askString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .checkProjectExistsByIri(projectIri = projectIri) - .toString - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .checkProjectExistsByIri(projectIri = projectIri) + .toString + ) //_ = log.debug("projectExists - query: {}", askString) checkProjectExistsResponse <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] - result = checkProjectExistsResponse.result + result = checkProjectExistsResponse.result } yield result @@ -466,14 +468,14 @@ class ProjectsResponderV1(responderData: ResponderData) extends Responder(respon def projectByShortnameExists(shortname: String): Future[Boolean] = for { askString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .checkProjectExistsByShortname(shortname = shortname) - .toString - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .checkProjectExistsByShortname(shortname = shortname) + .toString + ) //_ = log.debug("projectExists - query: {}", askString) checkProjectExistsResponse <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] - result = checkProjectExistsResponse.result + result = checkProjectExistsResponse.result } yield result @@ -486,14 +488,14 @@ class ProjectsResponderV1(responderData: ResponderData) extends Responder(respon def projectByShortcodeExists(shortcode: String): Future[Boolean] = for { askString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .checkProjectExistsByShortcode(shortcode = shortcode) - .toString - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .checkProjectExistsByShortcode(shortcode = shortcode) + .toString + ) //_ = log.debug("projectExists - query: {}", askString) checkProjectExistsResponse <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] - result = checkProjectExistsResponse.result + result = checkProjectExistsResponse.result } yield result } diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v1/ResourcesResponderV1.scala b/webapi/src/main/scala/org/knora/webapi/responders/v1/ResourcesResponderV1.scala index c689466b79..e83473e8f3 100755 --- a/webapi/src/main/scala/org/knora/webapi/responders/v1/ResourcesResponderV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v1/ResourcesResponderV1.scala @@ -216,19 +216,19 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo 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() - ) + 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 <- (storeManager ? SparqlSelectRequest(sparql)).mapTo[SparqlSelectResult] - rows = response.results.bindings + rows = response.results.bindings // Did we get any results? recursiveResults: GraphQueryResults <- @@ -266,7 +266,7 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo // Get the edges from the query results. val edges: Set[QueryResultEdge] = rows.map { row => - val rowMap = row.rowMap + val rowMap = row.rowMap val nodeIri = rowMap("node") // The SPARQL query takes a start node and returns the other node in the edge. @@ -312,7 +312,7 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo // 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)) + val filteredOtherNodes = otherNodes.filter(node => visibleNodeIrisFromEdges.contains(node.nodeIri)) // Make a GraphQueryResults containing the resulting nodes and edges, including the start // node. @@ -354,64 +354,64 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo for { // Get the start node. sparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getGraphData( - startNodeIri = graphDataGetRequest.resourceIri, - startNodeOnly = true - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getGraphData( + startNodeIri = graphDataGetRequest.resourceIri, + startNodeOnly = true + ) + .toString() + ) // _ = println(sparql) response: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(sparql)).mapTo[SparqlSelectResult] - rows = response.results.bindings + rows = response.results.bindings _ = if (rows.isEmpty) { - throw NotFoundException(s"Resource ${graphDataGetRequest.resourceIri} not found (it may have been deleted)") - } + 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") - ) + 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}" - ) - } + 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 - ) + startNode = startNode, + outbound = true, + depth = graphDataGetRequest.depth + ) // Recursively get the graph containing inbound links. inboundQueryResults: GraphQueryResults <- traverseGraph( - startNode = startNode, - outbound = false, - depth = graphDataGetRequest.depth - ) + 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 @@ -420,53 +420,63 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo // Get the labels of the resource classes and properties from the ontology responder. resourceClassIris = nodes.map(_.nodeClass) - propertyIris = edges.map(_.linkProp) + propertyIris = edges.map(_.linkProp) entityInfoRequest = EntityInfoGetRequestV1( - resourceClassIris = resourceClassIris, - propertyIris = propertyIris, - userProfile = graphDataGetRequest.userADM - ) + resourceClassIris = resourceClassIris, + propertyIris = propertyIris, + userProfile = graphDataGetRequest.userADM + ) entityInfoResponse: EntityInfoGetResponseV1 <- (responderManager ? entityInfoRequest) - .mapTo[EntityInfoGetResponseV1] + .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, settings.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 + // 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, settings.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, settings.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 + // 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, settings.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) } @@ -485,11 +495,11 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo ): Future[ResourceInfoResponseV1] = for { (userPermissions, resInfo) <- getResourceInfoV1( - resourceIri = resourceIri, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile, - queryOntology = true - ) + resourceIri = resourceIri, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile, + queryOntology = true + ) } yield userPermissions match { case Some(permissions) => ResourceInfoResponseV1( @@ -535,12 +545,12 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo val maybeIncomingRefsFuture: Future[Option[SparqlSelectResult]] = if (getIncoming) { for { incomingRefsSparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getIncomingReferences( - resourceIri = resourceIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getIncomingReferences( + resourceIri = resourceIri + ) + .toString() + ) response <- (storeManager ? SparqlSelectRequest(incomingRefsSparql)).mapTo[SparqlSelectResult] } yield Some(response) } else { @@ -555,145 +565,189 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo // Get the types of all the resources that this resource links to. linkedResourceTypes = groupedPropsByType.groupedLinkProperties.groupedProperties.foldLeft(Set.empty[IRI]) { - case (acc, (prop, 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") - } + case (acc, (prop, 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 - } + resTypeAcc ++ resType + } - acc ++ targetResourceTypes - } + 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, - featureFactoryConfig = featureFactoryConfig, - 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, - responderManager = responderManager, - featureFactoryConfig = featureFactoryConfig, - 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]]] - } + 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, + featureFactoryConfig = + featureFactoryConfig, + 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, + responderManager = + responderManager, + featureFactoryConfig = + featureFactoryConfig, + 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) @@ -702,69 +756,73 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo // Ask the ontology responder for information about the ontology entities that we need information about. entityInfoResponse: EntityInfoGetResponseV1 <- (responderManager ? EntityInfoGetRequestV1( - resourceClassIris = incomingTypes ++ linkedResourceTypes + resInfoWithoutQueryingOntology.restype_id, - propertyIris = - groupedPropsByType.groupedOrdinaryValueProperties.groupedProperties.keySet ++ groupedPropsByType.groupedLinkProperties.groupedProperties.keySet, - userProfile = userProfile - )).mapTo[EntityInfoGetResponseV1] + 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 + 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 - } + 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, settings.fallbackLanguage) - ) + predicateIri = OntologyConstants.Rdfs.Label, + preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) + ) resInfo: ResourceInfoV1 = resInfoWithoutQueryingOntology.copy( - restype_label = resourceClassLabel, - restype_description = resourceTypeEntityInfo.getPredicateObject( - predicateIri = OntologyConstants.Rdfs.Comment, - preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) - ), - restype_iconsrc = maybeResourceTypeIconSrc - ) + restype_label = resourceClassLabel, + restype_description = resourceTypeEntityInfo.getPredicateObject( + predicateIri = OntologyConstants.Rdfs.Comment, + preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) + ), + restype_iconsrc = maybeResourceTypeIconSrc + ) // Construct a ResourceDataV1. resData = ResourceDataV1( - rights = permissions, - restype_label = resourceClassLabel, - restype_name = resInfo.restype_id, - res_id = resourceIri, - iconsrc = maybeResourceTypeIconSrc - ) + 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, settings.fallbackLanguage) - ), - restype_description = incomingResourceTypeEntityInfo.getPredicateObject( - predicateIri = OntologyConstants.Rdfs.Comment, - preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) - ), - restype_iconsrc = - incomingResourceTypeEntityInfo.getPredicateObject(OntologyConstants.KnoraBase.ResourceIcon) match { - case Some(resClassIcon) => - Some(valueUtilV1.makeResourceClassIconURL(incoming.resinfo.restype_id, resClassIcon)) - case _ => None - } - ) - ) - } + 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, settings.fallbackLanguage) + ), + restype_description = incomingResourceTypeEntityInfo.getPredicateObject( + predicateIri = OntologyConstants.Rdfs.Comment, + preferredLangs = Some(userProfile.lang, settings.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. @@ -777,15 +835,15 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo // 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, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + containingResourceIri = resourceIri, + projectShortcode = resInfoWithoutQueryingOntology.project_shortcode, + groupedPropertiesByType = groupedPropsByType, + propertyInfoMap = entityInfoResponse.propertyInfoMap, + resourceEntityInfoMap = entityInfoResponse.resourceClassInfoMap, + propsAndCardinalities = propsAndCardinalities, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) // Construct PropertyV1 objects representing properties that have no data for this resource, but are possible properties for the resource type. @@ -795,66 +853,76 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo // Get information from the ontology about the properties that have no data for this resource. emptyPropsInfoResponse: EntityInfoGetResponseV1 <- (responderManager ? EntityInfoGetRequestV1( - propertyIris = emptyPropsIris, - userProfile = userProfile - )).mapTo[EntityInfoGetResponseV1] + 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(OntologyConstants.SalsahGui.GuiElementProp) - .map(guiElementIri => SalsahGuiConversions.iri2SalsahGuiElement(guiElementIri)), - label = propertyEntityInfo.getPredicateObject( - predicateIri = OntologyConstants.Rdfs.Label, - preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) - ), - occurrence = Some(propsAndCardinalities(propertyIri).cardinality.toString), - attributes = (propertyEntityInfo.getPredicateStringObjectsWithoutLang( - OntologyConstants.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(OntologyConstants.SalsahGui.GuiElementProp) - .map(guiElementIri => SalsahGuiConversions.iri2SalsahGuiElement(guiElementIri)), - label = propertyEntityInfo.getPredicateObject( - predicateIri = OntologyConstants.Rdfs.Label, - preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) - ), - occurrence = Some(propsAndCardinalities(propertyIri).cardinality.toString), - attributes = propertyEntityInfo - .getPredicateStringObjectsWithoutLang(OntologyConstants.SalsahGui.GuiAttribute) - .mkString(";"), - value_rights = Nil - ) - } - } + 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(OntologyConstants.SalsahGui.GuiElementProp) + .map(guiElementIri => + SalsahGuiConversions.iri2SalsahGuiElement(guiElementIri) + ), + label = propertyEntityInfo.getPredicateObject( + predicateIri = OntologyConstants.Rdfs.Label, + preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) + ), + occurrence = Some(propsAndCardinalities(propertyIri).cardinality.toString), + attributes = (propertyEntityInfo.getPredicateStringObjectsWithoutLang( + OntologyConstants.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(OntologyConstants.SalsahGui.GuiElementProp) + .map(guiElementIri => + SalsahGuiConversions.iri2SalsahGuiElement(guiElementIri) + ), + label = propertyEntityInfo.getPredicateObject( + predicateIri = OntologyConstants.Rdfs.Label, + preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) + ), + occurrence = Some(propsAndCardinalities(propertyIri).cardinality.toString), + attributes = propertyEntityInfo + .getPredicateStringObjectsWithoutLang( + OntologyConstants.SalsahGui.GuiAttribute + ) + .mkString(";"), + value_rights = Nil + ) + } + } // Add a fake property `__location__` if the resource has FileValues. properties: Seq[PropertyV1] = @@ -988,8 +1056,8 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo * @return a [[SourceObject]]. */ def createSourceObjectFromResultRow(projectShortcode: String, row: VariableResultsRow): SourceObject = { - val sourceObjectIri = row.rowMap("sourceObject") - val sourceObjectOwner = row.rowMap("sourceObjectAttachedToUser") + val sourceObjectIri = row.rowMap("sourceObject") + val sourceObjectOwner = row.rowMap("sourceObjectAttachedToUser") val sourceObjectProject = row.rowMap("sourceObjectAttachedToProject") val sourceObjectLiteral = row.rowMap("sourceObjectPermissions") @@ -1001,8 +1069,8 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo userProfile = userProfileV1 ) - val linkValueIri = row.rowMap("linkValue") - val linkValueCreator = row.rowMap("linkValueCreator") + val linkValueIri = row.rowMap("linkValue") + val linkValueCreator = row.rowMap("linkValueCreator") val linkValuePermissions = row.rowMap("linkValuePermissions") val linkValuePermissionCode = PermissionUtilADM.getUserPermissionV1( entityIri = linkValueIri, @@ -1030,52 +1098,52 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo for { // Get the resource info even if the user didn't ask for it, so we can check its permissions. (userPermission, resInfoV1) <- getResourceInfoV1( - resourceIri = resourceIri, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile, - queryOntology = true - ) + resourceIri = resourceIri, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile, + queryOntology = true + ) _ = if (userPermission.isEmpty) { - throw ForbiddenException( - s"User $userIri does not have permission to query the context of resource $resourceIri" - ) - } + throw ForbiddenException( + s"User $userIri does not have permission to query the context of resource $resourceIri" + ) + } // If this resource is part of another resource, get its parent resource. isPartOfSparqlQuery = org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .isPartOf( - resourceIri = resourceIri - ) - .toString() + .isPartOf( + resourceIri = resourceIri + ) + .toString() isPartOfResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(isPartOfSparqlQuery)) - .mapTo[SparqlSelectResult] + .mapTo[SparqlSelectResult] (containingResourceIriOption: Option[IRI], containingResInfoV1Option: Option[ResourceInfoV1]) <- isPartOfResponse.results.bindings match { case rows if rows.nonEmpty => - val rowMap = rows.head.rowMap - val containingResourceIri = rowMap("containingResource") + val rowMap = rows.head.rowMap + val containingResourceIri = rowMap("containingResource") val containingResourceProject = rowMap("containingResourceProject") for { (containingResourcePermissionCode, resInfoV1) <- getResourceInfoV1( - resourceIri = containingResourceIri, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile, - queryOntology = true - ) - - linkValueIri = rowMap("linkValue") - linkValueCreator = rowMap("linkValueCreator") + resourceIri = containingResourceIri, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile, + queryOntology = true + ) + + linkValueIri = rowMap("linkValue") + linkValueCreator = rowMap("linkValueCreator") linkValuePermissions = rowMap("linkValuePermissions") linkValuePermissionCode = PermissionUtilADM.getUserPermissionV1( - entityIri = linkValueIri, - entityCreator = linkValueCreator, - entityProject = containingResourceProject, - entityPermissionLiteral = linkValuePermissions, - userProfile = userProfileV1 - ) + entityIri = linkValueIri, + entityCreator = linkValueCreator, + entityProject = containingResourceProject, + entityPermissionLiteral = linkValuePermissions, + userProfile = userProfileV1 + ) // Allow the user to see the link only if they have permission to see both the containing resource and the link value. permissionCode = Seq(containingResourcePermissionCode, linkValuePermissionCode).min @@ -1092,54 +1160,67 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo for { // Otherwise, do a SPARQL query that returns resources that are part of this resource (as indicated by knora-base:isPartOf). contextSparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getContext( - resourceIri = resourceIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getContext( + resourceIri = resourceIri + ) + .toString() + ) // _ = println(contextSparqlQuery) contextQueryResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(contextSparqlQuery)) - .mapTo[SparqlSelectResult] + .mapTo[SparqlSelectResult] rows: Seq[VariableResultsRow] = contextQueryResponse.results.bindings // The results consist of one row per source object. sourceObjects: Seq[SourceObject] = rows.map { row: VariableResultsRow => - val sourceObject: IRI = row.rowMap("sourceObject") - val projectShortcode: String = sourceObject.toSmartIri.getProjectCode - .getOrElse(throw InconsistentRepositoryDataException(s"Invalid resource IRI: $sourceObject")) - createSourceObjectFromResultRow(projectShortcode, row) - } + val sourceObject: IRI = row.rowMap("sourceObject") + val projectShortcode: String = sourceObject.toSmartIri.getProjectCode + .getOrElse( + throw InconsistentRepositoryDataException( + s"Invalid resource IRI: $sourceObject" + ) + ) + createSourceObjectFromResultRow(projectShortcode, row) + } // Filter the source objects by eliminating the ones that the user doesn't have permission to see. sourceObjectsWithPermissions = sourceObjects.filter(sourceObj => sourceObj.permissionCode.nonEmpty) contextItems: Seq[ResourceContextItemV1] = sourceObjectsWithPermissions.map { sourceObj: SourceObject => - // Generate a IIIF preview URL from the full-size image. - val (preview: Option[LocationV1], locations: Option[Seq[LocationV1]]): ( - Option[LocationV1], - Option[Seq[LocationV1]] - ) = - sourceObj.fileValue.find(fileVal => fileVal.permissionCode.nonEmpty) match { - case Some(full: StillImageFileValue) => - val preview: LocationV1 = - valueUtilV1.fileValueV12LocationV1(fullSizeImageFileValueToPreview(full.image)) - val fileVals: Seq[LocationV1] = - createMultipleImageResolutions(full.image).map(valueUtilV1.fileValueV12LocationV1) - (Some(preview), Some(Vector(preview) ++ fileVals)) - - case None => (None, None) - } - - ResourceContextItemV1( - res_id = sourceObj.id, - preview = preview, - locations = locations, - firstprop = sourceObj.firstprop - ) - } + // Generate a IIIF preview URL from the full-size image. + val ( + preview: Option[LocationV1], + locations: Option[Seq[LocationV1]] + ): ( + Option[LocationV1], + Option[Seq[LocationV1]] + ) = + sourceObj.fileValue.find(fileVal => + fileVal.permissionCode.nonEmpty + ) match { + case Some(full: StillImageFileValue) => + val preview: LocationV1 = + valueUtilV1.fileValueV12LocationV1( + fullSizeImageFileValueToPreview(full.image) + ) + val fileVals: Seq[LocationV1] = + createMultipleImageResolutions(full.image).map( + valueUtilV1.fileValueV12LocationV1 + ) + (Some(preview), Some(Vector(preview) ++ fileVals)) + + case None => (None, None) + } + + ResourceContextItemV1( + res_id = sourceObj.id, + preview = preview, + locations = locations, + firstprop = sourceObj.firstprop + ) + } } yield contextItems } else { @@ -1154,78 +1235,103 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo // check if there are regions pointing to this resource // regionSparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getRegions( - resourceIri = resourceIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getRegions( + resourceIri = resourceIri + ) + .toString() + ) regionQueryResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(regionSparqlQuery)) - .mapTo[SparqlSelectResult] + .mapTo[SparqlSelectResult] regionRows = regionQueryResponse.results.bindings regionPropertiesSequencedFutures: Seq[Future[PropsGetForRegionV1]] = regionRows.filter { regionRow => - val permissionCodeForRegion = PermissionUtilADM.getUserPermissionV1( - entityIri = regionRow.rowMap("region"), - entityCreator = regionRow.rowMap("owner"), - entityProject = regionRow.rowMap("project"), - entityPermissionLiteral = regionRow.rowMap("regionObjectPermissions"), - userProfile = userProfileV1 - ) - - // ignore regions the user has no permissions on - permissionCodeForRegion.nonEmpty - }.map { regionRow => - val regionIri = regionRow.rowMap("region") - val resClass = regionRow.rowMap("resclass") // possibly we deal with a subclass of knora-base:Region - - // get the properties for each region - for { - propsV1: Seq[PropertyV1] <- getResourceProperties( - resourceIri = regionIri, - maybeResourceTypeIri = Some(resClass), - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) - - propsGetV1 = propsV1.map { - // convert each PropertyV1 in a PropertyGetV1 - propV1: PropertyV1 => - convertPropertyV1toPropertyGetV1(propV1) - } - - // get the icon for this region's resource class - entityInfoResponse: EntityInfoGetResponseV1 <- (responderManager ? EntityInfoGetRequestV1( - resourceClassIris = Set(resClass), - userProfile = userProfile - )).mapTo[EntityInfoGetResponseV1] - - regionInfo: ClassInfoV1 = entityInfoResponse.resourceClassInfoMap(resClass) - - resClassIcon: Option[String] = regionInfo.predicates.get( - OntologyConstants.KnoraBase.ResourceIcon - ) match { - case Some(predicateInfo: PredicateInfoV1) => - Some( - valueUtilV1.makeResourceClassIconURL( - resClass, - predicateInfo.objects.headOption.getOrElse( - throw InconsistentRepositoryDataException( - s"resourceClass $resClass has no value for ${OntologyConstants.KnoraBase.ResourceIcon}" - ) - ) - ) - ) - case None => None - } - - } yield PropsGetForRegionV1( - properties = propsGetV1, - res_id = regionIri, - iconsrc = resClassIcon - ) - - } + val permissionCodeForRegion = + PermissionUtilADM + .getUserPermissionV1( + entityIri = + regionRow.rowMap("region"), + entityCreator = + regionRow.rowMap("owner"), + entityProject = + regionRow.rowMap("project"), + entityPermissionLiteral = + regionRow.rowMap( + "regionObjectPermissions" + ), + userProfile = userProfileV1 + ) + + // ignore regions the user has no permissions on + permissionCodeForRegion.nonEmpty + }.map { regionRow => + val regionIri = + regionRow.rowMap("region") + val resClass = regionRow.rowMap( + "resclass" + ) // possibly we deal with a subclass of knora-base:Region + + // get the properties for each region + for { + propsV1: Seq[PropertyV1] <- + getResourceProperties( + resourceIri = regionIri, + maybeResourceTypeIri = + Some(resClass), + featureFactoryConfig = + featureFactoryConfig, + userProfile = userProfile + ) + + propsGetV1 = propsV1.map { + // convert each PropertyV1 in a PropertyGetV1 + propV1: PropertyV1 => + convertPropertyV1toPropertyGetV1( + propV1 + ) + } + + // get the icon for this region's resource class + entityInfoResponse: EntityInfoGetResponseV1 <- + (responderManager ? EntityInfoGetRequestV1( + resourceClassIris = + Set(resClass), + userProfile = userProfile + )).mapTo[EntityInfoGetResponseV1] + + regionInfo: ClassInfoV1 = + entityInfoResponse + .resourceClassInfoMap(resClass) + + resClassIcon: Option[String] = + regionInfo.predicates.get( + OntologyConstants.KnoraBase.ResourceIcon + ) match { + case Some( + predicateInfo: PredicateInfoV1 + ) => + Some( + valueUtilV1 + .makeResourceClassIconURL( + resClass, + predicateInfo.objects.headOption + .getOrElse( + throw InconsistentRepositoryDataException( + s"resourceClass $resClass has no value for ${OntologyConstants.KnoraBase.ResourceIcon}" + ) + ) + ) + ) + case None => None + } + + } yield PropsGetForRegionV1( + properties = propsGetV1, + res_id = regionIri, + iconsrc = resClassIcon + ) + + } // turn sequenced Futures into one Future of a sequence regionProperties: Seq[PropsGetForRegionV1] <- Future.sequence(regionPropertiesSequencedFutures) @@ -1245,39 +1351,39 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo } resourceContextV1 = containingResourceIriOption match { - case Some(_) => - // This resource is part of another resource, so return the resource info of the parent. - ResourceContextV1( - resinfo = resinfoV1WithRegionsOption, - parent_res_id = containingResourceIriOption, - parent_resinfo = containingResInfoV1Option, - context = ResourceContextCodeV1.RESOURCE_CONTEXT_IS_PARTOF, - canonical_res_id = resourceIri - ) - - case None => - if (resourceContexts.nonEmpty) { - // This resource has parts, so return information about the parts. - ResourceContextV1( - res_id = Some(resourceContexts.map(_.res_id)), - preview = Some(resourceContexts.map(_.preview)), - locations = Some(resourceContexts.map(_.locations)), - firstprop = Some(resourceContexts.map(_.firstprop)), - region = Some(resourceContexts.map(_ => None)), - canonical_res_id = resourceIri, - resinfo = resinfoV1WithRegionsOption, - resclass_name = Some("image"), - context = ResourceContextCodeV1.RESOURCE_CONTEXT_IS_COMPOUND - ) - } else { - // Indicate that neither of the above is true. - ResourceContextV1( - resinfo = resinfoV1WithRegionsOption, - canonical_res_id = resourceIri, - context = ResourceContextCodeV1.RESOURCE_CONTEXT_NONE - ) - } - } + case Some(_) => + // This resource is part of another resource, so return the resource info of the parent. + ResourceContextV1( + resinfo = resinfoV1WithRegionsOption, + parent_res_id = containingResourceIriOption, + parent_resinfo = containingResInfoV1Option, + context = ResourceContextCodeV1.RESOURCE_CONTEXT_IS_PARTOF, + canonical_res_id = resourceIri + ) + + case None => + if (resourceContexts.nonEmpty) { + // This resource has parts, so return information about the parts. + ResourceContextV1( + res_id = Some(resourceContexts.map(_.res_id)), + preview = Some(resourceContexts.map(_.preview)), + locations = Some(resourceContexts.map(_.locations)), + firstprop = Some(resourceContexts.map(_.firstprop)), + region = Some(resourceContexts.map(_ => None)), + canonical_res_id = resourceIri, + resinfo = resinfoV1WithRegionsOption, + resclass_name = Some("image"), + context = ResourceContextCodeV1.RESOURCE_CONTEXT_IS_COMPOUND + ) + } else { + // Indicate that neither of the above is true. + ResourceContextV1( + resinfo = resinfoV1WithRegionsOption, + canonical_res_id = resourceIri, + context = ResourceContextCodeV1.RESOURCE_CONTEXT_NONE + ) + } + } } yield ResourceContextResponseV1(resource_context = resourceContextV1) } @@ -1296,11 +1402,11 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo ): Future[ResourceRightsResponseV1] = for { (userPermission, _) <- getResourceInfoV1( - resourceIri = resourceIri, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile, - queryOntology = false - ) + resourceIri = resourceIri, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile, + queryOntology = false + ) // Construct an API response. rightsResponse = ResourceRightsResponseV1(rights = userPermission) @@ -1324,33 +1430,33 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo userProfile: UserADM ): Future[ResourceSearchResponseV1] = { val userProfileV1 = userProfile.asUserProfileV1 - val searchPhrase = MatchStringWhileTyping(searchString) + val searchPhrase = MatchStringWhileTyping(searchString) for { searchResourcesSparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getResourceSearchResult( - searchPhrase = searchPhrase, - restypeIriOption = resourceTypeIri, - numberOfProps = numberOfProps, - limitOfResults = limitOfResults, - separator = StringFormatter.INFORMATION_SEPARATOR_ONE - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getResourceSearchResult( + searchPhrase = searchPhrase, + restypeIriOption = resourceTypeIri, + numberOfProps = numberOfProps, + limitOfResults = limitOfResults, + separator = StringFormatter.INFORMATION_SEPARATOR_ONE + ) + .toString() + ) // _ = println(searchResourcesSparql) searchResponse <- (storeManager ? SparqlSelectRequest(searchResourcesSparql)).mapTo[SparqlSelectResult] - resultFutures: Seq[Future[ResourceSearchResultRowV1]] = searchResponse.results.bindings.map { - row: VariableResultsRow => - val resourceIri = row.rowMap("resourceIri") - val resourceClass = row.rowMap("resourceClass") - val firstProp = row.rowMap("firstProp") - val attachedToUser = row.rowMap("attachedToUser") - val attachedToProject = row.rowMap("attachedToProject") + resultFutures: Seq[Future[ResourceSearchResultRowV1]] = + searchResponse.results.bindings.map { row: VariableResultsRow => + val resourceIri = row.rowMap("resourceIri") + val resourceClass = row.rowMap("resourceClass") + val firstProp = row.rowMap("firstProp") + val attachedToUser = row.rowMap("attachedToUser") + val attachedToProject = row.rowMap("attachedToProject") val resourcePermissions = row.rowMap("resourcePermissions") val permissionCode = PermissionUtilADM.getUserPermissionV1( @@ -1363,13 +1469,13 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo for { resourceClassInfoResponse <- (responderManager ? EntityInfoGetRequestV1( - resourceClassIris = Set(resourceClass), - userProfile = userProfile - )).mapTo[EntityInfoGetResponseV1] + resourceClassIris = Set(resourceClass), + userProfile = userProfile + )).mapTo[EntityInfoGetResponseV1] cardinalities: Map[IRI, KnoraCardinalityInfo] = resourceClassInfoResponse - .resourceClassInfoMap(resourceClass) - .knoraResourceCardinalities + .resourceClassInfoMap(resourceClass) + .knoraResourceCardinalities searchResultRow: ResourceSearchResultRowV1 = if (numberOfProps > 1) { @@ -1379,7 +1485,7 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo maybeValues match { case Some(valuesReturned) => val valueStrings = valuesReturned.split(StringFormatter.INFORMATION_SEPARATOR_ONE) - val properties = row.rowMap("properties").split(StringFormatter.INFORMATION_SEPARATOR_ONE) + val properties = row.rowMap("properties").split(StringFormatter.INFORMATION_SEPARATOR_ONE) val valueOrders = row.rowMap("valueOrders").split(StringFormatter.INFORMATION_SEPARATOR_ONE).map(_.toInt) @@ -1436,12 +1542,12 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo } yield searchResultRow - } + } resources: Seq[ResourceSearchResultRowV1] <- Future.sequence(resultFutures) filteredResources = resources.filter( - _.rights.nonEmpty - ) // user must have permissions to see resource (must not be None) + _.rights.nonEmpty + ) // user must have permissions to see resource (must not be None) } yield ResourceSearchResponseV1(resources = filteredResources) } @@ -1472,12 +1578,12 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo val updateFuture: Future[MultipleResourceCreateResponseV1] = for { // Get user's IRI and don't allow anonymous users to create resources. userIri: IRI <- Future { - if (requestingUser.isAnonymousUser) { - throw ForbiddenException("Anonymous users aren't allowed to create resources") - } else { - requestingUser.id - } - } + if (requestingUser.isAnonymousUser) { + throw ForbiddenException("Anonymous users aren't allowed to create resources") + } else { + requestingUser.id + } + } // Get information about the project in which the resources will be created. projectInfoResponse <- { @@ -1494,39 +1600,44 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo resourceProjectIri: IRI = projectADM.id - _ = if ( - resourceProjectIri == OntologyConstants.KnoraAdmin.SystemProject || resourceProjectIri == OntologyConstants.KnoraAdmin.DefaultSharedOntologiesProject - ) { - throw BadRequestException(s"Resources cannot be created in project $resourceProjectIri") - } + _ = + if ( + resourceProjectIri == OntologyConstants.KnoraAdmin.SystemProject || resourceProjectIri == OntologyConstants.KnoraAdmin.DefaultSharedOntologiesProject + ) { + throw BadRequestException(s"Resources cannot be created in project $resourceProjectIri") + } // Ensure that the resource class isn't from a non-shared ontology in another project. namedGraph = StringFormatter.getGeneralInstance.projectDataNamedGraphV2(projectADM) // Create random IRIs for resources, collect in Map[clientResourceID, IRI] - clientResourceIDsToResourceIris: Map[String, IRI] = new ErrorHandlingMap( - toWrap = resourcesToCreate - .map(resRequest => resRequest.clientResourceID -> stringFormatter.makeRandomResourceIri(projectADM.shortcode)) - .toMap, - errorTemplateFun = { key => - s"Resource $key is the target of a link, but was not provided in the request" - }, - errorFun = { errorMsg => - throw BadRequestException(errorMsg) - } - ) + clientResourceIDsToResourceIris: Map[String, IRI] = + new ErrorHandlingMap( + toWrap = resourcesToCreate + .map(resRequest => + resRequest.clientResourceID -> stringFormatter.makeRandomResourceIri(projectADM.shortcode) + ) + .toMap, + errorTemplateFun = { key => + s"Resource $key is the target of a link, but was not provided in the request" + }, + errorFun = { errorMsg => + throw BadRequestException(errorMsg) + } + ) // Map each clientResourceID to its resource class IRI - clientResourceIDsToResourceClasses: Map[String, IRI] = new ErrorHandlingMap( - toWrap = resourcesToCreate.map(resRequest => resRequest.clientResourceID -> resRequest.resourceTypeIri).toMap, - errorTemplateFun = { key => - s"Resource $key is the target of a link, but was not provided in the request" - }, - errorFun = { errorMsg => - throw BadRequestException(errorMsg) - } - ) + clientResourceIDsToResourceClasses: Map[String, IRI] = + new ErrorHandlingMap( + toWrap = resourcesToCreate.map(resRequest => resRequest.clientResourceID -> resRequest.resourceTypeIri).toMap, + errorTemplateFun = { key => + s"Resource $key is the target of a link, but was not provided in the request" + }, + errorFun = { errorMsg => + throw BadRequestException(errorMsg) + } + ) // Get ontology information about all the resource classes and properties used in the request. @@ -1536,42 +1647,42 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo resourceClassOntologyIris: Set[SmartIri] = resourceClasses.map(_.toSmartIri.getOntologyFromEntity) readOntologyMetadataV2: ReadOntologyMetadataV2 <- (responderManager ? OntologyMetadataGetByIriRequestV2( - resourceClassOntologyIris, - requestingUser - )).mapTo[ReadOntologyMetadataV2] + resourceClassOntologyIris, + requestingUser + )).mapTo[ReadOntologyMetadataV2] _ = for (ontologyMetadata <- readOntologyMetadataV2.ontologies) { - val ontologyProjectIri: IRI = ontologyMetadata.projectIri - .getOrElse( - throw InconsistentRepositoryDataException(s"Ontology ${ontologyMetadata.ontologyIri} has no project") - ) - .toString + val ontologyProjectIri: IRI = ontologyMetadata.projectIri + .getOrElse( + throw InconsistentRepositoryDataException(s"Ontology ${ontologyMetadata.ontologyIri} has no project") + ) + .toString - if ( - resourceProjectIri != ontologyProjectIri && !(ontologyMetadata.ontologyIri.isKnoraBuiltInDefinitionIri || ontologyMetadata.ontologyIri.isKnoraSharedDefinitionIri) - ) { - throw BadRequestException( - s"Cannot create a resource in project $resourceProjectIri with a resource class from ontology ${ontologyMetadata.ontologyIri}, which belongs to another project and is not shared" - ) - } - } + if ( + resourceProjectIri != ontologyProjectIri && !(ontologyMetadata.ontologyIri.isKnoraBuiltInDefinitionIri || ontologyMetadata.ontologyIri.isKnoraSharedDefinitionIri) + ) { + throw BadRequestException( + s"Cannot create a resource in project $resourceProjectIri with a resource class from ontology ${ontologyMetadata.ontologyIri}, which belongs to another project and is not shared" + ) + } + } resourceClassesEntityInfoResponse: EntityInfoGetResponseV1 <- (responderManager ? EntityInfoGetRequestV1( - resourceClassIris = resourceClasses, - propertyIris = Set.empty[IRI], - userProfile = requestingUser - )).mapTo[EntityInfoGetResponseV1] + resourceClassIris = resourceClasses, + propertyIris = Set.empty[IRI], + userProfile = requestingUser + )).mapTo[EntityInfoGetResponseV1] allPropertyIris: Set[IRI] = resourceClassesEntityInfoResponse.resourceClassInfoMap.flatMap { - case (_, resourceEntityInfo) => - resourceEntityInfo.knoraResourceCardinalities.keySet - }.toSet + case (_, resourceEntityInfo) => + resourceEntityInfo.knoraResourceCardinalities.keySet + }.toSet propertyEntityInfoResponse: EntityInfoGetResponseV1 <- (responderManager ? EntityInfoGetRequestV1( - resourceClassIris = Set.empty[IRI], - propertyIris = allPropertyIris, - userProfile = requestingUser - )).mapTo[EntityInfoGetResponseV1] + resourceClassIris = Set.empty[IRI], + propertyIris = allPropertyIris, + userProfile = requestingUser + )).mapTo[EntityInfoGetResponseV1] propertyEntityInfoMapsPerResource: Map[IRI, Map[IRI, PropertyInfoV1]] = resourceClassesEntityInfoResponse.resourceClassInfoMap.map { case (resourceClassIri, resourceEntityInfo) => @@ -1585,8 +1696,8 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo // Get the default object access permissions for all the resource classes and properties used in the request. - defaultResourceClassAccessPermissionsFutures: Vector[Future[(IRI, String)]] = resourceClasses.toVector.map { - resourceClassIri => + defaultResourceClassAccessPermissionsFutures: Vector[Future[(IRI, String)]] = + resourceClasses.toVector.map { resourceClassIri => for { defaultObjectAccessPermissions <- { responderManager ? DefaultObjectAccessPermissionsStringForResourceClassGetADM( @@ -1597,17 +1708,18 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo ) }.mapTo[DefaultObjectAccessPermissionsStringResponseADM] } yield (resourceClassIri, defaultObjectAccessPermissions.permissionLiteral) - } + } defaultResourceClassAccessPermissionsSeq: Vector[(IRI, String)] <- Future.sequence( - defaultResourceClassAccessPermissionsFutures - ) - defaultResourceClassAccessPermissionsMap = new ErrorHandlingMap( - defaultResourceClassAccessPermissionsSeq.toMap, - { key: IRI => - s"No default resource class access permissions found for resource class $key" - } - ) + defaultResourceClassAccessPermissionsFutures + ) + defaultResourceClassAccessPermissionsMap = + new ErrorHandlingMap( + defaultResourceClassAccessPermissionsSeq.toMap, + { key: IRI => + s"No default resource class access permissions found for resource class $key" + } + ) defaultPropertyAccessPermissionsFutures: Map[IRI, Future[Map[IRI, String]]] = propertyEntityInfoMapsPerResource.map { case (resourceClassIri, propertyInfoMap) => @@ -1630,9 +1742,10 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo (resourceClassIri, propertyPermissionsFuture) } - defaultPropertyAccessPermissionsMapContents: Map[IRI, Map[IRI, String]] <- ActorUtil.sequenceFuturesInMap( - defaultPropertyAccessPermissionsFutures - ) + defaultPropertyAccessPermissionsMapContents: Map[IRI, Map[IRI, String]] <- + ActorUtil.sequenceFuturesInMap( + defaultPropertyAccessPermissionsFutures + ) defaultPropertyAccessPermissionsMapToWrap: Map[IRI, Map[IRI, String]] = defaultPropertyAccessPermissionsMapContents.map { @@ -1645,47 +1758,50 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo ) } - defaultPropertyAccessPermissionsMap: Map[IRI, Map[IRI, String]] = new ErrorHandlingMap( - defaultPropertyAccessPermissionsMapToWrap.toMap, - { key: IRI => - s"No default property access permissions found for resource class $key" - } - ) + defaultPropertyAccessPermissionsMap: Map[IRI, Map[IRI, String]] = + new ErrorHandlingMap( + defaultPropertyAccessPermissionsMapToWrap.toMap, + { key: IRI => + s"No default property access permissions found for resource class $key" + } + ) - resourceCreationFutures: Seq[Future[SparqlTemplateResourceToCreate]] = resourcesToCreate.map { - resourceCreateRequest: OneOfMultipleResourceCreateRequestV1 => + resourceCreationFutures: Seq[Future[SparqlTemplateResourceToCreate]] = + resourcesToCreate.map { resourceCreateRequest: OneOfMultipleResourceCreateRequestV1 => val creationDate: Instant = resourceCreateRequest.creationDate.getOrElse(Instant.now) for { // Check user's PermissionProfile (part of UserADM) to see if the user has the permission to // create a new resource in the given project. - defaultObjectAccessPermissions: String <- FastFuture( - Try(defaultResourceClassAccessPermissionsMap(resourceCreateRequest.resourceTypeIri)) - ) + defaultObjectAccessPermissions: String <- + FastFuture( + Try(defaultResourceClassAccessPermissionsMap(resourceCreateRequest.resourceTypeIri)) + ) // _ = log.debug(s"createNewResource - defaultObjectAccessPermissions: $defaultObjectAccessPermissions") _ = if (resourceCreateRequest.resourceTypeIri == OntologyConstants.KnoraBase.Resource) { - throw BadRequestException( - s"Instances of knora-base:Resource cannot be created, only instances of subclasses" - ) - } + throw BadRequestException( + s"Instances of knora-base:Resource cannot be created, only instances of subclasses" + ) + } resourceIri = clientResourceIDsToResourceIris(resourceCreateRequest.clientResourceID) // Check every resource to be created with respect of ontology and cardinalities. Links are still // represented by LinkToClientIDUpdateV1 instances here. fileValues <- checkResource( - resourceClassIri = resourceCreateRequest.resourceTypeIri, - resourceClassInfo = - resourceClassesEntityInfoResponse.resourceClassInfoMap(resourceCreateRequest.resourceTypeIri), - propertyInfoMap = propertyEntityInfoMapsPerResource(resourceCreateRequest.resourceTypeIri), - values = resourceCreateRequest.values, - convertedFile = resourceCreateRequest.file, - clientResourceIDsToResourceClasses = clientResourceIDsToResourceClasses, - featureFactoryConfig = featureFactoryConfig, - userProfile = requestingUser - ) + resourceClassIri = resourceCreateRequest.resourceTypeIri, + resourceClassInfo = resourceClassesEntityInfoResponse.resourceClassInfoMap( + resourceCreateRequest.resourceTypeIri + ), + propertyInfoMap = propertyEntityInfoMapsPerResource(resourceCreateRequest.resourceTypeIri), + values = resourceCreateRequest.values, + convertedFile = resourceCreateRequest.file, + clientResourceIDsToResourceClasses = clientResourceIDsToResourceClasses, + featureFactoryConfig = featureFactoryConfig, + userProfile = requestingUser + ) // Convert each LinkToClientIDUpdateV1 into a LinkUpdateV1. resourceValuesWithLinkTargetIris: Map[IRI, Seq[CreateValueV1WithComment]] = @@ -1731,35 +1847,35 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo resourceLabel = resourceCreateRequest.label, resourceCreationDate = creationDate ) - } + } // change sequence of futures to future of sequences sparqlTemplateResourcesToCreate: Seq[SparqlTemplateResourceToCreate] <- Future.sequence(resourceCreationFutures) //create a sparql query for all the resources to be created createMultipleResourcesSparql: String = generateSparqlForNewResources( - resourcesToCreate = sparqlTemplateResourcesToCreate, - projectIri = projectIri, - namedGraph = namedGraph, - creatorIri = userIri - ) + resourcesToCreate = sparqlTemplateResourcesToCreate, + projectIri = projectIri, + namedGraph = namedGraph, + creatorIri = userIri + ) // Do the update. createResourceResponse <- (storeManager ? SparqlUpdateRequest(createMultipleResourcesSparql)) - .mapTo[SparqlUpdateResponse] + .mapTo[SparqlUpdateResponse] // We don't query the newly created resources to verify that they and their values were actually created, // because this would be too expensive. In any case, since the update is done with INSERT DATA, i.e. there is no WHERE clause, // any failure should result in an HTTP error from the triplestore (SPARQL 1.1 Protocol §2.2.5, "Failure Responses"). - responses: Seq[OneOfMultipleResourcesCreateResponseV1] = resourcesToCreate.map { - resourceToCreate: OneOfMultipleResourceCreateRequestV1 => + responses: Seq[OneOfMultipleResourcesCreateResponseV1] = + resourcesToCreate.map { resourceToCreate: OneOfMultipleResourceCreateRequestV1 => OneOfMultipleResourcesCreateResponseV1( clientResourceID = resourceToCreate.clientResourceID, resourceIri = clientResourceIDsToResourceIris(resourceToCreate.clientResourceID), label = resourceToCreate.label ) - } + } } yield MultipleResourceCreateResponseV1(responses, projectADM) doSipiPostUpdateForResources( @@ -1837,103 +1953,122 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo // Check that each submitted value is consistent with the knora-base:objectClassConstraint of the property that is supposed to // point to it. propertyObjectClassConstraintChecks: Seq[Unit] <- Future.sequence { - values.foldLeft(Vector.empty[Future[Unit]]) { case (acc, (propertyIri, valuesWithComments)) => - val propertyInfo = - propertyInfoMap.getOrElse(propertyIri, throw NotFoundException(s"Property not found: $propertyIri")) - val propertyObjectClassConstraint = - propertyInfo.getPredicateObject(OntologyConstants.KnoraBase.ObjectClassConstraint).getOrElse { - throw InconsistentRepositoryDataException( - s"Property $propertyIri has no knora-base:objectClassConstraint" - ) - } - - acc ++ valuesWithComments.map { valueV1WithComment: CreateValueV1WithComment => - valueV1WithComment.updateValueV1 match { - case LinkToClientIDUpdateV1(targetClientID) => - // We're creating a link to a resource that doesn't exist yet, because it - // will be created in the same transaction. Check that it will belong to a - // suitable class. - val checkSubClassRequest = CheckSubClassRequestV1( - subClassIri = clientResourceIDsToResourceClasses(targetClientID), - superClassIri = propertyObjectClassConstraint, - userProfile = userProfile - ) - - for { - subClassResponse <- (responderManager ? checkSubClassRequest).mapTo[CheckSubClassResponseV1] - - _ = if (!subClassResponse.isSubClass) { - throw OntologyConstraintException( - s"Resource $targetClientID cannot be the target of property $propertyIri, because it is not a member of OWL class $propertyObjectClassConstraint" - ) - } - } yield () - - case linkUpdate: LinkUpdateV1 => - // We're creating a link to an existing resource. Check that it belongs to a - // suitable class. - for { - checkTargetClassResponse <- checkResourceClass( - resourceIri = linkUpdate.targetResourceIri, - owlClass = propertyObjectClassConstraint, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ).mapTo[ResourceCheckClassResponseV1] - - _ = if (!checkTargetClassResponse.isInClass) { - throw OntologyConstraintException( - s"Resource ${linkUpdate.targetResourceIri} cannot be the target of property $propertyIri, because it is not a member of OWL class $propertyObjectClassConstraint" - ) - } - } yield () - - case otherValue => - // We're creating an ordinary value. Check that its type is valid for the property's - // knora-base:objectClassConstraint. - valueUtilV1.checkValueTypeForPropertyObjectClassConstraint( - propertyIri = propertyIri, - propertyObjectClassConstraint = propertyObjectClassConstraint, - valueType = otherValue.valueTypeIri, - responderManager = responderManager, - userProfile = userProfile - ) - } - } - } - } + values.foldLeft(Vector.empty[Future[Unit]]) { + case (acc, (propertyIri, valuesWithComments)) => + val propertyInfo = + propertyInfoMap.getOrElse( + propertyIri, + throw NotFoundException( + s"Property not found: $propertyIri" + ) + ) + val propertyObjectClassConstraint = + propertyInfo + .getPredicateObject( + OntologyConstants.KnoraBase.ObjectClassConstraint + ) + .getOrElse { + throw InconsistentRepositoryDataException( + s"Property $propertyIri has no knora-base:objectClassConstraint" + ) + } + + acc ++ valuesWithComments.map { + valueV1WithComment: CreateValueV1WithComment => + valueV1WithComment.updateValueV1 match { + case LinkToClientIDUpdateV1(targetClientID) => + // We're creating a link to a resource that doesn't exist yet, because it + // will be created in the same transaction. Check that it will belong to a + // suitable class. + val checkSubClassRequest = CheckSubClassRequestV1( + subClassIri = + clientResourceIDsToResourceClasses( + targetClientID + ), + superClassIri = propertyObjectClassConstraint, + userProfile = userProfile + ) + + for { + subClassResponse <- + (responderManager ? checkSubClassRequest) + .mapTo[CheckSubClassResponseV1] + + _ = if (!subClassResponse.isSubClass) { + throw OntologyConstraintException( + s"Resource $targetClientID cannot be the target of property $propertyIri, because it is not a member of OWL class $propertyObjectClassConstraint" + ) + } + } yield () + + case linkUpdate: LinkUpdateV1 => + // We're creating a link to an existing resource. Check that it belongs to a + // suitable class. + for { + checkTargetClassResponse <- + checkResourceClass( + resourceIri = linkUpdate.targetResourceIri, + owlClass = propertyObjectClassConstraint, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ).mapTo[ResourceCheckClassResponseV1] + + _ = if (!checkTargetClassResponse.isInClass) { + throw OntologyConstraintException( + s"Resource ${linkUpdate.targetResourceIri} cannot be the target of property $propertyIri, because it is not a member of OWL class $propertyObjectClassConstraint" + ) + } + } yield () + + case otherValue => + // We're creating an ordinary value. Check that its type is valid for the property's + // knora-base:objectClassConstraint. + valueUtilV1 + .checkValueTypeForPropertyObjectClassConstraint( + propertyIri = propertyIri, + propertyObjectClassConstraint = + propertyObjectClassConstraint, + valueType = otherValue.valueTypeIri, + responderManager = responderManager, + userProfile = userProfile + ) + } + } + } + } // Check that the resource class has a suitable cardinality for each submitted value. _ = values.foreach { case (propertyIri, valuesForProperty) => - val cardinalityInfo = resourceClassInfo.knoraResourceCardinalities.getOrElse( - propertyIri, - throw OntologyConstraintException( - s"Resource class $resourceClassIri has no cardinality for property $propertyIri" - ) - ) + val cardinalityInfo = resourceClassInfo.knoraResourceCardinalities.getOrElse( + propertyIri, + throw OntologyConstraintException( + s"Resource class $resourceClassIri has no cardinality for property $propertyIri" + ) + ) - if ( - (cardinalityInfo.cardinality == Cardinality.MayHaveOne || cardinalityInfo.cardinality == Cardinality.MustHaveOne) && valuesForProperty.size > 1 - ) { - throw OntologyConstraintException( - s"Resource class $resourceClassIri does not allow more than one value for property $propertyIri" - ) - } - } + if ( + (cardinalityInfo.cardinality == Cardinality.MayHaveOne || cardinalityInfo.cardinality == Cardinality.MustHaveOne) && valuesForProperty.size > 1 + ) { + throw OntologyConstraintException( + s"Resource class $resourceClassIri does not allow more than one value for property $propertyIri" + ) + } + } // Check that no required values are missing. requiredProps: Set[IRI] = resourceClassInfo.knoraResourceCardinalities.filter { case (_, cardinalityInfo) => - cardinalityInfo.cardinality == Cardinality.MustHaveOne || cardinalityInfo.cardinality == Cardinality.MustHaveSome - }.keySet -- resourceClassInfo.linkValueProperties -- resourceClassInfo.fileValueProperties // exclude link value and file value properties from checking + cardinalityInfo.cardinality == Cardinality.MustHaveOne || cardinalityInfo.cardinality == Cardinality.MustHaveSome + }.keySet -- resourceClassInfo.linkValueProperties -- resourceClassInfo.fileValueProperties // exclude link value and file value properties from checking submittedPropertyIris = values.keySet _ = if (!requiredProps.subsetOf(submittedPropertyIris)) { - val missingProps = (requiredProps -- submittedPropertyIris).mkString(", ") - throw OntologyConstraintException( - s"Values were not submitted for the following property or properties, which are required by resource class $resourceClassIri: $missingProps" - ) - } + val missingProps = (requiredProps -- submittedPropertyIris).mkString(", ") + throw OntologyConstraintException( + s"Values were not submitted for the following property or properties, which are required by resource class $resourceClassIri: $missingProps" + ) + } // check if a file value is required by the ontology fileValues: Option[(IRI, Vector[CreateValueV1WithComment])] = @@ -1991,19 +2126,19 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo for { // Ask the values responder for the SPARQL statements that are needed to create the values. generateSparqlForValuesRequest <- Future( - GenerateSparqlToCreateMultipleValuesRequestV1( - projectIri = projectIri, - resourceIri = resourceIri, - resourceClassIri = resourceClassIri, - defaultPropertyAccessPermissions = defaultPropertyAccessPermissions, - values = values ++ fileValues, - clientResourceIDsToResourceIris = clientResourceIDsToResourceIris, - creationDate = creationDate, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile, - apiRequestID = apiRequestID - ) - ) + GenerateSparqlToCreateMultipleValuesRequestV1( + projectIri = projectIri, + resourceIri = resourceIri, + resourceClassIri = resourceClassIri, + defaultPropertyAccessPermissions = defaultPropertyAccessPermissions, + values = values ++ fileValues, + clientResourceIDsToResourceIris = clientResourceIDsToResourceIris, + creationDate = creationDate, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile, + apiRequestID = apiRequestID + ) + ) generateSparqlForValuesResponse: GenerateSparqlToCreateMultipleValuesResponseV1 <- (responderManager ? generateSparqlForValuesRequest) @@ -2059,31 +2194,31 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo // Verify that the resource was created. for { createdResourcesSparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getCreatedResource( - resourceIri = resourceIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getCreatedResource( + resourceIri = resourceIri + ) + .toString() + ) createdResourceResponse <- (storeManager ? SparqlSelectRequest(createdResourcesSparql)).mapTo[SparqlSelectResult] _ = if (createdResourceResponse.results.bindings.isEmpty) { - log.error( - s"Attempted a SPARQL update to create a new resource, but it inserted no rows:\n\n$createNewResourceSparql" - ) - throw UpdateNotPerformedException( - s"Resource $resourceIri was not created. Please report this as a possible bug." - ) - } + log.error( + s"Attempted a SPARQL update to create a new resource, but it inserted no rows:\n\n$createNewResourceSparql" + ) + throw UpdateNotPerformedException( + s"Resource $resourceIri was not created. Please report this as a possible bug." + ) + } // Verify that all the requested values were created. verifyCreateValuesRequest = VerifyMultipleValueCreationRequestV1( - resourceIri = resourceIri, - unverifiedValues = generateSparqlForValuesResponse.unverifiedValues, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + resourceIri = resourceIri, + unverifiedValues = generateSparqlForValuesResponse.unverifiedValues, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) verifyMultipleValueCreationResponse: VerifyMultipleValueCreationResponseV1 <- (responderManager ? verifyCreateValuesRequest) @@ -2107,10 +2242,10 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo } apiResponse: ResourceCreateResponseV1 = ResourceCreateResponseV1( - results = resourceCreateValueResponses, - res_id = resourceIri, - projectADM = projectADM - ) + results = resourceCreateValueResponses, + res_id = resourceIri, + projectADM = projectADM + ) } yield apiResponse /** @@ -2147,18 +2282,19 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo val updateFuture = for { // Get ontology information about the resource class and its properties. resourceClassEntityInfoResponse: EntityInfoGetResponseV1 <- (responderManager ? EntityInfoGetRequestV1( - resourceClassIris = Set(resourceClassIri), - propertyIris = Set.empty[IRI], - userProfile = requestingUser - )).mapTo[EntityInfoGetResponseV1] + resourceClassIris = Set(resourceClassIri), + propertyIris = Set.empty[IRI], + userProfile = requestingUser + )).mapTo[EntityInfoGetResponseV1] resourceClassInfo = resourceClassEntityInfoResponse.resourceClassInfoMap(resourceClassIri) - propertyEntityInfoResponse: EntityInfoGetResponseV1 <- (responderManager ? EntityInfoGetRequestV1( - resourceClassIris = Set.empty[IRI], - propertyIris = resourceClassInfo.knoraResourceCardinalities.keySet, - userProfile = requestingUser - )).mapTo[EntityInfoGetResponseV1] + propertyEntityInfoResponse: EntityInfoGetResponseV1 <- + (responderManager ? EntityInfoGetRequestV1( + resourceClassIris = Set.empty[IRI], + propertyIris = resourceClassInfo.knoraResourceCardinalities.keySet, + userProfile = requestingUser + )).mapTo[EntityInfoGetResponseV1] propertyInfoMap = propertyEntityInfoResponse.propertyInfoMap @@ -2191,19 +2327,19 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo } defaultPropertyAccessPermissionsIterable: Iterable[(IRI, String)] <- Future.sequence( - defaultPropertyAccessPermissionsFutures - ) + defaultPropertyAccessPermissionsFutures + ) defaultPropertyAccessPermissions = defaultPropertyAccessPermissionsIterable.toMap fileValues <- checkResource( - resourceClassIri = resourceClassIri, - resourceClassInfo = resourceClassInfo, - propertyInfoMap = propertyInfoMap, - values = values, - convertedFile = file, - featureFactoryConfig = featureFactoryConfig, - userProfile = requestingUser - ) + resourceClassIri = resourceClassIri, + resourceClassInfo = resourceClassInfo, + propertyInfoMap = propertyInfoMap, + values = values, + convertedFile = file, + featureFactoryConfig = featureFactoryConfig, + userProfile = requestingUser + ) // Everything looks OK, so we can create the resource and its values. @@ -2226,36 +2362,37 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo ) resourcesToCreate: Seq[SparqlTemplateResourceToCreate] = Seq( - SparqlTemplateResourceToCreate( - resourceIri = resourceIri, - permissions = defaultResourceClassAccessPermissions, - sparqlForValues = generateSparqlForValuesResponse.insertSparql, - resourceClassIri = resourceClassIri, - resourceLabel = label, - resourceCreationDate = creationDate - ) - ) + SparqlTemplateResourceToCreate( + resourceIri = resourceIri, + permissions = defaultResourceClassAccessPermissions, + sparqlForValues = + generateSparqlForValuesResponse.insertSparql, + resourceClassIri = resourceClassIri, + resourceLabel = label, + resourceCreationDate = creationDate + ) + ) createNewResourceSparql = generateSparqlForNewResources( - resourcesToCreate = resourcesToCreate, - projectIri = projectADM.id, - namedGraph = namedGraph, - creatorIri = creatorIri - ) + resourcesToCreate = resourcesToCreate, + projectIri = projectADM.id, + namedGraph = namedGraph, + creatorIri = creatorIri + ) // Do the update. createResourceResponse <- (storeManager ? SparqlUpdateRequest(createNewResourceSparql)) - .mapTo[SparqlUpdateResponse] + .mapTo[SparqlUpdateResponse] apiResponse <- verifyResourceCreated( - resourceIri = resourceIri, - creatorIri = creatorIri, - createNewResourceSparql = createNewResourceSparql, - generateSparqlForValuesResponse = generateSparqlForValuesResponse, - projectADM = projectADM, - featureFactoryConfig = featureFactoryConfig, - userProfile = requestingUser - ) + resourceIri = resourceIri, + creatorIri = creatorIri, + createNewResourceSparql = createNewResourceSparql, + generateSparqlForValuesResponse = generateSparqlForValuesResponse, + projectADM = projectADM, + featureFactoryConfig = featureFactoryConfig, + userProfile = requestingUser + ) } yield apiResponse doSipiPostUpdateForResources( @@ -2291,16 +2428,18 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo // Get user's IRI and don't allow anonymous users to create resources. userIri: IRI <- Future { - if (userProfile.isAnonymousUser) { - throw ForbiddenException("Anonymous users aren't allowed to create resources") - } else { - userProfile.id - } - } + if (userProfile.isAnonymousUser) { + throw ForbiddenException("Anonymous users aren't allowed to create resources") + } else { + userProfile.id + } + } _ = if (resourceClassIri == OntologyConstants.KnoraBase.Resource) { - throw BadRequestException(s"Instances of knora-base:Resource cannot be created, only instances of subclasses") - } + throw BadRequestException( + s"Instances of knora-base:Resource cannot be created, only instances of subclasses" + ) + } // Get project info projectResponse <- { @@ -2315,64 +2454,69 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo resourceProjectIri: IRI = projectResponse.project.id - _ = if ( - resourceProjectIri == OntologyConstants.KnoraAdmin.SystemProject || resourceProjectIri == OntologyConstants.KnoraAdmin.DefaultSharedOntologiesProject - ) { - throw BadRequestException(s"Resources cannot be created in project $resourceProjectIri") - } + _ = + if ( + resourceProjectIri == OntologyConstants.KnoraAdmin.SystemProject || resourceProjectIri == OntologyConstants.KnoraAdmin.DefaultSharedOntologiesProject + ) { + throw BadRequestException(s"Resources cannot be created in project $resourceProjectIri") + } // Ensure that the resource class isn't from a non-shared ontology in another project. resourceClassOntologyIri: SmartIri = resourceClassIri.toSmartIri.getOntologyFromEntity readOntologyMetadataV2: ReadOntologyMetadataV2 <- (responderManager ? OntologyMetadataGetByIriRequestV2( - Set(resourceClassOntologyIri), - userProfile - )).mapTo[ReadOntologyMetadataV2] - ontologyMetadata: OntologyMetadataV2 = readOntologyMetadataV2.ontologies.headOption - .getOrElse(throw BadRequestException(s"Ontology $resourceClassOntologyIri not found")) - ontologyProjectIri: IRI = ontologyMetadata.projectIri - .getOrElse(throw InconsistentRepositoryDataException(s"Ontology $resourceClassOntologyIri has no project")) - .toString + Set(resourceClassOntologyIri), + userProfile + )).mapTo[ReadOntologyMetadataV2] + ontologyMetadata: OntologyMetadataV2 = + readOntologyMetadataV2.ontologies.headOption + .getOrElse(throw BadRequestException(s"Ontology $resourceClassOntologyIri not found")) + ontologyProjectIri: IRI = + ontologyMetadata.projectIri + .getOrElse(throw InconsistentRepositoryDataException(s"Ontology $resourceClassOntologyIri has no project")) + .toString - _ = if ( - resourceProjectIri != ontologyProjectIri && !(ontologyMetadata.ontologyIri.isKnoraBuiltInDefinitionIri || ontologyMetadata.ontologyIri.isKnoraSharedDefinitionIri) - ) { - throw BadRequestException( - s"Cannot create a resource in project $resourceProjectIri with resource class $resourceClassIri, which is defined in a non-shared ontology in another project" - ) - } + _ = + if ( + resourceProjectIri != ontologyProjectIri && !(ontologyMetadata.ontologyIri.isKnoraBuiltInDefinitionIri || ontologyMetadata.ontologyIri.isKnoraSharedDefinitionIri) + ) { + throw BadRequestException( + s"Cannot create a resource in project $resourceProjectIri with resource class $resourceClassIri, which is defined in a non-shared ontology in another project" + ) + } - namedGraph = StringFormatter.getGeneralInstance.projectDataNamedGraphV2(projectResponse.project) + namedGraph = StringFormatter.getGeneralInstance.projectDataNamedGraphV2(projectResponse.project) resourceIri: IRI = stringFormatter.makeRandomResourceIri(projectResponse.project.shortcode) // Check user's PermissionProfile (part of UserADM) to see if the user has the permission to // create a new resource in the given project. - _ = if ( - !userProfile.permissions.hasPermissionFor(ResourceCreateOperation(resourceClassIri), resourceProjectIri, None) - ) { - throw ForbiddenException( - s"User $userIri does not have permissions to create a resource in project $resourceProjectIri" - ) - } + _ = + if ( + !userProfile.permissions.hasPermissionFor(ResourceCreateOperation(resourceClassIri), resourceProjectIri, None) + ) { + throw ForbiddenException( + s"User $userIri does not have permissions to create a resource in project $resourceProjectIri" + ) + } result: ResourceCreateResponseV1 <- IriLocker.runWithIriLock( - apiRequestID, - resourceIri, - () => - createResourceAndCheck( - resourceClassIri = resourceClassIri, - projectADM = projectResponse.project, - label = label, - resourceIri = resourceIri, - values = values, - file = file, - creatorIri = userIri, - namedGraph = namedGraph, - featureFactoryConfig = featureFactoryConfig, - requestingUser = userProfile, - apiRequestID = apiRequestID - ) - ) + apiRequestID, + resourceIri, + () => + createResourceAndCheck( + resourceClassIri = resourceClassIri, + projectADM = projectResponse.project, + label = label, + resourceIri = resourceIri, + values = values, + file = file, + creatorIri = userIri, + namedGraph = namedGraph, + featureFactoryConfig = featureFactoryConfig, + requestingUser = userProfile, + apiRequestID = apiRequestID + ) + ) } yield result /** @@ -2387,22 +2531,22 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo for { // Check that the user has permission to delete the resource. (permissionCode, resourceInfo) <- getResourceInfoV1( - resourceIri = resourceDeleteRequest.resourceIri, - featureFactoryConfig = resourceDeleteRequest.featureFactoryConfig, - userProfile = resourceDeleteRequest.userADM, - queryOntology = false - ) + resourceIri = resourceDeleteRequest.resourceIri, + featureFactoryConfig = resourceDeleteRequest.featureFactoryConfig, + userProfile = resourceDeleteRequest.userADM, + queryOntology = false + ) _ = if ( - !PermissionUtilADM.impliesPermissionCodeV1( - userHasPermissionCode = permissionCode, - userNeedsPermission = OntologyConstants.KnoraBase.DeletePermission - ) - ) { - throw ForbiddenException( - s"User $userIri does not have permission to mark resource ${resourceDeleteRequest.resourceIri} as deleted" - ) - } + !PermissionUtilADM.impliesPermissionCodeV1( + userHasPermissionCode = permissionCode, + userNeedsPermission = OntologyConstants.KnoraBase.DeletePermission + ) + ) { + throw ForbiddenException( + s"User $userIri does not have permission to mark resource ${resourceDeleteRequest.resourceIri} as deleted" + ) + } projectInfoResponse <- { responderManager ? ProjectInfoByIRIGetRequestV1( @@ -2417,58 +2561,58 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo // Create update sparql string sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .deleteResource( - dataNamedGraph = - StringFormatter.getGeneralInstance.projectDataNamedGraphV1(projectInfoResponse.project_info), - resourceIri = resourceDeleteRequest.resourceIri, - maybeDeleteComment = resourceDeleteRequest.deleteComment, - currentTime = currentTime, - requestingUser = resourceDeleteRequest.userADM.id - ) - .toString() + .deleteResource( + dataNamedGraph = StringFormatter.getGeneralInstance + .projectDataNamedGraphV1(projectInfoResponse.project_info), + resourceIri = resourceDeleteRequest.resourceIri, + maybeDeleteComment = resourceDeleteRequest.deleteComment, + currentTime = currentTime, + requestingUser = resourceDeleteRequest.userADM.id + ) + .toString() // Do the update. sparqlUpdateResponse <- (storeManager ? SparqlUpdateRequest(sparqlUpdate)).mapTo[SparqlUpdateResponse] // Check whether the update succeeded. sparqlQuery = org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .checkResourceDeletion( - resourceIri = resourceDeleteRequest.resourceIri - ) - .toString() + .checkResourceDeletion( + resourceIri = resourceDeleteRequest.resourceIri + ) + .toString() sparqlSelectResponse <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] - rows = sparqlSelectResponse.results.bindings + rows = sparqlSelectResponse.results.bindings _ = if ( - rows.isEmpty || !stringFormatter.optionStringToBoolean( - rows.head.rowMap.get("isDeleted"), - throw InconsistentRepositoryDataException( - s"Invalid boolean for isDeleted: ${rows.head.rowMap.get("isDeleted")}" - ) - ) - ) { - throw UpdateNotPerformedException( - s"Resource ${resourceDeleteRequest.resourceIri} was not marked as deleted. Please report this as a possible bug." - ) - } + rows.isEmpty || !stringFormatter.optionStringToBoolean( + rows.head.rowMap.get("isDeleted"), + throw InconsistentRepositoryDataException( + s"Invalid boolean for isDeleted: ${rows.head.rowMap.get("isDeleted")}" + ) + ) + ) { + throw UpdateNotPerformedException( + s"Resource ${resourceDeleteRequest.resourceIri} was not marked as deleted. Please report this as a possible bug." + ) + } } yield ResourceDeleteResponseV1(id = resourceDeleteRequest.resourceIri) for { // Don't allow anonymous users to delete resources. userIri <- Future { - if (resourceDeleteRequest.userADM.isAnonymousUser) { - throw ForbiddenException("Anonymous users aren't allowed to mark resources as deleted") - } else { - resourceDeleteRequest.userADM.id - } - } + if (resourceDeleteRequest.userADM.isAnonymousUser) { + throw ForbiddenException("Anonymous users aren't allowed to mark resources as deleted") + } else { + resourceDeleteRequest.userADM.id + } + } // Do the remaining pre-update checks and the update while holding an update lock on the resource. taskResult <- IriLocker.runWithIriLock( - resourceDeleteRequest.apiRequestID, - resourceDeleteRequest.resourceIri, - () => makeTaskFuture(userIri) - ) + resourceDeleteRequest.apiRequestID, + resourceDeleteRequest.resourceIri, + () => makeTaskFuture(userIri) + ) } yield taskResult } @@ -2490,26 +2634,26 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo for { // Check that the user has permission to view the resource. (permissionCode, resourceInfo) <- getResourceInfoV1( - resourceIri = resourceIri, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile, - queryOntology = false - ) + resourceIri = resourceIri, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile, + queryOntology = false + ) _ = if ( - !PermissionUtilADM.impliesPermissionCodeV1( - userHasPermissionCode = permissionCode, - userNeedsPermission = OntologyConstants.KnoraBase.RestrictedViewPermission - ) - ) { - throw ForbiddenException(s"User ${userProfile.id} does not have permission to view resource $resourceIri") - } + !PermissionUtilADM.impliesPermissionCodeV1( + userHasPermissionCode = permissionCode, + userNeedsPermission = OntologyConstants.KnoraBase.RestrictedViewPermission + ) + ) { + throw ForbiddenException(s"User ${userProfile.id} does not have permission to view resource $resourceIri") + } checkSubClassRequest = CheckSubClassRequestV1( - subClassIri = resourceInfo.restype_id, - superClassIri = owlClass, - userProfile = userProfile - ) + subClassIri = resourceInfo.restype_id, + superClassIri = owlClass, + userProfile = userProfile + ) subClassResponse <- (responderManager ? checkSubClassRequest).mapTo[CheckSubClassResponseV1] @@ -2536,23 +2680,23 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo for { // get the resource's permissions (permissionCode, resourceInfo) <- getResourceInfoV1( - resourceIri = resourceIri, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile, - queryOntology = false - ) + resourceIri = resourceIri, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile, + queryOntology = false + ) // check if the given user may change its label _ = if ( - !PermissionUtilADM.impliesPermissionCodeV1( - userHasPermissionCode = permissionCode, - userNeedsPermission = OntologyConstants.KnoraBase.ModifyPermission - ) - ) { - throw ForbiddenException( - s"User $userIri does not have permission to change the label of resource $resourceIri" - ) - } + !PermissionUtilADM.impliesPermissionCodeV1( + userHasPermissionCode = permissionCode, + userNeedsPermission = OntologyConstants.KnoraBase.ModifyPermission + ) + ) { + throw ForbiddenException( + s"User $userIri does not have permission to change the label of resource $resourceIri" + ) + } projectInfoResponse <- { responderManager ? ProjectInfoByIRIGetRequestV1( @@ -2570,13 +2714,13 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo // the user has sufficient permissions to change the resource's label sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .changeResourceLabel( - dataNamedGraph = namedGraph, - resourceIri = resourceIri, - label = label, - currentTime = currentTime - ) - .toString() + .changeResourceLabel( + dataNamedGraph = namedGraph, + resourceIri = resourceIri, + label = label, + currentTime = currentTime + ) + .toString() //_ = print(sparqlUpdate) @@ -2585,40 +2729,40 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo // Check whether the update succeeded. sparqlQuery = org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .checkResourceLabelChange( - resourceIri = resourceIri, - label = label - ) - .toString() + .checkResourceLabelChange( + resourceIri = resourceIri, + label = label + ) + .toString() sparqlSelectResponse <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] - rows = sparqlSelectResponse.results.bindings + rows = sparqlSelectResponse.results.bindings // we expect exactly one row to be returned if the label was updated correctly in the data. _ = if (rows.length != 1) { - throw UpdateNotPerformedException( - s"The label of the resource $resourceIri was not updated correctly. Please report this as a possible bug." - ) - } + throw UpdateNotPerformedException( + s"The label of the resource $resourceIri was not updated correctly. Please report this as a possible bug." + ) + } } yield ChangeResourceLabelResponseV1(res_id = resourceIri, label = label) for { // Don't allow anonymous users to change a resource's label. userIri <- Future { - if (userProfile.isAnonymousUser) { - throw ForbiddenException("Anonymous users aren't allowed to change a resource's label") - } else { - userProfile.id - } - } + if (userProfile.isAnonymousUser) { + throw ForbiddenException("Anonymous users aren't allowed to change a resource's label") + } else { + userProfile.id + } + } // Do the remaining pre-update checks and the update while holding an update lock on the resource. taskResult <- IriLocker.runWithIriLock( - apiRequestID, - resourceIri, - () => makeTaskFuture(userIri) - ) + apiRequestID, + resourceIri, + () => makeTaskFuture(userIri) + ) } yield taskResult } @@ -2645,22 +2789,22 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo ): Future[(Option[Int], ResourceInfoV1)] = for { sparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getResourceInfo( - resourceIri = resourceIri - ) - .toString() - ) - resInfoResponse <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getResourceInfo( + resourceIri = resourceIri + ) + .toString() + ) + resInfoResponse <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] resInfoResponseRows = resInfoResponse.results.bindings resInfo: (Option[Int], ResourceInfoV1) <- makeResourceInfoV1( - resourceIri = resourceIri, - resInfoResponseRows = resInfoResponseRows, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile, - queryOntology = queryOntology - ) + resourceIri = resourceIri, + resInfoResponseRows = resInfoResponseRows, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile, + queryOntology = queryOntology + ) } yield resInfo /** @@ -2679,28 +2823,28 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo for { // get resource class of the specified resource resclassSparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getResourceClass( - resourceIri = resourceIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getResourceClass( + resourceIri = resourceIri + ) + .toString() + ) resclassQueryResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(resclassSparqlQuery)) - .mapTo[SparqlSelectResult] + .mapTo[SparqlSelectResult] resclass = resclassQueryResponse.results.bindings.headOption - .getOrElse(throw InconsistentRepositoryDataException(s"No resource class given for $resourceIri")) + .getOrElse(throw InconsistentRepositoryDataException(s"No resource class given for $resourceIri")) properties: Seq[PropertyV1] <- getResourceProperties( - resourceIri = resourceIri, - maybeResourceTypeIri = Some(resclass.rowMap("resourceClass")), - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + resourceIri = resourceIri, + maybeResourceTypeIri = Some(resclass.rowMap("resourceClass")), + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) propertiesGetV1: Seq[PropertyGetV1] = properties.map { prop => - convertPropertyV1toPropertyGetV1(prop) - } + convertPropertyV1toPropertyGetV1(prop) + } } yield PropertiesGetResponseV1(PropsGetV1(propertiesGetV1)) @@ -2732,47 +2876,49 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo resourceEntityInfoMap: Map[IRI, ClassInfoV1], propsAndCardinalities: Map[IRI, KnoraCardinalityInfo] ) <- maybeResourceTypeIri match { - case Some(resourceTypeIri) => - val propertyEntityIris: Set[IRI] = - groupedPropsByType.groupedOrdinaryValueProperties.groupedProperties.keySet ++ groupedPropsByType.groupedLinkProperties.groupedProperties.keySet - val resourceEntityIris: Set[IRI] = Set(resourceTypeIri) - - for { - entityInfoResponse <- (responderManager ? EntityInfoGetRequestV1( - resourceClassIris = resourceEntityIris, - propertyIris = propertyEntityIris, - userProfile = userProfile - )) - .mapTo[EntityInfoGetResponseV1] - resourceEntityInfoMap: Map[IRI, ClassInfoV1] = entityInfoResponse.resourceClassInfoMap - propertyInfoMap: Map[IRI, PropertyInfoV1] = entityInfoResponse.propertyInfoMap - - resourceTypeEntityInfo = resourceEntityInfoMap(resourceTypeIri) - - // all properties and their cardinalities for the queried resource's type, except the ones that point to LinkValue objects - propsAndCardinalities: Map[IRI, KnoraCardinalityInfo] = - resourceTypeEntityInfo.knoraResourceCardinalities.filterNot { case (propertyIri, _) => - resourceTypeEntityInfo.linkValueProperties(propertyIri) - } - } yield (propertyInfoMap, resourceEntityInfoMap, propsAndCardinalities) - - case None => - Future((Map.empty[IRI, PropertyInfoV1], Map.empty[IRI, ClassInfoV1], Map.empty[IRI, KnoraCardinalityInfo])) - } + case Some(resourceTypeIri) => + val propertyEntityIris: Set[IRI] = + groupedPropsByType.groupedOrdinaryValueProperties.groupedProperties.keySet ++ groupedPropsByType.groupedLinkProperties.groupedProperties.keySet + val resourceEntityIris: Set[IRI] = Set(resourceTypeIri) + + for { + entityInfoResponse <- (responderManager ? EntityInfoGetRequestV1( + resourceClassIris = resourceEntityIris, + propertyIris = propertyEntityIris, + userProfile = userProfile + )) + .mapTo[EntityInfoGetResponseV1] + resourceEntityInfoMap: Map[IRI, ClassInfoV1] = entityInfoResponse.resourceClassInfoMap + propertyInfoMap: Map[IRI, PropertyInfoV1] = entityInfoResponse.propertyInfoMap + + resourceTypeEntityInfo = resourceEntityInfoMap(resourceTypeIri) + + // all properties and their cardinalities for the queried resource's type, except the ones that point to LinkValue objects + propsAndCardinalities: Map[IRI, KnoraCardinalityInfo] = + resourceTypeEntityInfo.knoraResourceCardinalities.filterNot { case (propertyIri, _) => + resourceTypeEntityInfo.linkValueProperties(propertyIri) + } + } yield (propertyInfoMap, resourceEntityInfoMap, propsAndCardinalities) + + case None => + Future( + (Map.empty[IRI, PropertyInfoV1], Map.empty[IRI, ClassInfoV1], Map.empty[IRI, KnoraCardinalityInfo]) + ) + } projectShortcode = resourceIri.toSmartIri.getProjectCode - .getOrElse(throw InconsistentRepositoryDataException(s"Invalid resource IRI: $resourceIri")) + .getOrElse(throw InconsistentRepositoryDataException(s"Invalid resource IRI: $resourceIri")) queryResult <- queryResults2PropertyV1s( - containingResourceIri = resourceIri, - projectShortcode = projectShortcode, - groupedPropertiesByType = groupedPropsByType, - propertyInfoMap = propertyInfoMap, - resourceEntityInfoMap = resourceEntityInfoMap, - propsAndCardinalities = propsAndCardinalities, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + containingResourceIri = resourceIri, + projectShortcode = projectShortcode, + groupedPropertiesByType = groupedPropsByType, + propertyInfoMap = propertyInfoMap, + resourceEntityInfoMap = resourceEntityInfoMap, + propsAndCardinalities = propsAndCardinalities, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) } yield queryResult /** @@ -2803,115 +2949,129 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo for { // Extract the permission-relevant assertions from the query results. - permissionRelevantAssertions: Seq[(IRI, IRI)] <- Future( - PermissionUtilADM.filterPermissionRelevantAssertions( - resInfoResponseRows.map(row => (row.rowMap("prop"), row.rowMap("obj"))) + permissionRelevantAssertions: Seq[(IRI, IRI)] <- + Future( + PermissionUtilADM.filterPermissionRelevantAssertions( + resInfoResponseRows.map(row => (row.rowMap("prop"), row.rowMap("obj"))) + ) ) - ) - maybeResourceProjectStatement: Option[(IRI, IRI)] = permissionRelevantAssertions.find { - case (subject, predicate) => subject == OntologyConstants.KnoraBase.AttachedToProject - } + maybeResourceProjectStatement: Option[(IRI, IRI)] = + permissionRelevantAssertions.find { case (subject, predicate) => + subject == OntologyConstants.KnoraBase.AttachedToProject + } - resourceProject = maybeResourceProjectStatement - .getOrElse( - throw InconsistentRepositoryDataException(s"Resource $resourceIri has no knora-base:attachedToProject") - ) - ._2 - projectShortcode: String = resourceIri.toSmartIri.getProjectCode - .getOrElse(throw InconsistentRepositoryDataException(s"Invalid resource IRI $resourceIri")) + resourceProject = + maybeResourceProjectStatement + .getOrElse( + throw InconsistentRepositoryDataException(s"Resource $resourceIri has no knora-base:attachedToProject") + ) + ._2 + projectShortcode: String = + resourceIri.toSmartIri.getProjectCode + .getOrElse(throw InconsistentRepositoryDataException(s"Invalid resource IRI $resourceIri")) // Get the rows describing file values from the query results, grouped by file value IRI. - fileValueGroupedRows: Seq[(IRI, Seq[VariableResultsRow])] = resInfoResponseRows - .filter(row => - stringFormatter.optionStringToBoolean( - row.rowMap.get("isFileValue"), - throw InconsistentRepositoryDataException( - s"Invalid boolean for isFileValue: ${row.rowMap.get("isFileValue")}" + fileValueGroupedRows: Seq[(IRI, Seq[VariableResultsRow])] = + resInfoResponseRows + .filter(row => + stringFormatter.optionStringToBoolean( + row.rowMap.get("isFileValue"), + throw InconsistentRepositoryDataException( + s"Invalid boolean for isFileValue: ${row.rowMap.get("isFileValue")}" + ) ) ) - ) - .groupBy(row => row.rowMap("obj")) - .toVector + .groupBy(row => row.rowMap("obj")) + .toVector // Convert the file value rows to ValueProps objects, and filter out the ones that the user doesn't have permission to see. valuePropsForFileValues: Seq[(IRI, ValueProps)] = fileValueGroupedRows.map { - case (fileValueIri, fileValueRows) => - (fileValueIri, valueUtilV1.createValueProps(fileValueIri, fileValueRows)) - }.filter { case (fileValueIri, fileValueProps) => - val permissionCode = PermissionUtilADM.getUserPermissionWithValuePropsV1( - valueIri = fileValueIri, - valueProps = fileValueProps, - entityProject = Some(resourceProject), - userProfile = userProfileV1 - ) - PermissionUtilADM.impliesPermissionCodeV1( - userHasPermissionCode = permissionCode, - userNeedsPermission = OntologyConstants.KnoraBase.RestrictedViewPermission - ) - } + case (fileValueIri, fileValueRows) => + ( + fileValueIri, + valueUtilV1.createValueProps( + fileValueIri, + fileValueRows + ) + ) + }.filter { case (fileValueIri, fileValueProps) => + val permissionCode = + PermissionUtilADM.getUserPermissionWithValuePropsV1( + valueIri = fileValueIri, + valueProps = fileValueProps, + entityProject = Some(resourceProject), + userProfile = userProfileV1 + ) + PermissionUtilADM.impliesPermissionCodeV1( + userHasPermissionCode = permissionCode, + userNeedsPermission = + OntologyConstants.KnoraBase.RestrictedViewPermission + ) + } // Convert the ValueProps objects into FileValueV1 objects fileValuesWithFuture: Seq[Future[FileValueV1]] = valuePropsForFileValues.map { - case (fileValueIri, fileValueProps) => - for { - valueV1 <- valueUtilV1.makeValueV1( - valueProps = fileValueProps, - projectShortcode = projectShortcode, - responderManager = responderManager, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) - - } yield valueV1 match { - case fileValueV1: FileValueV1 => fileValueV1 - case otherValueV1 => - throw InconsistentRepositoryDataException( - s"Value $fileValueIri is not a knora-base:FileValue, it is an instance of ${otherValueV1.valueTypeIri}" - ) - } - } + case (fileValueIri, fileValueProps) => + for { + valueV1 <- valueUtilV1.makeValueV1( + valueProps = fileValueProps, + projectShortcode = projectShortcode, + responderManager = responderManager, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) + + } yield valueV1 match { + case fileValueV1: FileValueV1 => fileValueV1 + case otherValueV1 => + throw InconsistentRepositoryDataException( + s"Value $fileValueIri is not a knora-base:FileValue, it is an instance of ${otherValueV1.valueTypeIri}" + ) + } + } fileValues: Seq[FileValueV1] <- Future.sequence(fileValuesWithFuture) // Generate a IIIF preview URL from the full-size image. fullSizeImageFileValues: Seq[StillImageFileValueV1] = fileValues.collect { - case fileValue: StillImageFileValueV1 => fileValue - } + case fileValue: StillImageFileValueV1 => fileValue + } - preview: Option[LocationV1] = fullSizeImageFileValues.headOption.map { - fullSizeImageFileValue: StillImageFileValueV1 => + preview: Option[LocationV1] = + fullSizeImageFileValues.headOption.map { fullSizeImageFileValue: StillImageFileValueV1 => valueUtilV1.fileValueV12LocationV1(fullSizeImageFileValueToPreview(fullSizeImageFileValue)) - } + } // Convert the file values into LocationV1 objects as required by Knora API v1. locations: Seq[LocationV1] = preview.toVector ++ fileValues.flatMap { fileValueV1 => - createMultipleImageResolutions(fileValueV1).map(oneResolution => - valueUtilV1.fileValueV12LocationV1(oneResolution) - ) - } + createMultipleImageResolutions(fileValueV1).map(oneResolution => + valueUtilV1.fileValueV12LocationV1(oneResolution) + ) + } // Get the user's permission on the resource. userPermission = PermissionUtilADM.getUserPermissionFromAssertionsV1( - entityIri = resourceIri, - assertions = permissionRelevantAssertions, - userProfile = userProfileV1 - ) + entityIri = resourceIri, + assertions = permissionRelevantAssertions, + userProfile = userProfileV1 + ) // group the SPARQL results by the predicate "prop" and map each row to a Seq of objects "obj", etc. (getting rid of VariableResultsRow). - groupedByPredicateToWrap: Map[IRI, Seq[Map[String, String]]] = resInfoResponseRows - .groupBy(row => row.rowMap("prop")) - .map { case (predicate: IRI, rows: Seq[VariableResultsRow]) => - (predicate, rows.map(_.rowMap - "prop")) - } + groupedByPredicateToWrap: Map[IRI, Seq[Map[String, String]]] = + resInfoResponseRows + .groupBy(row => row.rowMap("prop")) + .map { case (predicate: IRI, rows: Seq[VariableResultsRow]) => + (predicate, rows.map(_.rowMap - "prop")) + } groupedByPredicate = new ErrorHandlingMap( - groupedByPredicateToWrap, - { key: IRI => - s"Resource $resourceIri has no $key" - } - ) + groupedByPredicateToWrap, + { key: IRI => + s"Resource $resourceIri has no $key" + } + ) // Query the ontology about the resource's OWL class. (restype_label, restype_description, restype_iconsrc) <- @@ -2920,43 +3080,44 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo for { entityInfoResponse <- (responderManager ? EntityInfoGetRequestV1( - resourceClassIris = Set(resTypeIri), - userProfile = userProfile - )) - .mapTo[EntityInfoGetResponseV1] + resourceClassIris = Set(resTypeIri), + userProfile = userProfile + )) + .mapTo[EntityInfoGetResponseV1] entityInfo = entityInfoResponse.resourceClassInfoMap(resTypeIri) label = entityInfo.getPredicateObject( - predicateIri = OntologyConstants.Rdfs.Label, - preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) - ) + predicateIri = OntologyConstants.Rdfs.Label, + preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) + ) description = entityInfo.getPredicateObject( - predicateIri = OntologyConstants.Rdfs.Comment, - preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) - ) + predicateIri = OntologyConstants.Rdfs.Comment, + preferredLangs = Some(userProfile.lang, settings.fallbackLanguage) + ) iconsrc = entityInfo.getPredicateObject(OntologyConstants.KnoraBase.ResourceIcon) match { - case Some(resClassIcon) => Some(valueUtilV1.makeResourceClassIconURL(resTypeIri, resClassIcon)) - case _ => None - } + case Some(resClassIcon) => + Some(valueUtilV1.makeResourceClassIconURL(resTypeIri, resClassIcon)) + case _ => None + } } yield (label, description, iconsrc) } else { Future(None, None, None) } resourceInfo = ResourceInfoV1( - restype_id = groupedByPredicate(OntologyConstants.Rdf.Type).head("obj"), - firstproperty = Some(groupedByPredicate(OntologyConstants.Rdfs.Label).head("obj")), - preview = preview, // The first element of the list, or None if the list is empty - locations = if (locations.nonEmpty) Some(locations) else None, - locdata = locations.lastOption, - person_id = groupedByPredicate(OntologyConstants.KnoraBase.AttachedToUser).head("obj"), - project_id = groupedByPredicate(OntologyConstants.KnoraBase.AttachedToProject).head("obj"), - project_shortcode = projectShortcode, - restype_label = restype_label, - restype_name = Some(groupedByPredicate(OntologyConstants.Rdf.Type).head("obj")), - restype_description = restype_description, - restype_iconsrc = restype_iconsrc, - resclass_has_location = locations.nonEmpty - ) + restype_id = groupedByPredicate(OntologyConstants.Rdf.Type).head("obj"), + firstproperty = Some(groupedByPredicate(OntologyConstants.Rdfs.Label).head("obj")), + preview = preview, // The first element of the list, or None if the list is empty + locations = if (locations.nonEmpty) Some(locations) else None, + locdata = locations.lastOption, + person_id = groupedByPredicate(OntologyConstants.KnoraBase.AttachedToUser).head("obj"), + project_id = groupedByPredicate(OntologyConstants.KnoraBase.AttachedToProject).head("obj"), + project_shortcode = projectShortcode, + restype_label = restype_label, + restype_name = Some(groupedByPredicate(OntologyConstants.Rdf.Type).head("obj")), + restype_description = restype_description, + restype_iconsrc = restype_iconsrc, + resclass_has_location = locations.nonEmpty + ) } yield (userPermission, resourceInfo) } } @@ -2973,12 +3134,12 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo private def getGroupedProperties(resourceIri: IRI): Future[GroupedPropertiesByType] = for { sparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getResourcePropertiesAndValues( - resourceIri = resourceIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getResourcePropertiesAndValues( + resourceIri = resourceIri + ) + .toString() + ) // _ = println(sparqlQuery) resPropsResponse <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] @@ -2988,8 +3149,9 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo .partition(_.rowMap.get("isLinkProp").exists(_.toBoolean)) // Partition the rows with values into rows with ordinary values and rows with link values (reifications). - (rowsWithLinkValues: Seq[VariableResultsRow], rowsWithOrdinaryValues: Seq[VariableResultsRow]) = rowsWithValues - .partition(_.rowMap.get("isLinkValueProp").exists(_.toBoolean)) + (rowsWithLinkValues: Seq[VariableResultsRow], rowsWithOrdinaryValues: Seq[VariableResultsRow]) = + rowsWithValues + .partition(_.rowMap.get("isLinkValueProp").exists(_.toBoolean)) } yield valueUtilV1.createGroupedPropsByType( rowsWithOrdinaryValues = rowsWithOrdinaryValues, @@ -3119,19 +3281,20 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo for { // Convert the SPARQL query results to a ValueV1. valueV1 <- valueUtilV1.makeValueV1( - valueProps = valueProps, - projectShortcode = projectShortcode, - responderManager = responderManager, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + valueProps = valueProps, + projectShortcode = projectShortcode, + responderManager = responderManager, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) valPermission = PermissionUtilADM.getUserPermissionWithValuePropsV1( - valueIri = valObjIri, - valueProps = valueProps, - entityProject = None, // We don't need to specify this here, because it's in valueProps - userProfile = userProfileV1 - ) + valueIri = valObjIri, + valueProps = valueProps, + entityProject = + None, // We don't need to specify this here, because it's in valueProps + userProfile = userProfileV1 + ) predicates = valueProps.literalData @@ -3151,9 +3314,10 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo for { valueObjectsV1 <- Future.sequence(valueObjectsV1WithFuture) - valueObjectsV1Sorted = valueObjectsV1.toVector.sortBy( - _.order - ) // sort the values by their order given in the triplestore [[OntologyConstants.KnoraBase.ValueHasOrder]] + valueObjectsV1Sorted = + valueObjectsV1.toVector.sortBy( + _.order + ) // sort the values by their order given in the triplestore [[OntologyConstants.KnoraBase.ValueHasOrder]] // get all the values the user has at least viewing permissions on valueObjectListFiltered = valueObjectsV1Sorted.filter(_.valuePermission.nonEmpty) @@ -3163,11 +3327,11 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo // Make a PropertyV1 for the property. propertyV1 = makePropertyV1( - propertyIri = propertyIri, - propertyCardinality = propsAndCardinalities.get(propertyIri), - propertyEntityInfo = propertyEntityInfo, - valueObjects = valueObjectListFiltered - ) + propertyIri = propertyIri, + propertyCardinality = propsAndCardinalities.get(propertyIri), + propertyEntityInfo = propertyEntityInfo, + valueObjects = valueObjectListFiltered + ) } yield // If the property has a value that the user isn't allowed to see, and its cardinality // is MustHaveOne or MayHaveOne, don't return any information about the property. @@ -3181,8 +3345,8 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo for { valuePropertiesWithDataWithOption: Iterable[Option[PropertyV1]] <- Future.sequence( - valuePropertiesWithDataWithFuture - ) + valuePropertiesWithDataWithFuture + ) valuePropertiesWithData = valuePropertiesWithDataWithOption.toVector.flatten @@ -3270,44 +3434,46 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo for { apiValueV1ForLinkValue <- valueUtilV1.makeValueV1( - valueProps = linkValueProps, - projectShortcode = projectShortcode, - responderManager = responderManager, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + valueProps = linkValueProps, + projectShortcode = projectShortcode, + responderManager = responderManager, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) linkValueV1: LinkValueV1 = apiValueV1ForLinkValue match { - case linkValueV1: LinkValueV1 => linkValueV1 - case _ => - throw InconsistentRepositoryDataException( - s"Expected $linkValueIri to be a knora-base:LinkValue, but its type is ${apiValueV1ForLinkValue.valueTypeIri}" - ) - } + case linkValueV1: LinkValueV1 => linkValueV1 + case _ => + throw InconsistentRepositoryDataException( + s"Expected $linkValueIri to be a knora-base:LinkValue, but its type is ${apiValueV1ForLinkValue.valueTypeIri}" + ) + } // Check the permissions on the LinkValue. linkValuePermission = PermissionUtilADM.getUserPermissionWithValuePropsV1( - valueIri = linkValueIri, - valueProps = linkValueProps, - entityProject = None, // We don't need to specify this here, because it's in linkValueProps - userProfile = userProfileV1 - ) + valueIri = linkValueIri, + valueProps = linkValueProps, + entityProject = + None, // We don't need to specify this here, because it's in linkValueProps + userProfile = userProfileV1 + ) // We only allow the user to see information about the link if they have at least view permission on both the link value // and on the target resource. targetResourcePermission = PermissionUtilADM.getUserPermissionWithValuePropsV1( - valueIri = targetResourceIri, - valueProps = valueProps, - entityProject = None, // We don't need to specify this here, because it's in valueProps - userProfile = userProfileV1 - ) + valueIri = targetResourceIri, + valueProps = valueProps, + entityProject = + None, // We don't need to specify this here, because it's in valueProps + userProfile = userProfileV1 + ) linkPermission = (targetResourcePermission, linkValuePermission) match { - case (Some(targetResourcePermissionCode), Some(linkValuePermissionCode)) => - Some(scala.math.min(targetResourcePermissionCode, linkValuePermissionCode)) - case _ => None - } + case (Some(targetResourcePermissionCode), Some(linkValuePermissionCode)) => + Some(scala.math.min(targetResourcePermissionCode, linkValuePermissionCode)) + case _ => None + } } yield ValueObjectV1( valueObjectIri = linkValueIri, @@ -3331,11 +3497,11 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo // Make a PropertyV1 for the property. propertyV1 = makePropertyV1( - propertyIri = propertyIri, - propertyCardinality = propsAndCardinalities.get(propertyIri), - propertyEntityInfo = propertyEntityInfo, - valueObjects = valueObjectListFiltered - ) + propertyIri = propertyIri, + propertyCardinality = propsAndCardinalities.get(propertyIri), + propertyEntityInfo = propertyEntityInfo, + valueObjects = valueObjectListFiltered + ) // If the property has a value that the user isn't allowed to see, and its cardinality // is MustHaveOne or MayHaveOne, don't return any information about the property. @@ -3348,8 +3514,8 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo } linkPropertiesWithDataWithOption: Iterable[Option[PropertyV1]] <- Future.sequence( - linkPropertiesWithDataWithFuture - ) + linkPropertiesWithDataWithFuture + ) linkPropertiesWithData: Vector[PropertyV1] = linkPropertiesWithDataWithOption.toVector.flatten @@ -3430,9 +3596,9 @@ class ResourcesResponderV1(responderData: ResponderData) extends Responder(respo * @return a corresponding preview image. */ private def fullSizeImageFileValueToPreview(fullSizeImageFileValue: StillImageFileValueV1): StillImageFileValueV1 = { - val proportion = fullSizeImageFileValue.dimY.toDouble / 128.0 + val proportion = fullSizeImageFileValue.dimY.toDouble / 128.0 val previewHeight = 128 - val previewWidth = (fullSizeImageFileValue.dimX.toDouble / proportion).round.toInt + val previewWidth = (fullSizeImageFileValue.dimX.toDouble / proportion).round.toInt fullSizeImageFileValue.copy( dimX = previewWidth, diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v1/SearchResponderV1.scala b/webapi/src/main/scala/org/knora/webapi/responders/v1/SearchResponderV1.scala index 26fe52aa09..024d57955f 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/v1/SearchResponderV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v1/SearchResponderV1.scala @@ -161,16 +161,16 @@ class SearchResponderV1(responderData: ResponderData) extends Responder(responde for { // Get the search results with paging. searchSparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .searchFulltext( - searchTerms = LuceneQueryString(searchGetRequest.searchValue), - preferredLanguage = searchGetRequest.userProfile.lang, - fallbackLanguage = settings.fallbackLanguage, - projectIriOption = searchGetRequest.filterByProject, - restypeIriOption = searchGetRequest.filterByRestype - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .searchFulltext( + searchTerms = LuceneQueryString(searchGetRequest.searchValue), + preferredLanguage = searchGetRequest.userProfile.lang, + fallbackLanguage = settings.fallbackLanguage, + projectIriOption = searchGetRequest.filterByProject, + restypeIriOption = searchGetRequest.filterByRestype + ) + .toString() + ) // _ = println("================" + pagingSparql) @@ -185,145 +185,146 @@ class SearchResponderV1(responderData: ResponderData) extends Responder(responde // Get information about those entities from the ontology responder. entityInfoRequest = EntityInfoGetRequestV1( - resourceClassIris = resourceClassIris, - propertyIris = propertyIris, - userProfile = searchGetRequest.userProfile - ) + resourceClassIris = resourceClassIris, + propertyIris = propertyIris, + userProfile = searchGetRequest.userProfile + ) entityInfoResponse <- (responderManager ? entityInfoRequest).mapTo[EntityInfoGetResponseV1] // Group the search results by resource IRI. groupedByResourceIri: Map[IRI, Seq[VariableResultsRow]] = searchResponse.results.bindings - .groupBy(_.rowMap("resource")) + .groupBy(_.rowMap("resource")) // Convert the query result rows into SearchResultRowV1 objects. - subjects: Vector[SearchResultRowV1] = groupedByResourceIri - .foldLeft(Vector.empty[SearchResultRowV1]) { case (subjectsAcc, (resourceIri, rows)) => - val firstRowMap = rows.head.rowMap - - // Does the user have permission to see the resource? - - val resourceCreator = firstRowMap("resourceCreator") - val resourceProject = firstRowMap("resourceProject") - val resourceProjectShortcode = resourceIri.toSmartIri.getProjectCode.getOrElse( - throw InconsistentRepositoryDataException(s"Invalid resource IRI: $resourceIri") - ) - val resourcePermissions = firstRowMap("resourcePermissions") - - val resourcePermissionCode: Option[Int] = PermissionUtilADM.getUserPermissionV1( - entityIri = resourceIri, - entityCreator = resourceCreator, - entityProject = resourceProject, - entityPermissionLiteral = resourcePermissions, - userProfile = userProfileV1 - ) - - if (resourcePermissionCode.nonEmpty) { - // Yes. Get more information about the resource. - - val resourceClassIri = firstRowMap("resourceClass") - val resourceEntityInfo: ClassInfoV1 = entityInfoResponse.resourceClassInfoMap(resourceClassIri) - val resourceClassLabel = resourceEntityInfo.getPredicateObject( - predicateIri = OntologyConstants.Rdfs.Label, - preferredLangs = Some(searchGetRequest.userProfile.lang, settings.fallbackLanguage) + subjects: Vector[SearchResultRowV1] = + groupedByResourceIri + .foldLeft(Vector.empty[SearchResultRowV1]) { case (subjectsAcc, (resourceIri, rows)) => + val firstRowMap = rows.head.rowMap + + // Does the user have permission to see the resource? + + val resourceCreator = firstRowMap("resourceCreator") + val resourceProject = firstRowMap("resourceProject") + val resourceProjectShortcode = resourceIri.toSmartIri.getProjectCode.getOrElse( + throw InconsistentRepositoryDataException(s"Invalid resource IRI: $resourceIri") ) - val resourceClassIcon = resourceEntityInfo.getPredicateObject(OntologyConstants.KnoraBase.ResourceIcon) - val resourceLabel = firstRowMap.getOrElse( - "resourceLabel", - throw InconsistentRepositoryDataException(s"Resource $resourceIri has no rdfs:label") + val resourcePermissions = firstRowMap("resourcePermissions") + + val resourcePermissionCode: Option[Int] = PermissionUtilADM.getUserPermissionV1( + entityIri = resourceIri, + entityCreator = resourceCreator, + entityProject = resourceProject, + entityPermissionLiteral = resourcePermissions, + userProfile = userProfileV1 ) - // Collect the matching values in the resource. - val mapOfMatchingValues: Map[IRI, MatchingValue] = - rows.filter(_.rowMap.get("valueObject").nonEmpty).foldLeft(Map.empty[IRI, MatchingValue]) { - case (valuesAcc, row) => - // Convert the permissions on the matching value object into a ValueProps. - val valueIri = row.rowMap("valueObject") - val literal = row.rowMap("literal") - val valueCreator = row.rowMap("valueCreator") - val valuePermissionsLiteral = row.rowMap("valuePermissions") - val valuePermissionCode = PermissionUtilADM.getUserPermissionV1( - entityIri = valueIri, - entityCreator = valueCreator, - entityProject = resourceProject, - entityPermissionLiteral = valuePermissionsLiteral, - userProfile = userProfileV1 - ) + if (resourcePermissionCode.nonEmpty) { + // Yes. Get more information about the resource. - val value: Option[(IRI, MatchingValue)] = valuePermissionCode.map { permissionCode => - val propertyIri = row.rowMap("resourceProperty") - val propertyLabel = entityInfoResponse - .propertyInfoMap(propertyIri) - .getPredicateObject( - OntologyConstants.Rdfs.Label, - preferredLangs = Some(searchGetRequest.userProfile.lang, settings.fallbackLanguage) - ) match { - case Some(label) => label - case None => - throw InconsistentRepositoryDataException(s"Property $propertyIri has no rdfs:label") - } + val resourceClassIri = firstRowMap("resourceClass") + val resourceEntityInfo: ClassInfoV1 = entityInfoResponse.resourceClassInfoMap(resourceClassIri) + val resourceClassLabel = resourceEntityInfo.getPredicateObject( + predicateIri = OntologyConstants.Rdfs.Label, + preferredLangs = Some(searchGetRequest.userProfile.lang, settings.fallbackLanguage) + ) + val resourceClassIcon = resourceEntityInfo.getPredicateObject(OntologyConstants.KnoraBase.ResourceIcon) + val resourceLabel = firstRowMap.getOrElse( + "resourceLabel", + throw InconsistentRepositoryDataException(s"Resource $resourceIri has no rdfs:label") + ) - valueIri -> MatchingValue( - valueTypeIri = row.rowMap("valueObjectType"), - propertyIri = propertyIri, - propertyLabel = propertyLabel, - literal = literal, - valuePermissionCode = valuePermissionCode + // Collect the matching values in the resource. + val mapOfMatchingValues: Map[IRI, MatchingValue] = + rows.filter(_.rowMap.get("valueObject").nonEmpty).foldLeft(Map.empty[IRI, MatchingValue]) { + case (valuesAcc, row) => + // Convert the permissions on the matching value object into a ValueProps. + val valueIri = row.rowMap("valueObject") + val literal = row.rowMap("literal") + val valueCreator = row.rowMap("valueCreator") + val valuePermissionsLiteral = row.rowMap("valuePermissions") + val valuePermissionCode = PermissionUtilADM.getUserPermissionV1( + entityIri = valueIri, + entityCreator = valueCreator, + entityProject = resourceProject, + entityPermissionLiteral = valuePermissionsLiteral, + userProfile = userProfileV1 ) - } - valuesAcc ++ value - } + val value: Option[(IRI, MatchingValue)] = valuePermissionCode.map { permissionCode => + val propertyIri = row.rowMap("resourceProperty") + val propertyLabel = entityInfoResponse + .propertyInfoMap(propertyIri) + .getPredicateObject( + OntologyConstants.Rdfs.Label, + preferredLangs = Some(searchGetRequest.userProfile.lang, settings.fallbackLanguage) + ) match { + case Some(label) => label + case None => + throw InconsistentRepositoryDataException(s"Property $propertyIri has no rdfs:label") + } - // Sort by value IRI, then by property IRI, so the results are consistent between requests. - val vectorOfMatchingValues: Vector[(IRI, MatchingValue)] = mapOfMatchingValues.toVector - val matchingValuesSortedByValueIri: Vector[MatchingValue] = vectorOfMatchingValues.sortBy(_._1).map(_._2) - val matchingValues: Vector[MatchingValue] = matchingValuesSortedByValueIri.sortBy(_.propertyIri) + valueIri -> MatchingValue( + valueTypeIri = row.rowMap("valueObjectType"), + propertyIri = propertyIri, + propertyLabel = propertyLabel, + literal = literal, + valuePermissionCode = valuePermissionCode + ) + } - // Does the user have permission to see at least one matching value in the resource, or did the resource's label match? - if (matchingValues.nonEmpty || rows.exists(_.rowMap.get("valueObject").isEmpty)) { - // Yes. Make a search result for the resource. + valuesAcc ++ value + } - val resourceClassIconURL = resourceClassIcon.map { resClassIcon => - valueUtilV1.makeResourceClassIconURL(resourceClassIri, resClassIcon) - } + // Sort by value IRI, then by property IRI, so the results are consistent between requests. + val vectorOfMatchingValues: Vector[(IRI, MatchingValue)] = mapOfMatchingValues.toVector + val matchingValuesSortedByValueIri: Vector[MatchingValue] = vectorOfMatchingValues.sortBy(_._1).map(_._2) + val matchingValues: Vector[MatchingValue] = matchingValuesSortedByValueIri.sortBy(_.propertyIri) - subjectsAcc :+ SearchResultRowV1( - obj_id = resourceIri, - preview_path = firstRowMap.get("previewPath") match { - case Some(path) => - Some(valueUtilV1.makeSipiImagePreviewGetUrlFromFilename(resourceProjectShortcode, path)) - case None => - // If there is no preview image, use the resource class icon from the ontology. - resourceClassIconURL - }, - iconsrc = resourceClassIconURL, - icontitle = resourceClassLabel, - iconlabel = resourceClassLabel, - valuetype_id = OntologyConstants.Rdfs.Label +: matchingValues.map(_.valueTypeIri), - valuelabel = "Label" +: matchingValues.map(_.propertyLabel), - value = resourceLabel +: matchingValues.map(_.literal), - preview_nx = firstRowMap.get("previewDimX") match { - case Some(previewDimX) => previewDimX.toInt - case None => settings.defaultIconSizeDimX - }, - preview_ny = firstRowMap.get("previewDimY") match { - case Some(previewDimY) => previewDimY.toInt - case None => settings.defaultIconSizeDimY - }, - rights = resourcePermissionCode - ) + // Does the user have permission to see at least one matching value in the resource, or did the resource's label match? + if (matchingValues.nonEmpty || rows.exists(_.rowMap.get("valueObject").isEmpty)) { + // Yes. Make a search result for the resource. + + val resourceClassIconURL = resourceClassIcon.map { resClassIcon => + valueUtilV1.makeResourceClassIconURL(resourceClassIri, resClassIcon) + } + + subjectsAcc :+ SearchResultRowV1( + obj_id = resourceIri, + preview_path = firstRowMap.get("previewPath") match { + case Some(path) => + Some(valueUtilV1.makeSipiImagePreviewGetUrlFromFilename(resourceProjectShortcode, path)) + case None => + // If there is no preview image, use the resource class icon from the ontology. + resourceClassIconURL + }, + iconsrc = resourceClassIconURL, + icontitle = resourceClassLabel, + iconlabel = resourceClassLabel, + valuetype_id = OntologyConstants.Rdfs.Label +: matchingValues.map(_.valueTypeIri), + valuelabel = "Label" +: matchingValues.map(_.propertyLabel), + value = resourceLabel +: matchingValues.map(_.literal), + preview_nx = firstRowMap.get("previewDimX") match { + case Some(previewDimX) => previewDimX.toInt + case None => settings.defaultIconSizeDimX + }, + preview_ny = firstRowMap.get("previewDimY") match { + case Some(previewDimY) => previewDimY.toInt + case None => settings.defaultIconSizeDimY + }, + rights = resourcePermissionCode + ) + } else { + // The user doesn't have permission to see any of the matching values. + subjectsAcc + } } else { - // The user doesn't have permission to see any of the matching values. + // The user doesn't have permission to see the resource. subjectsAcc } - } else { - // The user doesn't have permission to see the resource. - subjectsAcc } - } - .sortBy(_.obj_id) // Sort the matching resources by resource IRI so paging works. + .sortBy(_.obj_id) // Sort the matching resources by resource IRI so paging works. (maxPreviewDimX, maxPreviewDimY) = findMaxPreviewDimensions(subjects) @@ -331,11 +332,11 @@ class SearchResponderV1(responderData: ResponderData) extends Responder(responde resultsPage = subjects.slice(searchGetRequest.startAt, searchGetRequest.startAt + limit) results = SearchGetResponseV1( - subjects = resultsPage, - nhits = subjects.size.toString, - thumb_max = SearchPreviewDimensionsV1(maxPreviewDimX, maxPreviewDimY), - paging = makePaging(offset = searchGetRequest.startAt, limit = limit, resultCount = subjects.size) - ) + subjects = resultsPage, + nhits = subjects.size.toString, + thumb_max = SearchPreviewDimensionsV1(maxPreviewDimX, maxPreviewDimY), + paging = makePaging(offset = searchGetRequest.startAt, limit = limit, resultCount = subjects.size) + ) } yield results } @@ -349,14 +350,14 @@ class SearchResponderV1(responderData: ResponderData) extends Responder(responde import org.knora.webapi.messages.StringFormatter val userProfileV1 = searchGetRequest.userProfile.asUserProfileV1 - val limit = checkLimit(searchGetRequest.showNRows) + val limit = checkLimit(searchGetRequest.showNRows) for { // get information about all the properties involved propertyInfo: EntityInfoGetResponseV1 <- (responderManager ? EntityInfoGetRequestV1( - propertyIris = searchGetRequest.propertyIri.toSet, - userProfile = searchGetRequest.userProfile - )).mapTo[EntityInfoGetResponseV1] + propertyIris = searchGetRequest.propertyIri.toSet, + userProfile = searchGetRequest.userProfile + )).mapTo[EntityInfoGetResponseV1] /* * handle parallel lists here: propertyIri, comparisonOperator, SearchValue @@ -422,7 +423,7 @@ class SearchResponderV1(responderData: ResponderData) extends Responder(responde // parse date: Calendar:YYYY-MM-DD[:YYYY-MM-DD] val parsedDate = datestring.split(StringFormatter.CalendarSeparator) - val calendar = KnoraCalendarV1.lookup(parsedDate(0)) + val calendar = KnoraCalendarV1.lookup(parsedDate(0)) // val daysInMonth = Calendar.DAY_OF_MONTH // will be used to determine the number of days in the given month // val monthsInYear = Calendar.MONTH // will be used to determine the number of months in the given year (generic for other calendars) @@ -431,10 +432,10 @@ class SearchResponderV1(responderData: ResponderData) extends Responder(responde // it is a period: 0 : cal | 1 : start | 2 : end val periodStart = DateUtilV1.dateString2DateRange(parsedDate(1), calendar).start - val periodEnd = DateUtilV1.dateString2DateRange(parsedDate(2), calendar).end + val periodEnd = DateUtilV1.dateString2DateRange(parsedDate(2), calendar).end val start = DateUtilV1.convertDateToJulianDayNumber(periodStart) - val end = DateUtilV1.convertDateToJulianDayNumber(periodEnd) + val end = DateUtilV1.convertDateToJulianDayNumber(periodEnd) // check if end is bigger than start (the user could have submitted a period where start is bigger than end) if (start > end) @@ -447,7 +448,7 @@ class SearchResponderV1(responderData: ResponderData) extends Responder(responde val dateRange = DateUtilV1.dateString2DateRange(parsedDate(1), calendar) val start = DateUtilV1.convertDateToJulianDayNumber(dateRange.start) - val end = DateUtilV1.convertDateToJulianDayNumber(dateRange.end) + val end = DateUtilV1.convertDateToJulianDayNumber(dateRange.end) (start, end) } @@ -465,9 +466,9 @@ class SearchResponderV1(responderData: ResponderData) extends Responder(responde val (matchBooleanPositiveTerms, matchBooleanNegativeTerms) = if (compop == SearchComparisonOperatorV1.MATCH_BOOLEAN) { - val terms = searchString.asInstanceOf[String].split("\\s+").toSet - val negativeTerms = terms.filter(_.startsWith("-")) - val positiveTerms = terms -- negativeTerms + val terms = searchString.asInstanceOf[String].split("\\s+").toSet + val negativeTerms = terms.filter(_.startsWith("-")) + val positiveTerms = terms -- negativeTerms val negativeTermsWithoutPrefixes = negativeTerms.map(_.stripPrefix("-")) val positiveTermsWithoutPrefixes = positiveTerms.map(_.stripPrefix("+")) (positiveTermsWithoutPrefixes, negativeTermsWithoutPrefixes) @@ -569,15 +570,15 @@ class SearchResponderV1(responderData: ResponderData) extends Responder(responde // Get the search results. searchSparql = org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .searchExtended( - searchCriteria = searchCriteria, - preferredLanguage = searchGetRequest.userProfile.lang, - fallbackLanguage = settings.fallbackLanguage, - projectIriOption = searchGetRequest.filterByProject, - restypeIriOption = searchGetRequest.filterByRestype, - ownerIriOption = searchGetRequest.filterByOwner - ) - .toString() + .searchExtended( + searchCriteria = searchCriteria, + preferredLanguage = searchGetRequest.userProfile.lang, + fallbackLanguage = settings.fallbackLanguage, + projectIriOption = searchGetRequest.filterByProject, + restypeIriOption = searchGetRequest.filterByRestype, + ownerIriOption = searchGetRequest.filterByOwner + ) + .toString() // _ = println(searchSparql) @@ -589,188 +590,189 @@ class SearchResponderV1(responderData: ResponderData) extends Responder(responde // Get information about those resource classes from the ontology responder. entityInfoRequest = EntityInfoGetRequestV1( - resourceClassIris = resourceClassIris, - userProfile = searchGetRequest.userProfile - ) + resourceClassIris = resourceClassIris, + userProfile = searchGetRequest.userProfile + ) entityInfoResponse <- (responderManager ? entityInfoRequest).mapTo[EntityInfoGetResponseV1] // Group the search results by resource IRI. groupedByResourceIri: Map[IRI, Seq[VariableResultsRow]] = searchResponse.results.bindings - .groupBy(_.rowMap("resource")) + .groupBy(_.rowMap("resource")) // Convert the query result rows into SearchResultRowV1 objects. - subjects: Vector[SearchResultRowV1] = groupedByResourceIri - .foldLeft(Vector.empty[SearchResultRowV1]) { case (subjectsAcc, (resourceIri, rows)) => - val firstRowMap = rows.head.rowMap - - // Does the user have permission to see the resource? - - val resourceCreator = firstRowMap("resourceCreator") - val resourceProject = firstRowMap("resourceProject") - val resourceProjectShortcode = resourceIri.toSmartIri.getProjectCode.getOrElse( - throw InconsistentRepositoryDataException(s"Invalid resource IRI: $resourceIri") - ) - val resourcePermissions = firstRowMap("resourcePermissions") - - val resourcePermissionCode: Option[Int] = PermissionUtilADM.getUserPermissionV1( - entityIri = resourceIri, - entityCreator = resourceCreator, - entityProject = resourceProject, - entityPermissionLiteral = resourcePermissions, - userProfile = userProfileV1 - ) - - if (resourcePermissionCode.nonEmpty) { - // Yes. Get more information about the resource. - - val resourceClassIri = firstRowMap("resourceClass") - val resourceEntityInfo = entityInfoResponse.resourceClassInfoMap(resourceClassIri) - val resourceClassLabel = resourceEntityInfo.getPredicateObject( - predicateIri = OntologyConstants.Rdfs.Label, - preferredLangs = Some(searchGetRequest.userProfile.lang, settings.fallbackLanguage) + subjects: Vector[SearchResultRowV1] = + groupedByResourceIri + .foldLeft(Vector.empty[SearchResultRowV1]) { case (subjectsAcc, (resourceIri, rows)) => + val firstRowMap = rows.head.rowMap + + // Does the user have permission to see the resource? + + val resourceCreator = firstRowMap("resourceCreator") + val resourceProject = firstRowMap("resourceProject") + val resourceProjectShortcode = resourceIri.toSmartIri.getProjectCode.getOrElse( + throw InconsistentRepositoryDataException(s"Invalid resource IRI: $resourceIri") ) - val resourceClassIcon = resourceEntityInfo.getPredicateObject(OntologyConstants.KnoraBase.ResourceIcon) - val resourceLabel = firstRowMap.getOrElse( - "resourceLabel", - throw InconsistentRepositoryDataException(s"Resource $resourceIri has no rdfs:label") + val resourcePermissions = firstRowMap("resourcePermissions") + + val resourcePermissionCode: Option[Int] = PermissionUtilADM.getUserPermissionV1( + entityIri = resourceIri, + entityCreator = resourceCreator, + entityProject = resourceProject, + entityPermissionLiteral = resourcePermissions, + userProfile = userProfileV1 ) - // If there were search criteria referring to values, collect the matching values in the resource. - val matchingValues: Vector[MatchingValue] = if (searchCriteria.nonEmpty) { - // Construct a Map of value IRIs to MatchingValue objects found in the resource. - val mapOfMatchingValues: Map[IRI, MatchingValue] = rows.foldLeft(Map.empty[IRI, MatchingValue]) { - case (valuesAcc: Map[IRI, MatchingValue], row: VariableResultsRow) => - // For each row, get the matching value for each search criterion. - val valuesInRow: Seq[(IRI, MatchingValue)] = searchCriteria.zipWithIndex.map { - case (searchCriterion, index) => - val valueIri = row.rowMap(s"valueObject$index") - val literal = row.rowMap(s"literal$index") - val valuePermissionLiteral = row.rowMap(s"valuePermissions$index") - val valueCreator = row.rowMap(s"valueCreator$index") - - // Is the matching value object a LinkValue? - val valuePermissionCode = - if (searchCriterion.valueType == OntologyConstants.KnoraBase.Resource) { - // Yes. - val linkValuePermissionCode = PermissionUtilADM.getUserPermissionV1( - entityIri = valueIri, - entityCreator = valueCreator, - entityProject = resourceProject, - entityPermissionLiteral = valuePermissionLiteral, - userProfile = userProfileV1 - ) + if (resourcePermissionCode.nonEmpty) { + // Yes. Get more information about the resource. - // Get the permission code for the target resource. - val targetResourceIri = row.rowMap(s"targetResource$index") - val targetResourceCreator = row.rowMap(s"targetResourceCreator$index") - val targetResourceProject = row.rowMap(s"targetResourceProject$index") - val targetResourcePermissionLiteral = row.rowMap(s"targetResourcePermissions$index") - - val targetResourcePermissionCode = PermissionUtilADM.getUserPermissionV1( - entityIri = targetResourceIri, - entityCreator = targetResourceCreator, - entityProject = targetResourceProject, - entityPermissionLiteral = targetResourcePermissionLiteral, - userProfile = userProfileV1 - ) + val resourceClassIri = firstRowMap("resourceClass") + val resourceEntityInfo = entityInfoResponse.resourceClassInfoMap(resourceClassIri) + val resourceClassLabel = resourceEntityInfo.getPredicateObject( + predicateIri = OntologyConstants.Rdfs.Label, + preferredLangs = Some(searchGetRequest.userProfile.lang, settings.fallbackLanguage) + ) + val resourceClassIcon = resourceEntityInfo.getPredicateObject(OntologyConstants.KnoraBase.ResourceIcon) + val resourceLabel = firstRowMap.getOrElse( + "resourceLabel", + throw InconsistentRepositoryDataException(s"Resource $resourceIri has no rdfs:label") + ) - // Only allow the user to see the match if they have view permission on both the link value and the target resource. - Seq(linkValuePermissionCode, targetResourcePermissionCode).min - } else { - // The matching object is an ordinary value, not a LinkValue. - PermissionUtilADM.getUserPermissionV1( - entityIri = valueIri, - entityCreator = valueCreator, - entityProject = resourceProject, - entityPermissionLiteral = valuePermissionLiteral, - userProfile = userProfileV1 - ) + // If there were search criteria referring to values, collect the matching values in the resource. + val matchingValues: Vector[MatchingValue] = if (searchCriteria.nonEmpty) { + // Construct a Map of value IRIs to MatchingValue objects found in the resource. + val mapOfMatchingValues: Map[IRI, MatchingValue] = rows.foldLeft(Map.empty[IRI, MatchingValue]) { + case (valuesAcc: Map[IRI, MatchingValue], row: VariableResultsRow) => + // For each row, get the matching value for each search criterion. + val valuesInRow: Seq[(IRI, MatchingValue)] = searchCriteria.zipWithIndex.map { + case (searchCriterion, index) => + val valueIri = row.rowMap(s"valueObject$index") + val literal = row.rowMap(s"literal$index") + val valuePermissionLiteral = row.rowMap(s"valuePermissions$index") + val valueCreator = row.rowMap(s"valueCreator$index") + + // Is the matching value object a LinkValue? + val valuePermissionCode = + if (searchCriterion.valueType == OntologyConstants.KnoraBase.Resource) { + // Yes. + val linkValuePermissionCode = PermissionUtilADM.getUserPermissionV1( + entityIri = valueIri, + entityCreator = valueCreator, + entityProject = resourceProject, + entityPermissionLiteral = valuePermissionLiteral, + userProfile = userProfileV1 + ) + + // Get the permission code for the target resource. + val targetResourceIri = row.rowMap(s"targetResource$index") + val targetResourceCreator = row.rowMap(s"targetResourceCreator$index") + val targetResourceProject = row.rowMap(s"targetResourceProject$index") + val targetResourcePermissionLiteral = row.rowMap(s"targetResourcePermissions$index") + + val targetResourcePermissionCode = PermissionUtilADM.getUserPermissionV1( + entityIri = targetResourceIri, + entityCreator = targetResourceCreator, + entityProject = targetResourceProject, + entityPermissionLiteral = targetResourcePermissionLiteral, + userProfile = userProfileV1 + ) + + // Only allow the user to see the match if they have view permission on both the link value and the target resource. + Seq(linkValuePermissionCode, targetResourcePermissionCode).min + } else { + // The matching object is an ordinary value, not a LinkValue. + PermissionUtilADM.getUserPermissionV1( + entityIri = valueIri, + entityCreator = valueCreator, + entityProject = resourceProject, + entityPermissionLiteral = valuePermissionLiteral, + userProfile = userProfileV1 + ) + } + + val propertyIri = searchCriterion.propertyIri + val propertyLabel = propertyInfo + .propertyInfoMap(propertyIri) + .getPredicateObject( + predicateIri = OntologyConstants.Rdfs.Label, + preferredLangs = Some(searchGetRequest.userProfile.lang, settings.fallbackLanguage) + ) match { + case Some(label) => label + case None => + throw InconsistentRepositoryDataException(s"Property $propertyIri has no rdfs:label") } - val propertyIri = searchCriterion.propertyIri - val propertyLabel = propertyInfo - .propertyInfoMap(propertyIri) - .getPredicateObject( - predicateIri = OntologyConstants.Rdfs.Label, - preferredLangs = Some(searchGetRequest.userProfile.lang, settings.fallbackLanguage) - ) match { - case Some(label) => label - case None => - throw InconsistentRepositoryDataException(s"Property $propertyIri has no rdfs:label") - } + valueIri -> MatchingValue( + valueTypeIri = searchCriterion.valueType, + propertyIri = propertyIri, + propertyLabel = propertyLabel, + literal = literal, + valuePermissionCode = valuePermissionCode + ) + } - valueIri -> MatchingValue( - valueTypeIri = searchCriterion.valueType, - propertyIri = propertyIri, - propertyLabel = propertyLabel, - literal = literal, - valuePermissionCode = valuePermissionCode - ) - } + // Filter out the values that the user doesn't have permission to see. + val filteredValues: Seq[(IRI, MatchingValue)] = valuesInRow.filter { + case (matchingValueIri, matchingValue) => matchingValue.valuePermissionCode.nonEmpty + } - // Filter out the values that the user doesn't have permission to see. - val filteredValues: Seq[(IRI, MatchingValue)] = valuesInRow.filter { - case (matchingValueIri, matchingValue) => matchingValue.valuePermissionCode.nonEmpty - } + valuesAcc ++ filteredValues + } - valuesAcc ++ filteredValues + // Sort by value IRI, then by property IRI, so the results are consistent between requests. + val vectorOfMatchingValues: Vector[(IRI, MatchingValue)] = mapOfMatchingValues.toVector + val matchingValuesSortedByValueIri: Vector[MatchingValue] = + vectorOfMatchingValues.sortBy(_._1).map(_._2) + matchingValuesSortedByValueIri.sortBy(_.propertyIri) + } else { + Vector.empty[MatchingValue] } - // Sort by value IRI, then by property IRI, so the results are consistent between requests. - val vectorOfMatchingValues: Vector[(IRI, MatchingValue)] = mapOfMatchingValues.toVector - val matchingValuesSortedByValueIri: Vector[MatchingValue] = - vectorOfMatchingValues.sortBy(_._1).map(_._2) - matchingValuesSortedByValueIri.sortBy(_.propertyIri) - } else { - Vector.empty[MatchingValue] - } + // Does the user have permission to see at least one matching value in the resource, or were there no search criteria referring to values? + if (matchingValues.nonEmpty || searchCriteria.isEmpty) { + // Yes. Make a search result for the resource. - // Does the user have permission to see at least one matching value in the resource, or were there no search criteria referring to values? - if (matchingValues.nonEmpty || searchCriteria.isEmpty) { - // Yes. Make a search result for the resource. + val resourceClassIconURL = resourceClassIcon.map { resClassIcon => + valueUtilV1.makeResourceClassIconURL(resourceClassIri, resClassIcon) + } - val resourceClassIconURL = resourceClassIcon.map { resClassIcon => - valueUtilV1.makeResourceClassIconURL(resourceClassIri, resClassIcon) + subjectsAcc :+ SearchResultRowV1( + obj_id = resourceIri, + preview_path = firstRowMap.get("previewPath") match { + case Some(path) => + Some(valueUtilV1.makeSipiImagePreviewGetUrlFromFilename(resourceProjectShortcode, path)) + case None => + // If there is no preview image, use the resource class icon from the ontology. + resourceClassIconURL + }, + iconsrc = resourceClassIconURL, + icontitle = resourceClassLabel, + iconlabel = resourceClassLabel, + valuetype_id = OntologyConstants.Rdfs.Label +: matchingValues.map(_.valueTypeIri), + valuelabel = "Label" +: matchingValues.map(_.propertyLabel), + value = resourceLabel +: matchingValues.map(_.literal), + preview_nx = firstRowMap.get("previewDimX") match { + case Some(previewDimX) => previewDimX.toInt + case None => settings.defaultIconSizeDimX + }, + preview_ny = firstRowMap.get("previewDimY") match { + case Some(previewDimY) => previewDimY.toInt + case None => settings.defaultIconSizeDimY + }, + rights = resourcePermissionCode + ) + } else { + // The user doesn't have permission to see any of the matching values. + subjectsAcc } - - subjectsAcc :+ SearchResultRowV1( - obj_id = resourceIri, - preview_path = firstRowMap.get("previewPath") match { - case Some(path) => - Some(valueUtilV1.makeSipiImagePreviewGetUrlFromFilename(resourceProjectShortcode, path)) - case None => - // If there is no preview image, use the resource class icon from the ontology. - resourceClassIconURL - }, - iconsrc = resourceClassIconURL, - icontitle = resourceClassLabel, - iconlabel = resourceClassLabel, - valuetype_id = OntologyConstants.Rdfs.Label +: matchingValues.map(_.valueTypeIri), - valuelabel = "Label" +: matchingValues.map(_.propertyLabel), - value = resourceLabel +: matchingValues.map(_.literal), - preview_nx = firstRowMap.get("previewDimX") match { - case Some(previewDimX) => previewDimX.toInt - case None => settings.defaultIconSizeDimX - }, - preview_ny = firstRowMap.get("previewDimY") match { - case Some(previewDimY) => previewDimY.toInt - case None => settings.defaultIconSizeDimY - }, - rights = resourcePermissionCode - ) } else { - // The user doesn't have permission to see any of the matching values. + // The user doesn't have permission to see the resource. subjectsAcc } - } else { - // The user doesn't have permission to see the resource. - subjectsAcc - } - } - .sortBy(_.obj_id) // Sort the matching resources by resource IRI so paging works. + } + .sortBy(_.obj_id) // Sort the matching resources by resource IRI so paging works. (maxPreviewDimX, maxPreviewDimY) = findMaxPreviewDimensions(subjects) @@ -778,11 +780,11 @@ class SearchResponderV1(responderData: ResponderData) extends Responder(responde resultsPage = subjects.slice(searchGetRequest.startAt, searchGetRequest.startAt + limit) results = SearchGetResponseV1( - subjects = resultsPage, - nhits = subjects.size.toString, - thumb_max = SearchPreviewDimensionsV1(maxPreviewDimX, maxPreviewDimY), - paging = makePaging(offset = searchGetRequest.startAt, limit = limit, resultCount = subjects.size) - ) + subjects = resultsPage, + nhits = subjects.size.toString, + thumb_max = SearchPreviewDimensionsV1(maxPreviewDimX, maxPreviewDimY), + paging = makePaging(offset = searchGetRequest.startAt, limit = limit, resultCount = subjects.size) + ) } yield results } @@ -795,8 +797,8 @@ class SearchResponderV1(responderData: ResponderData) extends Responder(responde * @return a list of [[SearchResultPage]] objects. */ private def makePaging(offset: Int, limit: Int, resultCount: Int): Seq[SearchResultPage] = { - val pageRemainder = resultCount % limit - val numPages = (resultCount / limit) + (if (pageRemainder > 0) 1 else 0) + val pageRemainder = resultCount % limit + val numPages = (resultCount / limit) + (if (pageRemainder > 0) 1 else 0) val currentPageNum = offset / limit // The offset might put us in the middle of a page, but that's OK. (0 until numPages).map { pageNum => diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v1/StandoffResponderV1.scala b/webapi/src/main/scala/org/knora/webapi/responders/v1/StandoffResponderV1.scala index db973c9f85..400ff106ce 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/v1/StandoffResponderV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v1/StandoffResponderV1.scala @@ -63,10 +63,10 @@ class StandoffResponderV1(responderData: ResponderData) extends Responder(respon val xslTransformationFuture = for { xsltTransformation <- (responderManager ? GetXSLTransformationRequestV2( - xsltTextRepresentationIri = xslTransformationIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = userProfile - )).mapTo[GetXSLTransformationResponseV2] + xsltTextRepresentationIri = xslTransformationIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = userProfile + )).mapTo[GetXSLTransformationResponseV2] } yield GetXSLTransformationResponseV1( xslt = xsltTransformation.xslt ) @@ -139,10 +139,10 @@ class StandoffResponderV1(responderData: ResponderData) extends Responder(respon ): Future[GetMappingResponseV1] = for { mappingResponse: GetMappingResponseV2 <- (responderManager ? GetMappingRequestV2( - mappingIri = mappingIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = userProfile - )).mapTo[GetMappingResponseV2] + mappingIri = mappingIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = userProfile + )).mapTo[GetMappingResponseV2] } yield GetMappingResponseV1( mappingIri = mappingResponse.mappingIri, mapping = mappingResponse.mapping, diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v1/UsersResponderV1.scala b/webapi/src/main/scala/org/knora/webapi/responders/v1/UsersResponderV1.scala index 39952fe2a5..cbc07d3e6f 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/v1/UsersResponderV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v1/UsersResponderV1.scala @@ -74,39 +74,39 @@ class UsersResponderV1(responderData: ResponderData) extends Responder(responder //log.debug("usersGetV1") for { _ <- Future( - if (!userProfileV1.permissionData.isSystemAdmin) { - throw ForbiddenException("SystemAdmin permissions are required.") - } - ) + if (!userProfileV1.permissionData.isSystemAdmin) { + throw ForbiddenException("SystemAdmin permissions are required.") + } + ) sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getUsers() - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getUsers() + .toString() + ) usersResponse <- (storeManager ? SparqlSelectRequest(sparqlQueryString)).mapTo[SparqlSelectResult] usersResponseRows: Seq[VariableResultsRow] = usersResponse.results.bindings - usersWithProperties: Map[String, Map[String, String]] = usersResponseRows.groupBy(_.rowMap("s")).map { - case (userIri: IRI, rows: Seq[VariableResultsRow]) => + usersWithProperties: Map[String, Map[String, String]] = + usersResponseRows.groupBy(_.rowMap("s")).map { case (userIri: IRI, rows: Seq[VariableResultsRow]) => (userIri, rows.map(row => (row.rowMap("p"), row.rowMap("o"))).toMap) - } + } users = usersWithProperties.map { case (userIri: IRI, propsMap: Map[String, String]) => - UserDataV1( - lang = propsMap.get(OntologyConstants.KnoraAdmin.PreferredLanguage) match { - case Some(langList) => langList - case None => settings.fallbackLanguage - }, - user_id = Some(userIri), - email = propsMap.get(OntologyConstants.KnoraAdmin.Email), - firstname = propsMap.get(OntologyConstants.KnoraAdmin.GivenName), - lastname = propsMap.get(OntologyConstants.KnoraAdmin.FamilyName), - status = propsMap.get(OntologyConstants.KnoraAdmin.Status).map(_.toBoolean) - ) - }.toSeq + UserDataV1( + lang = propsMap.get(OntologyConstants.KnoraAdmin.PreferredLanguage) match { + case Some(langList) => langList + case None => settings.fallbackLanguage + }, + user_id = Some(userIri), + email = propsMap.get(OntologyConstants.KnoraAdmin.Email), + firstname = propsMap.get(OntologyConstants.KnoraAdmin.GivenName), + lastname = propsMap.get(OntologyConstants.KnoraAdmin.FamilyName), + status = propsMap.get(OntologyConstants.KnoraAdmin.Status).map(_.toBoolean) + ) + }.toSeq } yield users @@ -120,9 +120,9 @@ class UsersResponderV1(responderData: ResponderData) extends Responder(responder for { maybeUsersListToReturn <- usersGetV1(userProfileV1) result = maybeUsersListToReturn match { - case users: Seq[UserDataV1] if users.nonEmpty => UsersGetResponseV1(users = users) - case _ => throw NotFoundException(s"No users found") - } + case users: Seq[UserDataV1] if users.nonEmpty => UsersGetResponseV1(users = users) + case _ => throw NotFoundException(s"No users found") + } } yield result /** @@ -135,12 +135,12 @@ class UsersResponderV1(responderData: ResponderData) extends Responder(responder //log.debug("userDataByIriGetV1 - userIri: {}", userIri) for { sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getUserByIri( - userIri = userIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getUserByIri( + userIri = userIri + ) + .toString() + ) // _ = log.debug("userDataByIRIGetV1 - sparqlQueryString: {}", sparqlQueryString) @@ -176,25 +176,25 @@ class UsersResponderV1(responderData: ResponderData) extends Responder(responder case None => for { sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getUserByIri( - userIri = userIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getUserByIri( + userIri = userIri + ) + .toString() + ) // _ = log.debug(s"userProfileByIRIGetV1 - sparqlQueryString: {}", sparqlQueryString) userDataQueryResponse <- (storeManager ? SparqlSelectRequest(sparqlQueryString)).mapTo[SparqlSelectResult] maybeUserProfileV1 <- userDataQueryResponse2UserProfileV1( - userDataQueryResponse = userDataQueryResponse, - featureFactoryConfig = featureFactoryConfig - ) + userDataQueryResponse = userDataQueryResponse, + featureFactoryConfig = featureFactoryConfig + ) _ = if (maybeUserProfileV1.nonEmpty) { - writeUserProfileV1ToCache(maybeUserProfileV1.get) - } + writeUserProfileV1ToCache(maybeUserProfileV1.get) + } result = maybeUserProfileV1.map(_.ofType(profileType)) @@ -219,20 +219,20 @@ class UsersResponderV1(responderData: ResponderData) extends Responder(responder ): Future[UserProfileResponseV1] = for { _ <- Future( - if (!userProfile.permissionData.isSystemAdmin && !userProfile.userData.user_id.contains(userIRI)) { - throw ForbiddenException("SystemAdmin permissions are required.") - } - ) + if (!userProfile.permissionData.isSystemAdmin && !userProfile.userData.user_id.contains(userIRI)) { + throw ForbiddenException("SystemAdmin permissions are required.") + } + ) maybeUserProfileToReturn <- userProfileByIRIGetV1( - userIri = userIRI, - profileType = profileType, - featureFactoryConfig = featureFactoryConfig - ) + userIri = userIRI, + profileType = profileType, + featureFactoryConfig = featureFactoryConfig + ) result = maybeUserProfileToReturn match { - case Some(up) => UserProfileResponseV1(up) - case None => throw NotFoundException(s"User '$userIRI' not found") - } + case Some(up) => UserProfileResponseV1(up) + case None => throw NotFoundException(s"User '$userIRI' not found") + } } yield result /** @@ -259,25 +259,25 @@ class UsersResponderV1(responderData: ResponderData) extends Responder(responder case None => for { sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getUserByEmail( - email = email - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getUserByEmail( + email = email + ) + .toString() + ) //_ = log.debug(s"userProfileByEmailGetV1 - sparqlQueryString: $sparqlQueryString") userDataQueryResponse <- (storeManager ? SparqlSelectRequest(sparqlQueryString)).mapTo[SparqlSelectResult] //_ = log.debug(MessageUtil.toSource(userDataQueryResponse)) maybeUserProfileV1 <- userDataQueryResponse2UserProfileV1( - userDataQueryResponse = userDataQueryResponse, - featureFactoryConfig = featureFactoryConfig - ) + userDataQueryResponse = userDataQueryResponse, + featureFactoryConfig = featureFactoryConfig + ) _ = if (maybeUserProfileV1.nonEmpty) { - writeUserProfileV1ToCache(maybeUserProfileV1.get) - } + writeUserProfileV1ToCache(maybeUserProfileV1.get) + } result = maybeUserProfileV1.map(_.ofType(profileType)) @@ -304,15 +304,15 @@ class UsersResponderV1(responderData: ResponderData) extends Responder(responder ): Future[UserProfileResponseV1] = for { maybeUserProfileToReturn <- userProfileByEmailGetV1( - email = email, - profileType = profileType, - featureFactoryConfig = featureFactoryConfig - ) + email = email, + profileType = profileType, + featureFactoryConfig = featureFactoryConfig + ) result = maybeUserProfileToReturn match { - case Some(up: UserProfileV1) => UserProfileResponseV1(up) - case None => throw NotFoundException(s"User '$email' not found") - } + case Some(up: UserProfileV1) => UserProfileResponseV1(up) + case None => throw NotFoundException(s"User '$email' not found") + } } yield result /** @@ -330,26 +330,26 @@ class UsersResponderV1(responderData: ResponderData) extends Responder(responder ): Future[UserProjectMembershipsGetResponseV1] = for { sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getUserByIri( - userIri = userIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getUserByIri( + userIri = userIri + ) + .toString() + ) //_ = log.debug("userDataByIRIGetV1 - sparqlQueryString: {}", sparqlQueryString) userDataQueryResponse <- (storeManager ? SparqlSelectRequest(sparqlQueryString)).mapTo[SparqlSelectResult] groupedUserData: Map[String, Seq[String]] = userDataQueryResponse.results.bindings.groupBy(_.rowMap("p")).map { - case (predicate, rows) => predicate -> rows.map(_.rowMap("o")) - } + case (predicate, rows) => predicate -> rows.map(_.rowMap("o")) + } /* the projects the user is member of */ projectIris: Seq[IRI] = groupedUserData.get(OntologyConstants.KnoraAdmin.IsInProject) match { - case Some(projects) => projects - case None => Seq.empty[IRI] - } + case Some(projects) => projects + case None => Seq.empty[IRI] + } // _ = log.debug("userProjectMembershipsGetRequestV1 - userIri: {}, projectIris: {}", userIri, projectIris) } yield UserProjectMembershipsGetResponseV1(projects = projectIris) @@ -370,26 +370,26 @@ class UsersResponderV1(responderData: ResponderData) extends Responder(responder ): Future[UserProjectAdminMembershipsGetResponseV1] = for { sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getUserByIri( - userIri = userIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getUserByIri( + userIri = userIri + ) + .toString() + ) //_ = log.debug("userDataByIRIGetV1 - sparqlQueryString: {}", sparqlQueryString) userDataQueryResponse <- (storeManager ? SparqlSelectRequest(sparqlQueryString)).mapTo[SparqlSelectResult] groupedUserData: Map[String, Seq[String]] = userDataQueryResponse.results.bindings.groupBy(_.rowMap("p")).map { - case (predicate, rows) => predicate -> rows.map(_.rowMap("o")) - } + case (predicate, rows) => predicate -> rows.map(_.rowMap("o")) + } /* the projects the user is member of */ projectIris: Seq[IRI] = groupedUserData.get(OntologyConstants.KnoraAdmin.IsInProjectAdminGroup) match { - case Some(projects) => projects - case None => Seq.empty[IRI] - } + case Some(projects) => projects + case None => Seq.empty[IRI] + } // _ = log.debug("userProjectAdminMembershipsGetRequestV1 - userIri: {}, projectIris: {}", userIri, projectIris) } yield UserProjectAdminMembershipsGetResponseV1(projects = projectIris) @@ -409,26 +409,26 @@ class UsersResponderV1(responderData: ResponderData) extends Responder(responder ): Future[UserGroupMembershipsGetResponseV1] = for { sparqlQueryString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getUserByIri( - userIri = userIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getUserByIri( + userIri = userIri + ) + .toString() + ) //_ = log.debug("userDataByIRIGetV1 - sparqlQueryString: {}", sparqlQueryString) userDataQueryResponse <- (storeManager ? SparqlSelectRequest(sparqlQueryString)).mapTo[SparqlSelectResult] groupedUserData: Map[String, Seq[String]] = userDataQueryResponse.results.bindings.groupBy(_.rowMap("p")).map { - case (predicate, rows) => predicate -> rows.map(_.rowMap("o")) - } + case (predicate, rows) => predicate -> rows.map(_.rowMap("o")) + } /* the groups the user is member of */ groupIris: Seq[IRI] = groupedUserData.get(OntologyConstants.KnoraAdmin.IsInGroup) match { - case Some(projects) => projects - case None => Seq.empty[IRI] - } + case Some(projects) => projects + case None => Seq.empty[IRI] + } //_ = log.debug("userDataByIriGetV1 - maybeUserDataV1: {}", maybeUserDataV1) } yield UserGroupMembershipsGetResponseV1(groups = groupIris) @@ -543,34 +543,34 @@ class UsersResponderV1(responderData: ResponderData) extends Responder(responder for { /* get the user's permission profile from the permissions responder */ permissionData <- (responderManager ? PermissionDataGetADM( - projectIris = projectIris, - groupIris = groupIris, - isInProjectAdminGroups = isInProjectAdminGroups, - isInSystemAdminGroup = isInSystemAdminGroup, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - )).mapTo[PermissionsDataADM] + projectIris = projectIris, + groupIris = groupIris, + isInProjectAdminGroups = isInProjectAdminGroups, + isInSystemAdminGroup = isInSystemAdminGroup, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + )).mapTo[PermissionsDataADM] maybeProjectInfoFutures: Seq[Future[Option[ProjectInfoV1]]] = projectIris.map { projectIri => - (responderManager ? ProjectInfoByIRIGetV1( - iri = projectIri, - featureFactoryConfig = featureFactoryConfig, - userProfileV1 = None - )).mapTo[Option[ProjectInfoV1]] - } + (responderManager ? ProjectInfoByIRIGetV1( + iri = projectIri, + featureFactoryConfig = featureFactoryConfig, + userProfileV1 = None + )).mapTo[Option[ProjectInfoV1]] + } maybeProjectInfos: Seq[Option[ProjectInfoV1]] <- Future.sequence(maybeProjectInfoFutures) - projectInfos = maybeProjectInfos.flatten - projectInfoMap: Map[IRI, ProjectInfoV1] = projectInfos.map(projectInfo => projectInfo.id -> projectInfo).toMap + projectInfos = maybeProjectInfos.flatten + projectInfoMap: Map[IRI, ProjectInfoV1] = projectInfos.map(projectInfo => projectInfo.id -> projectInfo).toMap /* construct the user profile from the different parts */ up = UserProfileV1( - userData = userDataV1, - groups = groupIris, - projects_info = projectInfoMap, - sessionId = None, - permissionData = permissionData - ) + userData = userDataV1, + groups = groupIris, + projects_info = projectInfoMap, + sessionId = None, + permissionData = permissionData + ) // _ = log.debug("Retrieved UserProfileV1: {}", up.toString) result: Option[UserProfileV1] = Some(up) @@ -589,12 +589,12 @@ class UsersResponderV1(responderData: ResponderData) extends Responder(responder def userExists(userIri: IRI): Future[Boolean] = for { askString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt.checkUserExists(userIri = userIri).toString - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt.checkUserExists(userIri = userIri).toString + ) // _ = log.debug("userExists - query: {}", askString) checkUserExistsResponse <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] - result = checkUserExistsResponse.result + result = checkUserExistsResponse.result } yield result @@ -607,14 +607,14 @@ class UsersResponderV1(responderData: ResponderData) extends Responder(responder def projectExists(projectIri: IRI): Future[Boolean] = for { askString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .checkProjectExistsByIri(projectIri = projectIri) - .toString - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .checkProjectExistsByIri(projectIri = projectIri) + .toString + ) // _ = log.debug("projectExists - query: {}", askString) checkUserExistsResponse <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] - result = checkUserExistsResponse.result + result = checkUserExistsResponse.result } yield result @@ -626,13 +626,14 @@ class UsersResponderV1(responderData: ResponderData) extends Responder(responder */ def groupExists(groupIri: IRI): Future[Boolean] = for { - askString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt.checkGroupExistsByIri(groupIri = groupIri).toString - ) + askString <- + Future( + org.knora.webapi.messages.twirl.queries.sparql.admin.txt.checkGroupExistsByIri(groupIri = groupIri).toString + ) // _ = log.debug("groupExists - query: {}", askString) checkUserExistsResponse <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] - result = checkUserExistsResponse.result + result = checkUserExistsResponse.result } yield result diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v1/ValuesResponderV1.scala b/webapi/src/main/scala/org/knora/webapi/responders/v1/ValuesResponderV1.scala index 84af5f61b8..435fe34bba 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/v1/ValuesResponderV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v1/ValuesResponderV1.scala @@ -98,37 +98,40 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde ): Future[ValueGetResponseV1] = for { maybeValueQueryResult <- findValue( - valueIri = valueIri, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + valueIri = valueIri, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) response <- maybeValueQueryResult match { - case Some(valueQueryResult) => - for { - maybeValueCreatorProfile <- (responderManager ? UserProfileByIRIGetV1( - userIri = valueQueryResult.creatorIri, - userProfileType = UserProfileTypeV1.RESTRICTED, - featureFactoryConfig = featureFactoryConfig - )).mapTo[Option[UserProfileV1]] - - valueCreatorProfile = maybeValueCreatorProfile match { - case Some(up) => up - case None => throw NotFoundException(s"User ${valueQueryResult.creatorIri} not found") - } - } yield ValueGetResponseV1( - valuetype = valueQueryResult.value.valueTypeIri, - rights = valueQueryResult.permissionCode, - value = valueQueryResult.value, - valuecreator = valueCreatorProfile.userData.email.get, - valuecreatorname = valueCreatorProfile.userData.fullname.get, - valuecreationdate = valueQueryResult.creationDate, - comment = valueQueryResult.comment - ) - - case None => - throw NotFoundException(s"Value $valueIri not found (it may have been deleted)") - } + case Some(valueQueryResult) => + for { + maybeValueCreatorProfile <- (responderManager ? UserProfileByIRIGetV1( + userIri = valueQueryResult.creatorIri, + userProfileType = UserProfileTypeV1.RESTRICTED, + featureFactoryConfig = featureFactoryConfig + )).mapTo[Option[UserProfileV1]] + + valueCreatorProfile = maybeValueCreatorProfile match { + case Some(up) => up + case None => + throw NotFoundException( + s"User ${valueQueryResult.creatorIri} not found" + ) + } + } yield ValueGetResponseV1( + valuetype = valueQueryResult.value.valueTypeIri, + rights = valueQueryResult.permissionCode, + value = valueQueryResult.value, + valuecreator = valueCreatorProfile.userData.email.get, + valuecreatorname = valueCreatorProfile.userData.fullname.get, + valuecreationdate = valueQueryResult.creationDate, + comment = valueQueryResult.comment + ) + + case None => + throw NotFoundException(s"Value $valueIri not found (it may have been deleted)") + } } yield response /** @@ -150,51 +153,51 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde for { // Check that the submitted value has the correct type for the property. entityInfoResponse: EntityInfoGetResponseV1 <- (responderManager ? EntityInfoGetRequestV1( - propertyIris = Set(createValueRequest.propertyIri), - userProfile = createValueRequest.userProfile - )).mapTo[EntityInfoGetResponseV1] + propertyIris = Set(createValueRequest.propertyIri), + userProfile = createValueRequest.userProfile + )).mapTo[EntityInfoGetResponseV1] propertyInfo = entityInfoResponse.propertyInfoMap(createValueRequest.propertyIri) propertyObjectClassConstraint = propertyInfo - .getPredicateObject(OntologyConstants.KnoraBase.ObjectClassConstraint) - .getOrElse { - throw InconsistentRepositoryDataException( - s"Property ${createValueRequest.propertyIri} has no knora-base:objectClassConstraint" - ) - } + .getPredicateObject(OntologyConstants.KnoraBase.ObjectClassConstraint) + .getOrElse { + throw InconsistentRepositoryDataException( + s"Property ${createValueRequest.propertyIri} has no knora-base:objectClassConstraint" + ) + } // Check that the object of the property (the value to be created, or the target of the link to be created) will have // the correct type for the property's knora-base:objectClassConstraint. _ <- checkPropertyObjectClassConstraintForValue( - propertyIri = createValueRequest.propertyIri, - propertyObjectClassConstraint = propertyObjectClassConstraint, - updateValueV1 = createValueRequest.value, - featureFactoryConfig = createValueRequest.featureFactoryConfig, - userProfile = createValueRequest.userProfile - ) + propertyIri = createValueRequest.propertyIri, + propertyObjectClassConstraint = propertyObjectClassConstraint, + updateValueV1 = createValueRequest.value, + featureFactoryConfig = createValueRequest.featureFactoryConfig, + userProfile = createValueRequest.userProfile + ) // Check that the user has permission to modify the resource. (We do this as late as possible because it's // slower than the other checks, and there's no point in doing it if the other checks fail.) resourceFullResponse <- (responderManager ? ResourceFullGetRequestV1( - iri = createValueRequest.resourceIri, - featureFactoryConfig = createValueRequest.featureFactoryConfig, - userADM = createValueRequest.userProfile, - getIncoming = false - )).mapTo[ResourceFullResponseV1] + iri = createValueRequest.resourceIri, + featureFactoryConfig = createValueRequest.featureFactoryConfig, + userADM = createValueRequest.userProfile, + getIncoming = false + )).mapTo[ResourceFullResponseV1] resourcePermissionCode: Option[Int] = resourceFullResponse.resdata.flatMap(resdata => resdata.rights) _ = if ( - !PermissionUtilADM.impliesPermissionCodeV1( - userHasPermissionCode = resourcePermissionCode, - userNeedsPermission = OntologyConstants.KnoraBase.ModifyPermission - ) - ) { - throw ForbiddenException( - s"User $userIri does not have permission to modify resource ${createValueRequest.resourceIri}" - ) - } + !PermissionUtilADM.impliesPermissionCodeV1( + userHasPermissionCode = resourcePermissionCode, + userNeedsPermission = OntologyConstants.KnoraBase.ModifyPermission + ) + ) { + throw ForbiddenException( + s"User $userIri does not have permission to modify resource ${createValueRequest.resourceIri}" + ) + } // Ensure that creating the value would not violate the resource's cardinality restrictions or create a duplicate value. // This works in API v1 because a ResourceFullResponseV1 contains the resource's current property values (but only the @@ -204,43 +207,46 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde // cardinality of MustHaveOne or MayHaveOne, and already has a value that the user isn't allowed to see. We'll have to // implement this in a different way in API v2. cardinalityOK = resourceFullResponse.props.flatMap( - _.properties.find(_.pid == createValueRequest.propertyIri) - ) match { - case Some(prop: PropertyV1) => - if (prop.values.exists(apiValueV1 => createValueRequest.value.isDuplicateOfOtherValue(apiValueV1))) { - throw DuplicateValueException() - } + _.properties.find(_.pid == createValueRequest.propertyIri) + ) match { + case Some(prop: PropertyV1) => + if ( + prop.values + .exists(apiValueV1 => createValueRequest.value.isDuplicateOfOtherValue(apiValueV1)) + ) { + throw DuplicateValueException() + } - val propCardinality = Cardinality.lookup(prop.occurrence.get) - !((propCardinality == Cardinality.MayHaveOne || propCardinality == Cardinality.MustHaveOne) && prop.values.nonEmpty) + val propCardinality = Cardinality.lookup(prop.occurrence.get) + !((propCardinality == Cardinality.MayHaveOne || propCardinality == Cardinality.MustHaveOne) && prop.values.nonEmpty) - case None => - false - } + case None => + false + } _ = if (!cardinalityOK) { - throw OntologyConstraintException( - s"Cardinality restrictions do not allow a value to be added for property ${createValueRequest.propertyIri} of resource ${createValueRequest.resourceIri}" - ) - } + throw OntologyConstraintException( + s"Cardinality restrictions do not allow a value to be added for property ${createValueRequest.propertyIri} of resource ${createValueRequest.resourceIri}" + ) + } // Get the IRI of project of the containing resource. projectIri: IRI = resourceFullResponse.resinfo - .getOrElse( - throw InconsistentRepositoryDataException( - s"Did not find resource info for resource ${createValueRequest.resourceIri}" - ) - ) - .project_id + .getOrElse( + throw InconsistentRepositoryDataException( + s"Did not find resource info for resource ${createValueRequest.resourceIri}" + ) + ) + .project_id // Get the resource class of the containing resource resourceClassIri: IRI = resourceFullResponse.resinfo - .getOrElse( - throw InconsistentRepositoryDataException( - s"Did not find resource info for resource ${createValueRequest.resourceIri}" - ) - ) - .restype_id + .getOrElse( + throw InconsistentRepositoryDataException( + s"Did not find resource info for resource ${createValueRequest.resourceIri}" + ) + ) + .restype_id defaultObjectAccessPermissions <- { responderManager ? DefaultObjectAccessPermissionsStringForPropertyGetADM( @@ -263,51 +269,51 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde }.mapTo[Option[ProjectInfoV1]] projectInfo = maybeProjectInfo match { - case Some(pi) => pi - case None => throw NotFoundException(s"Project '$projectIri' not found.") - } + case Some(pi) => pi + case None => throw NotFoundException(s"Project '$projectIri' not found.") + } // Everything seems OK, so create the value. unverifiedValue <- createValueV1AfterChecks( - dataNamedGraph = StringFormatter.getGeneralInstance.projectDataNamedGraphV1(projectInfo), - projectIri = resourceFullResponse.resinfo.get.project_id, - resourceIri = createValueRequest.resourceIri, - propertyIri = createValueRequest.propertyIri, - value = createValueRequest.value, - comment = createValueRequest.comment, - valueCreator = userIri, - valuePermissions = defaultObjectAccessPermissions.permissionLiteral, - featureFactoryConfig = createValueRequest.featureFactoryConfig, - userProfile = createValueRequest.userProfile - ) + dataNamedGraph = StringFormatter.getGeneralInstance.projectDataNamedGraphV1(projectInfo), + projectIri = resourceFullResponse.resinfo.get.project_id, + resourceIri = createValueRequest.resourceIri, + propertyIri = createValueRequest.propertyIri, + value = createValueRequest.value, + comment = createValueRequest.comment, + valueCreator = userIri, + valuePermissions = defaultObjectAccessPermissions.permissionLiteral, + featureFactoryConfig = createValueRequest.featureFactoryConfig, + userProfile = createValueRequest.userProfile + ) // Verify that it was created. apiResponse <- verifyValueCreation( - resourceIri = createValueRequest.resourceIri, - propertyIri = createValueRequest.propertyIri, - unverifiedValue = unverifiedValue, - featureFactoryConfig = createValueRequest.featureFactoryConfig, - userProfile = createValueRequest.userProfile - ) + resourceIri = createValueRequest.resourceIri, + propertyIri = createValueRequest.propertyIri, + unverifiedValue = unverifiedValue, + featureFactoryConfig = createValueRequest.featureFactoryConfig, + userProfile = createValueRequest.userProfile + ) } yield apiResponse for { // Don't allow anonymous users to create values. userIri <- Future { - if (createValueRequest.userProfile.isAnonymousUser) { - throw ForbiddenException("Anonymous users aren't allowed to create values") - } else { - createValueRequest.userProfile.id - } - } + if (createValueRequest.userProfile.isAnonymousUser) { + throw ForbiddenException("Anonymous users aren't allowed to create values") + } else { + createValueRequest.userProfile.id + } + } // Do the remaining pre-update checks and the update while holding an update lock on the resource. taskResult <- IriLocker.runWithIriLock( - createValueRequest.apiRequestID, - createValueRequest.resourceIri, - () => makeTaskFuture(userIri) - ) + createValueRequest.apiRequestID, + createValueRequest.resourceIri, + () => makeTaskFuture(userIri) + ) } yield taskResult } @@ -375,20 +381,20 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde // that have standoff references to a particular target resource. // First, make a single list of all the values to be created. - valuesToCreatePerProperty: Map[IRI, Seq[CreateValueV1WithComment]] <- Future(createMultipleValuesRequest.values) + valuesToCreatePerProperty: Map[IRI, Seq[CreateValueV1WithComment]] <- Future(createMultipleValuesRequest.values) valuesToCreateForAllProperties: Iterable[Seq[CreateValueV1WithComment]] = valuesToCreatePerProperty.values - allValuesToCreate: Iterable[CreateValueV1WithComment] = valuesToCreateForAllProperties.flatten + allValuesToCreate: Iterable[CreateValueV1WithComment] = valuesToCreateForAllProperties.flatten // Then, get the standoff resource references from all the text values to be created. // The 'collect' method builds a new list by applying a partial function to all elements of the list // on which the function is defined. - resourceReferencesForAllTextValues: Iterable[Set[IRI]] = allValuesToCreate.collect { - case CreateValueV1WithComment(textValueV1: TextValueWithStandoffV1, _) => + resourceReferencesForAllTextValues: Iterable[Set[IRI]] = + allValuesToCreate.collect { case CreateValueV1WithComment(textValueV1: TextValueWithStandoffV1, _) => // check that resource references are consistent in `resource_reference` and linking standoff tags checkTextValueResourceRefs(textValueV1) textValueV1.resource_reference - } + } // Combine those resource references into a single list, so if there are n text values with a reference to // some IRI, the list will contain that IRI n times. @@ -418,81 +424,101 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde // // So now we can get the set of standoff link targets that are ordinary IRIs, and check that each of // them exists in the triplestore and is a knora-base:Resource. - targetIrisThatAlreadyExist: Set[IRI] = targetIris.keySet.filterNot(iri => - stringFormatter.isStandoffLinkReferenceToClientIDForResource(iri) - ) + targetIrisThatAlreadyExist: Set[IRI] = + targetIris.keySet.filterNot(iri => stringFormatter.isStandoffLinkReferenceToClientIDForResource(iri)) targetIriCheckResult <- checkStandoffResourceReferenceTargets( - targetIris = targetIrisThatAlreadyExist, - featureFactoryConfig = createMultipleValuesRequest.featureFactoryConfig, - userProfile = createMultipleValuesRequest.userProfile - ) + targetIris = targetIrisThatAlreadyExist, + featureFactoryConfig = createMultipleValuesRequest.featureFactoryConfig, + userProfile = createMultipleValuesRequest.userProfile + ) // For each target IRI, construct a SparqlTemplateLinkUpdate to create a hasStandoffLinkTo property and one LinkValue, // with the associated count as the LinkValue's initial reference count. standoffLinkUpdates: Seq[SparqlTemplateLinkUpdate] = targetIris.toSeq.map { - case (targetIri, initialReferenceCount) => - // If the target of a standoff link is a client ID for a resource, convert it to the corresponding real resource IRI. - val realTargetIri = stringFormatter.toRealStandoffLinkTargetResourceIri( - iri = targetIri, - clientResourceIDsToResourceIris = createMultipleValuesRequest.clientResourceIDsToResourceIris - ) - - SparqlTemplateLinkUpdate( - linkPropertyIri = OntologyConstants.KnoraBase.HasStandoffLinkTo.toSmartIri, - directLinkExists = false, - insertDirectLink = true, - deleteDirectLink = false, - linkValueExists = false, - linkTargetExists = - true, // doesn't matter, the generateInsertStatementsForStandoffLinks template doesn't use it - newLinkValueIri = stringFormatter.makeRandomValueIri(createMultipleValuesRequest.resourceIri), - linkTargetIri = realTargetIri, - currentReferenceCount = 0, - newReferenceCount = initialReferenceCount, - newLinkValueCreator = OntologyConstants.KnoraAdmin.SystemUser, - newLinkValuePermissions = standoffLinkValuePermissions - ) - } + case (targetIri, initialReferenceCount) => + // If the target of a standoff link is a client ID for a resource, convert it to the corresponding real resource IRI. + val realTargetIri = + stringFormatter.toRealStandoffLinkTargetResourceIri( + iri = targetIri, + clientResourceIDsToResourceIris = + createMultipleValuesRequest.clientResourceIDsToResourceIris + ) + + SparqlTemplateLinkUpdate( + linkPropertyIri = + OntologyConstants.KnoraBase.HasStandoffLinkTo.toSmartIri, + directLinkExists = false, + insertDirectLink = true, + deleteDirectLink = false, + linkValueExists = false, + linkTargetExists = + true, // doesn't matter, the generateInsertStatementsForStandoffLinks template doesn't use it + newLinkValueIri = stringFormatter.makeRandomValueIri( + createMultipleValuesRequest.resourceIri + ), + linkTargetIri = realTargetIri, + currentReferenceCount = 0, + newReferenceCount = initialReferenceCount, + newLinkValueCreator = + OntologyConstants.KnoraAdmin.SystemUser, + newLinkValuePermissions = + standoffLinkValuePermissions + ) + } // Generate INSERT clause statements based on those SparqlTemplateLinkUpdates. standoffLinkInsertSparql: String = org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .generateInsertStatementsForStandoffLinks( - resourceIri = createMultipleValuesRequest.resourceIri, - linkUpdates = standoffLinkUpdates, - creationDate = createMultipleValuesRequest.creationDate, - stringFormatter = stringFormatter - ) - .toString() + .generateInsertStatementsForStandoffLinks( + resourceIri = createMultipleValuesRequest.resourceIri, + linkUpdates = standoffLinkUpdates, + creationDate = createMultipleValuesRequest.creationDate, + stringFormatter = stringFormatter + ) + .toString() //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Number each value to be created, and give it a valueHasOrder // Ungroup the values to be created so we can number them as a single sequence (to create unique SPARQL variable names for each value). - ungroupedValues: Seq[(IRI, CreateValueV1WithComment)] = createMultipleValuesRequest.values.toSeq.flatMap { - case (propertyIri, values) => values.map(value => (propertyIri, value)) - } + ungroupedValues: Seq[(IRI, CreateValueV1WithComment)] = + createMultipleValuesRequest.values.toSeq.flatMap { case (propertyIri, values) => + values.map(value => (propertyIri, value)) + } // Number them all as a single sequence. Give each one a knora-base:valueHasOrder of 0 for now; we'll take care of that in a moment. - numberedValues: Seq[(IRI, NumberedValueToCreate)] = ungroupedValues.zipWithIndex.map { - case ((propertyIri: IRI, valueWithComment: CreateValueV1WithComment), valueIndex) => - (propertyIri, NumberedValueToCreate(valueWithComment, valueIndex, 0)) - } + numberedValues: Seq[(IRI, NumberedValueToCreate)] = + ungroupedValues.zipWithIndex.map { + case ((propertyIri: IRI, valueWithComment: CreateValueV1WithComment), valueIndex) => + (propertyIri, NumberedValueToCreate(valueWithComment, valueIndex, 0)) + } // Group them again by property so we generate knora-base:valueHasOrder for the values of each property. - groupedNumberedValues: Map[IRI, Seq[NumberedValueToCreate]] = numberedValues.groupBy(_._1).map { - case (propertyIri, propertyIriAndValueTuples) => (propertyIri, propertyIriAndValueTuples.map(_._2)) - } + groupedNumberedValues: Map[IRI, Seq[NumberedValueToCreate]] = + numberedValues.groupBy(_._1).map { case (propertyIri, propertyIriAndValueTuples) => + (propertyIri, propertyIriAndValueTuples.map(_._2)) + } // Generate knora-base:valueHasOrder for the values of each property. groupedNumberedValuesWithValueHasOrder: Map[IRI, Seq[NumberedValueToCreate]] = groupedNumberedValues.map { - case (propertyIri, values) => - val valuesWithValueHasOrder = values.zipWithIndex.map { case (numberedValueToCreate, valueHasOrder) => - numberedValueToCreate.copy(valueHasOrder = valueHasOrder) - } - - (propertyIri, valuesWithValueHasOrder) - } + case (propertyIri, values) => + val valuesWithValueHasOrder = + values.zipWithIndex.map { + case ( + numberedValueToCreate, + valueHasOrder + ) => + numberedValueToCreate + .copy(valueHasOrder = + valueHasOrder + ) + } + + ( + propertyIri, + valuesWithValueHasOrder + ) + } //////////////////////////////////////////////////////////////////////////////////////////////////////////// // Generate SPARQL for each value of each property @@ -511,7 +537,7 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde valuesToCreate.foldLeft(SparqlGenerationResultForProperty()) { case (propertyAcc: SparqlGenerationResultForProperty, valueToCreate: NumberedValueToCreate) => val updateValueV1 = valueToCreate.createValueV1WithComment.updateValueV1 - val newValueIri = stringFormatter.makeRandomValueIri(createMultipleValuesRequest.resourceIri) + val newValueIri = stringFormatter.makeRandomValueIri(createMultipleValuesRequest.resourceIri) // How we generate the SPARQL depends on whether we're creating a link or an ordinary value. val insertSparql: String = valueToCreate.createValueV1WithComment.updateValueV1 match { @@ -623,16 +649,17 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde // The SPARQL for the INSERT clause also contains the SPARQL that was generated to insert standoff links. allInsertSparql: String = resultsForAllProperties - .flatMap(result => result.insertSparql.zip(result.valueIndexes)) - .toSeq - .sortBy(_._2) - .map(_._1) - .mkString("\n\n") + standoffLinkInsertSparql + .flatMap(result => result.insertSparql.zip(result.valueIndexes)) + .toSeq + .sortBy(_._2) + .map(_._1) + .mkString("\n\n") + standoffLinkInsertSparql // Collect all the UnverifiedValueV1s for each property. - allUnverifiedValues: Map[IRI, Seq[UnverifiedValueV1]] = sparqlGenerationResults.map { - case (propertyIri, results) => propertyIri -> results.valuesToVerify - } + allUnverifiedValues: Map[IRI, Seq[UnverifiedValueV1]] = + sparqlGenerationResults.map { case (propertyIri, results) => + propertyIri -> results.valuesToVerify + } } yield GenerateSparqlToCreateMultipleValuesResponseV1( insertSparql = allInsertSparql, @@ -643,19 +670,19 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde for { // Don't allow anonymous users to create resources. userIri <- Future { - if (createMultipleValuesRequest.userProfile.isAnonymousUser) { - throw ForbiddenException("Anonymous users aren't allowed to create resources") - } else { - createMultipleValuesRequest.userProfile.id - } - } + if (createMultipleValuesRequest.userProfile.isAnonymousUser) { + throw ForbiddenException("Anonymous users aren't allowed to create resources") + } else { + createMultipleValuesRequest.userProfile.id + } + } // Do the remaining pre-update checks and the update while holding an update lock on the resource. taskResult <- IriLocker.runWithIriLock( - createMultipleValuesRequest.apiRequestID, - createMultipleValuesRequest.resourceIri, - () => makeTaskFuture(userIri) - ) + createMultipleValuesRequest.apiRequestID, + createMultipleValuesRequest.resourceIri, + () => makeTaskFuture(userIri) + ) } yield taskResult } @@ -690,8 +717,8 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde // when they're available. for { valueVerificationResponses: Map[IRI, Seq[CreateValueResponseV1]] <- ActorUtil.sequenceFutureSeqsInMap( - valueVerificationFutures - ) + valueVerificationFutures + ) } yield VerifyMultipleValueCreationResponseV1(verifiedValues = valueVerificationResponses) } @@ -731,52 +758,53 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde resourceIri <- Future(changeFileValueRequest.resourceIri) getFileValuesSparql = org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getFileValuesForResource( - resourceIri = resourceIri - ) - .toString() + .getFileValuesForResource( + resourceIri = resourceIri + ) + .toString() //_ = print(getFileValuesSparql) getFileValuesResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(getFileValuesSparql)) - .mapTo[SparqlSelectResult] + .mapTo[SparqlSelectResult] // _ <- Future(println(getFileValuesResponse)) // check that the resource to be updated exists and it is a subclass of knora-base:Representation - _ = if (getFileValuesResponse.results.bindings.isEmpty) - throw NotFoundException( - s"Value ${changeFileValueRequest.resourceIri} not found (it may have been deleted) or it is not a knora-base:Representation" - ) + _ = + if (getFileValuesResponse.results.bindings.isEmpty) + throw NotFoundException( + s"Value ${changeFileValueRequest.resourceIri} not found (it may have been deleted) or it is not a knora-base:Representation" + ) // get the property Iris, file value Iris and qualities attached to the resource fileValues: Seq[CurrentFileValue] = getFileValuesResponse.results.bindings.map { row: VariableResultsRow => - CurrentFileValue( - property = row.rowMap("p"), - valueObjectIri = row.rowMap("fileValueIri"), - quality = row.rowMap.get("quality") match { - case Some(quality: String) => Some(quality.toInt) - case None => None - } - ) - } + CurrentFileValue( + property = row.rowMap("p"), + valueObjectIri = row.rowMap("fileValueIri"), + quality = row.rowMap.get("quality") match { + case Some(quality: String) => Some(quality.toInt) + case None => None + } + ) + } // TODO: check if the file type returned by Sipi corresponds to the already existing file value type response: ChangeValueResponseV1 <- changeValueV1( - ChangeValueRequestV1( - valueIri = fileValues.head.valueObjectIri, - value = changeFileValueRequest.file, - featureFactoryConfig = changeFileValueRequest.featureFactoryConfig, - userProfile = changeFileValueRequest.userProfile, - apiRequestID = changeFileValueRequest.apiRequestID // re-use the same id - ) - ) + ChangeValueRequestV1( + valueIri = fileValues.head.valueObjectIri, + value = changeFileValueRequest.file, + featureFactoryConfig = changeFileValueRequest.featureFactoryConfig, + userProfile = changeFileValueRequest.userProfile, + apiRequestID = changeFileValueRequest.apiRequestID // re-use the same id + ) + ) changedLocation = response.value match { - case fileValueV1: FileValueV1 => valueUtilV1.fileValueV12LocationV1(fileValueV1) - case other => - throw AssertionException( - s"Expected Sipi to change a file value, but it changed one of these: ${other.valueTypeIri}" - ) - } + case fileValueV1: FileValueV1 => valueUtilV1.fileValueV12LocationV1(fileValueV1) + case other => + throw AssertionException( + s"Expected Sipi to change a file value, but it changed one of these: ${other.valueTypeIri}" + ) + } } yield ChangeFileValueResponseV1( locations = Vector(changedLocation), projectADM = projectADM @@ -794,10 +822,10 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde for { resourceInfoResponse <- (responderManager ? ResourceInfoGetRequestV1( - iri = changeFileValueRequest.resourceIri, - featureFactoryConfig = changeFileValueRequest.featureFactoryConfig, - userProfile = changeFileValueRequest.userProfile - )).mapTo[ResourceInfoResponseV1] + iri = changeFileValueRequest.resourceIri, + featureFactoryConfig = changeFileValueRequest.featureFactoryConfig, + userProfile = changeFileValueRequest.userProfile + )).mapTo[ResourceInfoResponseV1] // Get project info projectResponse <- { @@ -814,10 +842,10 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde // // The method `changeValueV1` will be called using the same lock. taskResult <- IriLocker.runWithIriLock( - changeFileValueRequest.apiRequestID, - changeFileValueRequest.resourceIri, - () => makeTaskFuture(changeFileValueRequest, projectResponse.project) - ) + changeFileValueRequest.apiRequestID, + changeFileValueRequest.resourceIri, + () => makeTaskFuture(changeFileValueRequest, projectResponse.project) + ) } yield taskResult } @@ -858,125 +886,135 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde for { // Ensure that the user has permission to modify the value. maybeCurrentValueQueryResult: Option[ValueQueryResult] <- changeValueRequest.value match { - case linkUpdateV1: LinkUpdateV1 => - // We're being asked to update a link. We expect the current value version IRI to point to a - // knora-base:LinkValue. Get all necessary information about the LinkValue and the corresponding - // direct link. - findLinkValueByIri( - subjectIri = findResourceWithValueResult.resourceIri, - predicateIri = propertyIri, - objectIri = None, - linkValueIri = changeValueRequest.valueIri, - featureFactoryConfig = changeValueRequest.featureFactoryConfig, - userProfile = changeValueRequest.userProfile - ) - - case otherValueV1 => - // We're being asked to update an ordinary value. - findValue( - valueIri = changeValueRequest.valueIri, - featureFactoryConfig = changeValueRequest.featureFactoryConfig, - userProfile = changeValueRequest.userProfile - ) - } - - currentValueQueryResult = maybeCurrentValueQueryResult.getOrElse( - throw NotFoundException(s"Value ${changeValueRequest.valueIri} not found (it may have been deleted)") - ) + case linkUpdateV1: LinkUpdateV1 => + // We're being asked to update a link. We expect the current value version IRI to point to a + // knora-base:LinkValue. Get all necessary information about the LinkValue and the corresponding + // direct link. + findLinkValueByIri( + subjectIri = + findResourceWithValueResult.resourceIri, + predicateIri = propertyIri, + objectIri = None, + linkValueIri = changeValueRequest.valueIri, + featureFactoryConfig = + changeValueRequest.featureFactoryConfig, + userProfile = changeValueRequest.userProfile + ) + + case otherValueV1 => + // We're being asked to update an ordinary value. + findValue( + valueIri = changeValueRequest.valueIri, + featureFactoryConfig = + changeValueRequest.featureFactoryConfig, + userProfile = changeValueRequest.userProfile + ) + } + + currentValueQueryResult = + maybeCurrentValueQueryResult.getOrElse( + throw NotFoundException(s"Value ${changeValueRequest.valueIri} not found (it may have been deleted)") + ) _ = if ( - !PermissionUtilADM.impliesPermissionCodeV1( - userHasPermissionCode = Some(currentValueQueryResult.permissionCode), - userNeedsPermission = OntologyConstants.KnoraBase.ModifyPermission - ) - ) { - throw ForbiddenException( - s"User $userIri does not have permission to add a new version to value ${changeValueRequest.valueIri}" - ) - } + !PermissionUtilADM.impliesPermissionCodeV1( + userHasPermissionCode = Some(currentValueQueryResult.permissionCode), + userNeedsPermission = OntologyConstants.KnoraBase.ModifyPermission + ) + ) { + throw ForbiddenException( + s"User $userIri does not have permission to add a new version to value ${changeValueRequest.valueIri}" + ) + } // Check that the submitted value has the correct type for the property. entityInfoResponse <- (responderManager ? EntityInfoGetRequestV1( - propertyIris = Set(propertyIri), - userProfile = changeValueRequest.userProfile - )).mapTo[EntityInfoGetResponseV1] + propertyIris = Set(propertyIri), + userProfile = changeValueRequest.userProfile + )).mapTo[EntityInfoGetResponseV1] propertyInfo = entityInfoResponse.propertyInfoMap(propertyIri) propertyObjectClassConstraint = propertyInfo - .getPredicateObject(OntologyConstants.KnoraBase.ObjectClassConstraint) - .getOrElse { - throw InconsistentRepositoryDataException(s"Property $propertyIri has no knora-base:objectClassConstraint") - } + .getPredicateObject(OntologyConstants.KnoraBase.ObjectClassConstraint) + .getOrElse { + throw InconsistentRepositoryDataException( + s"Property $propertyIri has no knora-base:objectClassConstraint" + ) + } // Check that the object of the property (the value to be updated, or the target of the link to be updated) will have // the correct type for the property's knora-base:objectClassConstraint. _ <- checkPropertyObjectClassConstraintForValue( - propertyIri = propertyIri, - propertyObjectClassConstraint = propertyObjectClassConstraint, - updateValueV1 = changeValueRequest.value, - featureFactoryConfig = changeValueRequest.featureFactoryConfig, - userProfile = changeValueRequest.userProfile - ) + propertyIri = propertyIri, + propertyObjectClassConstraint = propertyObjectClassConstraint, + updateValueV1 = changeValueRequest.value, + featureFactoryConfig = changeValueRequest.featureFactoryConfig, + userProfile = changeValueRequest.userProfile + ) // Check that the current value and the submitted value have the same type. _ = if (currentValueQueryResult.value.valueTypeIri != changeValueRequest.value.valueTypeIri) { - throw BadRequestException( - s"Value ${changeValueRequest.valueIri} has type ${currentValueQueryResult.value.valueTypeIri}, but the submitted new version has type ${changeValueRequest.value.valueTypeIri}" - ) - } + throw BadRequestException( + s"Value ${changeValueRequest.valueIri} has type ${currentValueQueryResult.value.valueTypeIri}, but the submitted new version has type ${changeValueRequest.value.valueTypeIri}" + ) + } // Make sure the new version would not be redundant, given the current version. _ = if (changeValueRequest.value.isRedundant(currentValueQueryResult.value)) { - throw DuplicateValueException("The submitted value is the same as the current version") - } + throw DuplicateValueException("The submitted value is the same as the current version") + } // Get details of the resource. (We do this as late as possible because it's slower than the other checks, // and there's no point in doing it if the other checks fail.) resourceFullResponse <- (responderManager ? ResourceFullGetRequestV1( - iri = findResourceWithValueResult.resourceIri, - featureFactoryConfig = changeValueRequest.featureFactoryConfig, - userADM = changeValueRequest.userProfile, - getIncoming = false - )).mapTo[ResourceFullResponseV1] + iri = findResourceWithValueResult.resourceIri, + featureFactoryConfig = changeValueRequest.featureFactoryConfig, + userADM = changeValueRequest.userProfile, + getIncoming = false + )).mapTo[ResourceFullResponseV1] _ = changeValueRequest.value match { - case _: FileValueV1 => () // It is a file value, do not check for duplicates. - case _ => // It is not a file value. - // Ensure that adding the new value version would not create a duplicate value. This works in API v1 because a - // ResourceFullResponseV1 contains only the values that the user is allowed to see, otherwise checking for - // duplicate values would be a security risk. We'll have to implement this in a different way in API v2. - resourceFullResponse.props.flatMap(_.properties.find(_.pid == propertyIri)) match { - case Some(prop: PropertyV1) => - // Don't consider the current value version when looking for duplicates. - val filteredValues = - prop.value_ids.zip(prop.values).filter(_._1 != changeValueRequest.valueIri).map(_._2) - - if (filteredValues.exists(apiValueV1 => changeValueRequest.value.isDuplicateOfOtherValue(apiValueV1))) { - throw DuplicateValueException() + case _: FileValueV1 => () // It is a file value, do not check for duplicates. + case _ => // It is not a file value. + // Ensure that adding the new value version would not create a duplicate value. This works in API v1 because a + // ResourceFullResponseV1 contains only the values that the user is allowed to see, otherwise checking for + // duplicate values would be a security risk. We'll have to implement this in a different way in API v2. + resourceFullResponse.props.flatMap(_.properties.find(_.pid == propertyIri)) match { + case Some(prop: PropertyV1) => + // Don't consider the current value version when looking for duplicates. + val filteredValues = + prop.value_ids.zip(prop.values).filter(_._1 != changeValueRequest.valueIri).map(_._2) + + if ( + filteredValues.exists(apiValueV1 => changeValueRequest.value.isDuplicateOfOtherValue(apiValueV1)) + ) { + throw DuplicateValueException() + } + + case None => + // This shouldn't happen unless someone just changed the ontology. + throw NotFoundException( + s"No information found about property $propertyIri for resource ${findResourceWithValueResult.resourceIri}" + ) } - case None => - // This shouldn't happen unless someone just changed the ontology. - throw NotFoundException( - s"No information found about property $propertyIri for resource ${findResourceWithValueResult.resourceIri}" - ) } - } - // Get the resource class of the containing resource - resourceClassIri: IRI = resourceFullResponse.resinfo - .getOrElse( - throw InconsistentRepositoryDataException( - s"Did not find resource info for resource ${findResourceWithValueResult.resourceIri}" + resourceClassIri: IRI = + resourceFullResponse.resinfo + .getOrElse( + throw InconsistentRepositoryDataException( + s"Did not find resource info for resource ${findResourceWithValueResult.resourceIri}" + ) ) - ) - .restype_id + .restype_id - _ = log.debug( - s"changeValueV1 - DefaultObjectAccessPermissionsStringForPropertyGetV1 - projectIri ${findResourceWithValueResult.projectIri}, propertyIri: ${findResourceWithValueResult.propertyIri}, permissions: ${changeValueRequest.userProfile.permissions} " - ) + _ = + log.debug( + s"changeValueV1 - DefaultObjectAccessPermissionsStringForPropertyGetV1 - projectIri ${findResourceWithValueResult.projectIri}, propertyIri: ${findResourceWithValueResult.propertyIri}, permissions: ${changeValueRequest.userProfile.permissions} " + ) defaultObjectAccessPermissions <- { responderManager ? DefaultObjectAccessPermissionsStringForPropertyGetADM( projectIri = findResourceWithValueResult.projectIri, @@ -998,94 +1036,100 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde }.mapTo[Option[ProjectInfoV1]] projectInfo = maybeProjectInfo match { - case Some(pi) => pi - case None => throw NotFoundException(s"Project '${resourceFullResponse.resinfo.get.project_id}' not found.") - } + case Some(pi) => pi + case None => + throw NotFoundException( + s"Project '${resourceFullResponse.resinfo.get.project_id}' not found." + ) + } // The rest of the preparation for the update depends on whether we're changing a link or an ordinary value. apiResponse <- (changeValueRequest.value, currentValueQueryResult) match { - case (linkUpdateV1: LinkUpdateV1, currentLinkValueQueryResult: LinkValueQueryResult) => - // We're updating a link. This means deleting an existing link and creating a new one, so - // check that the user has permission to modify the resource. - val resourcePermissionCode = resourceFullResponse.resdata.flatMap(resdata => resdata.rights) - if ( - !PermissionUtilADM.impliesPermissionCodeV1( - userHasPermissionCode = resourcePermissionCode, - userNeedsPermission = OntologyConstants.KnoraBase.ModifyPermission - ) - ) { - throw ForbiddenException( - s"User $userIri does not have permission to modify resource ${findResourceWithValueResult.resourceIri}" - ) - } - - // We'll need to create a new LinkValue. - - changeLinkValueV1AfterChecks( - projectIri = currentValueQueryResult.projectIri, - dataNamedGraph = StringFormatter.getGeneralInstance.projectDataNamedGraphV1(projectInfo), - resourceIri = findResourceWithValueResult.resourceIri, - propertyIri = propertyIri, - currentLinkValueV1 = currentLinkValueQueryResult.value, - linkUpdateV1 = linkUpdateV1, - comment = changeValueRequest.comment, - valueCreator = userIri, - valuePermissions = defaultObjectAccessPermissions.permissionLiteral, - featureFactoryConfig = changeValueRequest.featureFactoryConfig, - userProfile = changeValueRequest.userProfile - ) - - case _ => - // We're updating an ordinary value. Generate an IRI for the new version of the value. - val newValueIri = stringFormatter.makeRandomValueIri(findResourceWithValueResult.resourceIri) - - // Give the new version the same permissions as the previous version. - - val valuePermissions = currentValueQueryResult.permissionRelevantAssertions.find { case (p, o) => - p == OntologyConstants.KnoraBase.HasPermissions - } - .map(_._2) - .getOrElse( - throw InconsistentRepositoryDataException(s"Value ${changeValueRequest.valueIri} has no permissions") - ) - - changeOrdinaryValueV1AfterChecks( - projectIri = currentValueQueryResult.projectIri, - resourceIri = findResourceWithValueResult.resourceIri, - propertyIri = propertyIri, - currentValueIri = changeValueRequest.valueIri, - currentValueV1 = currentValueQueryResult.value, - newValueIri = newValueIri, - updateValueV1 = changeValueRequest.value, - comment = changeValueRequest.comment, - valueCreator = userIri, - valuePermissions = valuePermissions, - featureFactoryConfig = changeValueRequest.featureFactoryConfig, - userProfile = changeValueRequest.userProfile - ) - } + case (linkUpdateV1: LinkUpdateV1, currentLinkValueQueryResult: LinkValueQueryResult) => + // We're updating a link. This means deleting an existing link and creating a new one, so + // check that the user has permission to modify the resource. + val resourcePermissionCode = resourceFullResponse.resdata.flatMap(resdata => resdata.rights) + if ( + !PermissionUtilADM.impliesPermissionCodeV1( + userHasPermissionCode = resourcePermissionCode, + userNeedsPermission = OntologyConstants.KnoraBase.ModifyPermission + ) + ) { + throw ForbiddenException( + s"User $userIri does not have permission to modify resource ${findResourceWithValueResult.resourceIri}" + ) + } + + // We'll need to create a new LinkValue. + + changeLinkValueV1AfterChecks( + projectIri = currentValueQueryResult.projectIri, + dataNamedGraph = StringFormatter.getGeneralInstance.projectDataNamedGraphV1(projectInfo), + resourceIri = findResourceWithValueResult.resourceIri, + propertyIri = propertyIri, + currentLinkValueV1 = currentLinkValueQueryResult.value, + linkUpdateV1 = linkUpdateV1, + comment = changeValueRequest.comment, + valueCreator = userIri, + valuePermissions = defaultObjectAccessPermissions.permissionLiteral, + featureFactoryConfig = changeValueRequest.featureFactoryConfig, + userProfile = changeValueRequest.userProfile + ) + + case _ => + // We're updating an ordinary value. Generate an IRI for the new version of the value. + val newValueIri = stringFormatter.makeRandomValueIri(findResourceWithValueResult.resourceIri) + + // Give the new version the same permissions as the previous version. + + val valuePermissions = currentValueQueryResult.permissionRelevantAssertions.find { + case (p, o) => + p == OntologyConstants.KnoraBase.HasPermissions + } + .map(_._2) + .getOrElse( + throw InconsistentRepositoryDataException( + s"Value ${changeValueRequest.valueIri} has no permissions" + ) + ) + + changeOrdinaryValueV1AfterChecks( + projectIri = currentValueQueryResult.projectIri, + resourceIri = findResourceWithValueResult.resourceIri, + propertyIri = propertyIri, + currentValueIri = changeValueRequest.valueIri, + currentValueV1 = currentValueQueryResult.value, + newValueIri = newValueIri, + updateValueV1 = changeValueRequest.value, + comment = changeValueRequest.comment, + valueCreator = userIri, + valuePermissions = valuePermissions, + featureFactoryConfig = changeValueRequest.featureFactoryConfig, + userProfile = changeValueRequest.userProfile + ) + } } yield apiResponse } for { // Don't allow anonymous users to update values. userIri <- Future { - if (changeValueRequest.userProfile.isAnonymousUser) { - throw ForbiddenException("Anonymous users aren't allowed to update values") - } else { - changeValueRequest.userProfile.id - } - } + if (changeValueRequest.userProfile.isAnonymousUser) { + throw ForbiddenException("Anonymous users aren't allowed to update values") + } else { + changeValueRequest.userProfile.id + } + } // Find the resource containing the value. findResourceWithValueResult <- findResourceWithValue(changeValueRequest.valueIri) // Do the remaining pre-update checks and the update while holding an update lock on the resource. taskResult <- IriLocker.runWithIriLock( - changeValueRequest.apiRequestID, - findResourceWithValueResult.resourceIri, - () => makeTaskFuture(userIri, findResourceWithValueResult) - ) + changeValueRequest.apiRequestID, + findResourceWithValueResult.resourceIri, + () => makeTaskFuture(userIri, findResourceWithValueResult) + ) } yield taskResult } @@ -1105,29 +1149,31 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde for { // Ensure that the user has permission to modify the value. maybeCurrentValueQueryResult: Option[ValueQueryResult] <- findValue( - valueIri = changeCommentRequest.valueIri, - featureFactoryConfig = changeCommentRequest.featureFactoryConfig, - userProfile = changeCommentRequest.userProfile - ) - - currentValueQueryResult = maybeCurrentValueQueryResult.getOrElse( - throw NotFoundException(s"Value ${changeCommentRequest.valueIri} not found (it may have been deleted)") - ) + valueIri = changeCommentRequest.valueIri, + featureFactoryConfig = + changeCommentRequest.featureFactoryConfig, + userProfile = changeCommentRequest.userProfile + ) + + currentValueQueryResult = + maybeCurrentValueQueryResult.getOrElse( + throw NotFoundException(s"Value ${changeCommentRequest.valueIri} not found (it may have been deleted)") + ) _ = if ( - !PermissionUtilADM.impliesPermissionCodeV1( - userHasPermissionCode = Some(currentValueQueryResult.permissionCode), - userNeedsPermission = OntologyConstants.KnoraBase.ModifyPermission - ) - ) { - throw ForbiddenException( - s"User $userIri does not have permission to add a new version to value ${changeCommentRequest.valueIri}" - ) - } + !PermissionUtilADM.impliesPermissionCodeV1( + userHasPermissionCode = Some(currentValueQueryResult.permissionCode), + userNeedsPermission = OntologyConstants.KnoraBase.ModifyPermission + ) + ) { + throw ForbiddenException( + s"User $userIri does not have permission to add a new version to value ${changeCommentRequest.valueIri}" + ) + } // currentValueQueryResult.comment is an Option[String] _ = if (currentValueQueryResult.comment == changeCommentRequest.comment) - throw DuplicateValueException("The submitted comment is the same as the current comment") + throw DuplicateValueException("The submitted comment is the same as the current comment") // Everything looks OK, so update the comment. @@ -1144,37 +1190,38 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde }.mapTo[Option[ProjectInfoV1]] projectInfo = maybeProjectInfo match { - case Some(pi) => pi - case None => throw NotFoundException(s"Project '${findResourceWithValueResult.projectIri}' not found.") - } + case Some(pi) => pi + case None => + throw NotFoundException(s"Project '${findResourceWithValueResult.projectIri}' not found.") + } // Make a timestamp to indicate when the value was updated. currentTime: String = Instant.now.toString // Generate a SPARQL update. sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .changeComment( - dataNamedGraph = StringFormatter.getGeneralInstance.projectDataNamedGraphV1(projectInfo), - resourceIri = findResourceWithValueResult.resourceIri, - propertyIri = findResourceWithValueResult.propertyIri, - currentValueIri = changeCommentRequest.valueIri, - newValueIri = newValueIri, - maybeComment = changeCommentRequest.comment, - currentTime = currentTime - ) - .toString() + .changeComment( + dataNamedGraph = StringFormatter.getGeneralInstance.projectDataNamedGraphV1(projectInfo), + resourceIri = findResourceWithValueResult.resourceIri, + propertyIri = findResourceWithValueResult.propertyIri, + currentValueIri = changeCommentRequest.valueIri, + newValueIri = newValueIri, + maybeComment = changeCommentRequest.comment, + currentTime = currentTime + ) + .toString() // Do the update. sparqlUpdateResponse <- (storeManager ? SparqlUpdateRequest(sparqlUpdate)).mapTo[SparqlUpdateResponse] // To find out whether the update succeeded, look for the new value in the triplestore. verifyUpdateResult <- verifyOrdinaryValueUpdate( - resourceIri = findResourceWithValueResult.resourceIri, - propertyIri = findResourceWithValueResult.propertyIri, - searchValueIri = newValueIri, - featureFactoryConfig = changeCommentRequest.featureFactoryConfig, - userProfile = changeCommentRequest.userProfile - ) + resourceIri = findResourceWithValueResult.resourceIri, + propertyIri = findResourceWithValueResult.propertyIri, + searchValueIri = newValueIri, + featureFactoryConfig = changeCommentRequest.featureFactoryConfig, + userProfile = changeCommentRequest.userProfile + ) } yield ChangeValueResponseV1( value = verifyUpdateResult.value, comment = verifyUpdateResult.comment, @@ -1185,22 +1232,22 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde for { // Don't allow anonymous users to update values. userIri <- Future { - if (changeCommentRequest.userProfile.isAnonymousUser) { - throw ForbiddenException("Anonymous users aren't allowed to update values") - } else { - changeCommentRequest.userProfile.id - } - } + if (changeCommentRequest.userProfile.isAnonymousUser) { + throw ForbiddenException("Anonymous users aren't allowed to update values") + } else { + changeCommentRequest.userProfile.id + } + } // Find the resource containing the value. findResourceWithValueResult <- findResourceWithValue(changeCommentRequest.valueIri) // Do the remaining pre-update checks and the update while holding an update lock on the resource. taskResult <- IriLocker.runWithIriLock( - changeCommentRequest.apiRequestID, - findResourceWithValueResult.resourceIri, - () => makeTaskFuture(userIri, findResourceWithValueResult) - ) + changeCommentRequest.apiRequestID, + findResourceWithValueResult.resourceIri, + () => makeTaskFuture(userIri, findResourceWithValueResult) + ) } yield taskResult } @@ -1229,25 +1276,26 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde for { // Ensure that the user has permission to mark the value as deleted. maybeCurrentValueQueryResult <- findValue( - valueIri = deleteValueRequest.valueIri, - featureFactoryConfig = deleteValueRequest.featureFactoryConfig, - userProfile = deleteValueRequest.userProfile - ) + valueIri = deleteValueRequest.valueIri, + featureFactoryConfig = deleteValueRequest.featureFactoryConfig, + userProfile = deleteValueRequest.userProfile + ) - currentValueQueryResult = maybeCurrentValueQueryResult.getOrElse( - throw NotFoundException(s"Value ${deleteValueRequest.valueIri} not found (it may have been deleted)") - ) + currentValueQueryResult = + maybeCurrentValueQueryResult.getOrElse( + throw NotFoundException(s"Value ${deleteValueRequest.valueIri} not found (it may have been deleted)") + ) _ = if ( - !PermissionUtilADM.impliesPermissionCodeV1( - userHasPermissionCode = Some(currentValueQueryResult.permissionCode), - userNeedsPermission = OntologyConstants.KnoraBase.DeletePermission - ) - ) { - throw ForbiddenException( - s"User $userIri does not have permission to delete value ${deleteValueRequest.valueIri}" - ) - } + !PermissionUtilADM.impliesPermissionCodeV1( + userHasPermissionCode = Some(currentValueQueryResult.permissionCode), + userNeedsPermission = OntologyConstants.KnoraBase.DeletePermission + ) + ) { + throw ForbiddenException( + s"User $userIri does not have permission to delete value ${deleteValueRequest.valueIri}" + ) + } // Make a timestamp to indicate when the value was marked as deleted. currentTime: String = Instant.now.toString @@ -1255,162 +1303,187 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde // The way we delete the value depends on whether it's a link value or an ordinary value. (sparqlUpdate, deletedValueIri) <- currentValueQueryResult.value match { - case linkValue: LinkValueV1 => - // It's a LinkValue. Make a new version of it with a reference count of 0, and mark the new - // version as deleted. - - // Give the new version the same permissions as the previous version. - - val valuePermissions: String = currentValueQueryResult.permissionRelevantAssertions.find { case (p, o) => - p == OntologyConstants.KnoraBase.HasPermissions - } - .map(_._2) - .getOrElse( - throw InconsistentRepositoryDataException(s"Value ${deleteValueRequest.valueIri} has no permissions") - ) - - val linkPropertyIri = - stringFormatter.linkValuePropertyIriToLinkPropertyIri(findResourceWithValueResult.propertyIri) - - for { - // Get project info - maybeProjectInfo <- { - responderManager ? ProjectInfoByIRIGetV1( - iri = findResourceWithValueResult.projectIri, - featureFactoryConfig = deleteValueRequest.featureFactoryConfig, - userProfileV1 = None - ) - }.mapTo[Option[ProjectInfoV1]] - - projectInfo = maybeProjectInfo match { - case Some(pi) => pi - case None => throw NotFoundException(s"Project '${findResourceWithValueResult.projectIri}' not found.") - } - - sparqlTemplateLinkUpdate <- decrementLinkValue( - sourceResourceIri = findResourceWithValueResult.resourceIri, - linkPropertyIri = linkPropertyIri, - targetResourceIri = linkValue.objectIri, - valueCreator = userIri, - valuePermissions = valuePermissions, - featureFactoryConfig = deleteValueRequest.featureFactoryConfig, - userProfile = deleteValueRequest.userProfile - ) - - sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .deleteLink( - dataNamedGraph = StringFormatter.getGeneralInstance.projectDataNamedGraphV1(projectInfo), - linkSourceIri = findResourceWithValueResult.resourceIri, - linkUpdate = sparqlTemplateLinkUpdate, - maybeComment = deleteValueRequest.deleteComment, - currentTime = currentTime, - requestingUser = userIri - ) - .toString() - } yield (sparqlUpdate, sparqlTemplateLinkUpdate.newLinkValueIri) - - case other => - // It's not a LinkValue. Mark the existing version as deleted. - - // If it's a TextValue, make SparqlTemplateLinkUpdates for updating LinkValues representing - // links in standoff markup. - val linkUpdatesFuture: Future[Seq[SparqlTemplateLinkUpdate]] = other match { - case textValue: TextValueWithStandoffV1 => - val linkUpdateFutures = textValue.resource_reference.map { targetResourceIri => - decrementLinkValue( - sourceResourceIri = findResourceWithValueResult.resourceIri, - linkPropertyIri = OntologyConstants.KnoraBase.HasStandoffLinkTo, - targetResourceIri = targetResourceIri, - valueCreator = OntologyConstants.KnoraAdmin.SystemUser, - valuePermissions = standoffLinkValuePermissions, - featureFactoryConfig = deleteValueRequest.featureFactoryConfig, - userProfile = deleteValueRequest.userProfile - ) - }.toVector - - Future.sequence(linkUpdateFutures) - - case _ => Future(Seq.empty[SparqlTemplateLinkUpdate]) - } - - for { - linkUpdates <- linkUpdatesFuture - - // Get project info - maybeProjectInfo <- { - responderManager ? ProjectInfoByIRIGetV1( - iri = findResourceWithValueResult.projectIri, - featureFactoryConfig = deleteValueRequest.featureFactoryConfig, - userProfileV1 = None - ) - }.mapTo[Option[ProjectInfoV1]] - - projectInfo = maybeProjectInfo match { - case Some(pi) => pi - case None => throw NotFoundException(s"Project '${findResourceWithValueResult.projectIri}' not found.") - } - - sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .deleteValue( - dataNamedGraph = StringFormatter.getGeneralInstance.projectDataNamedGraphV1(projectInfo), - resourceIri = findResourceWithValueResult.resourceIri, - propertyIri = findResourceWithValueResult.propertyIri, - valueIri = deleteValueRequest.valueIri, - maybeDeleteComment = deleteValueRequest.deleteComment, - linkUpdates = linkUpdates, - currentTime = currentTime, - requestingUser = userIri, - stringFormatter = stringFormatter - ) - .toString() - } yield (sparqlUpdate, deleteValueRequest.valueIri) - } + case linkValue: LinkValueV1 => + // It's a LinkValue. Make a new version of it with a reference count of 0, and mark the new + // version as deleted. + + // Give the new version the same permissions as the previous version. + + val valuePermissions: String = + currentValueQueryResult.permissionRelevantAssertions.find { + case (p, o) => + p == OntologyConstants.KnoraBase.HasPermissions + } + .map(_._2) + .getOrElse( + throw InconsistentRepositoryDataException( + s"Value ${deleteValueRequest.valueIri} has no permissions" + ) + ) + + val linkPropertyIri = + stringFormatter.linkValuePropertyIriToLinkPropertyIri( + findResourceWithValueResult.propertyIri + ) + + for { + // Get project info + maybeProjectInfo <- { + responderManager ? ProjectInfoByIRIGetV1( + iri = findResourceWithValueResult.projectIri, + featureFactoryConfig = deleteValueRequest.featureFactoryConfig, + userProfileV1 = None + ) + }.mapTo[Option[ProjectInfoV1]] + + projectInfo = maybeProjectInfo match { + case Some(pi) => pi + case None => + throw NotFoundException( + s"Project '${findResourceWithValueResult.projectIri}' not found." + ) + } + + sparqlTemplateLinkUpdate <- decrementLinkValue( + sourceResourceIri = + findResourceWithValueResult.resourceIri, + linkPropertyIri = linkPropertyIri, + targetResourceIri = linkValue.objectIri, + valueCreator = userIri, + valuePermissions = valuePermissions, + featureFactoryConfig = + deleteValueRequest.featureFactoryConfig, + userProfile = + deleteValueRequest.userProfile + ) + + sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .deleteLink( + dataNamedGraph = StringFormatter.getGeneralInstance + .projectDataNamedGraphV1(projectInfo), + linkSourceIri = + findResourceWithValueResult.resourceIri, + linkUpdate = sparqlTemplateLinkUpdate, + maybeComment = deleteValueRequest.deleteComment, + currentTime = currentTime, + requestingUser = userIri + ) + .toString() + } yield (sparqlUpdate, sparqlTemplateLinkUpdate.newLinkValueIri) + + case other => + // It's not a LinkValue. Mark the existing version as deleted. + + // If it's a TextValue, make SparqlTemplateLinkUpdates for updating LinkValues representing + // links in standoff markup. + val linkUpdatesFuture: Future[Seq[SparqlTemplateLinkUpdate]] = + other match { + case textValue: TextValueWithStandoffV1 => + val linkUpdateFutures = textValue.resource_reference.map { + targetResourceIri => + decrementLinkValue( + sourceResourceIri = findResourceWithValueResult.resourceIri, + linkPropertyIri = + OntologyConstants.KnoraBase.HasStandoffLinkTo, + targetResourceIri = targetResourceIri, + valueCreator = OntologyConstants.KnoraAdmin.SystemUser, + valuePermissions = standoffLinkValuePermissions, + featureFactoryConfig = + deleteValueRequest.featureFactoryConfig, + userProfile = deleteValueRequest.userProfile + ) + }.toVector + + Future.sequence(linkUpdateFutures) + + case _ => Future(Seq.empty[SparqlTemplateLinkUpdate]) + } + + for { + linkUpdates <- linkUpdatesFuture + + // Get project info + maybeProjectInfo <- { + responderManager ? ProjectInfoByIRIGetV1( + iri = findResourceWithValueResult.projectIri, + featureFactoryConfig = deleteValueRequest.featureFactoryConfig, + userProfileV1 = None + ) + }.mapTo[Option[ProjectInfoV1]] + + projectInfo = maybeProjectInfo match { + case Some(pi) => pi + case None => + throw NotFoundException( + s"Project '${findResourceWithValueResult.projectIri}' not found." + ) + } + + sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .deleteValue( + dataNamedGraph = StringFormatter.getGeneralInstance + .projectDataNamedGraphV1(projectInfo), + resourceIri = + findResourceWithValueResult.resourceIri, + propertyIri = + findResourceWithValueResult.propertyIri, + valueIri = deleteValueRequest.valueIri, + maybeDeleteComment = + deleteValueRequest.deleteComment, + linkUpdates = linkUpdates, + currentTime = currentTime, + requestingUser = userIri, + stringFormatter = stringFormatter + ) + .toString() + } yield (sparqlUpdate, deleteValueRequest.valueIri) + } // Do the update. sparqlUpdateResponse <- (storeManager ? SparqlUpdateRequest(sparqlUpdate)).mapTo[SparqlUpdateResponse] // Check whether the update succeeded. sparqlQuery = org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .checkValueDeletion( - valueIri = deletedValueIri - ) - .toString() + .checkValueDeletion( + valueIri = deletedValueIri + ) + .toString() sparqlSelectResponse <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] - rows = sparqlSelectResponse.results.bindings + rows = sparqlSelectResponse.results.bindings _ = if ( - rows.isEmpty || !stringFormatter.optionStringToBoolean( - rows.head.rowMap.get("isDeleted"), - throw InconsistentRepositoryDataException( - s"Invalid boolean for isDeleted: ${rows.head.rowMap.get("isDeleted")}" - ) - ) - ) { - throw UpdateNotPerformedException( - s"The request to mark value ${deleteValueRequest.valueIri} (or a new version of that value) as deleted did not succeed. Please report this as a possible bug." - ) - } + rows.isEmpty || !stringFormatter.optionStringToBoolean( + rows.head.rowMap.get("isDeleted"), + throw InconsistentRepositoryDataException( + s"Invalid boolean for isDeleted: ${rows.head.rowMap.get("isDeleted")}" + ) + ) + ) { + throw UpdateNotPerformedException( + s"The request to mark value ${deleteValueRequest.valueIri} (or a new version of that value) as deleted did not succeed. Please report this as a possible bug." + ) + } } yield DeleteValueResponseV1(id = deletedValueIri) for { // Don't allow anonymous users to update values. userIri <- Future { - if (deleteValueRequest.userProfile.isAnonymousUser) { - throw ForbiddenException("Anonymous users aren't allowed to mark values as deleted") - } else { - deleteValueRequest.userProfile.id - } - } + if (deleteValueRequest.userProfile.isAnonymousUser) { + throw ForbiddenException("Anonymous users aren't allowed to mark values as deleted") + } else { + deleteValueRequest.userProfile.id + } + } // Find the resource containing the value. findResourceWithValueResult <- findResourceWithValue(deleteValueRequest.valueIri) // Do the remaining pre-update checks and the update while holding an update lock on the resource. taskResult <- IriLocker.runWithIriLock( - deleteValueRequest.apiRequestID, - findResourceWithValueResult.resourceIri, - () => makeTaskFuture(userIri, findResourceWithValueResult) - ) + deleteValueRequest.apiRequestID, + findResourceWithValueResult.resourceIri, + () => makeTaskFuture(userIri, findResourceWithValueResult) + ) } yield taskResult } @@ -1440,7 +1513,7 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde startAtVersion: IRI, versionRowsVector: Vector[Map[String, String]] ): Vector[Map[String, String]] = { - val startValue = versionMap(startAtVersion) + val startValue = versionMap(startAtVersion) val newVersionVector = versionRowsVector :+ startValue startValue.get("previousValue") match { @@ -1452,89 +1525,90 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde for { // Do a SPARQL query to get the versions of the value. sparqlQuery <- Future { - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getVersionHistory( - resourceIri = versionHistoryRequest.resourceIri, - propertyIri = versionHistoryRequest.propertyIri, - currentValueIri = versionHistoryRequest.currentValueIri - ) - .toString() - } + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getVersionHistory( + resourceIri = versionHistoryRequest.resourceIri, + propertyIri = versionHistoryRequest.propertyIri, + currentValueIri = versionHistoryRequest.currentValueIri + ) + .toString() + } selectResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] - rows = selectResponse.results.bindings + rows = selectResponse.results.bindings _ = if (rows.isEmpty) { - throw NotFoundException( - s"Value ${versionHistoryRequest.currentValueIri} is not the most recent version of an object of property ${versionHistoryRequest.propertyIri} for resource ${versionHistoryRequest.resourceIri}" - ) - } + throw NotFoundException( + s"Value ${versionHistoryRequest.currentValueIri} is not the most recent version of an object of property ${versionHistoryRequest.propertyIri} for resource ${versionHistoryRequest.resourceIri}" + ) + } // Convert the result rows to a map of value IRIs to result rows. versionMap: Map[IRI, Map[String, String]] = rows.map { row => - val valueIri = row.rowMap("value") - valueIri -> row.rowMap - }.toMap + val valueIri = row.rowMap("value") + valueIri -> row.rowMap + }.toMap // Order the result rows from most recent to oldest. versionRowsVector = versionMap2Vector( - versionMap, - versionHistoryRequest.currentValueIri, - Vector.empty[Map[String, String]] - ) + versionMap, + versionHistoryRequest.currentValueIri, + Vector.empty[Map[String, String]] + ) // Filter out the versions that the user doesn't have permission to see. filteredVersionRowsVector = versionRowsVector.filter { rowMap => - val valueIri = rowMap("value") - val valueCreator = rowMap("valueCreator") - val project = rowMap("project") - val valuePermissions = rowMap("valuePermissions") - - // Permission-checking on LinkValues is special, because they can be system-created rather than user-created. - val valuePermissionCode = - if ( - stringFormatter.optionStringToBoolean( - rowMap.get("isLinkValue"), - throw InconsistentRepositoryDataException( - s"Invalid boolean for isLinkValue: ${rowMap.get("isLinkValue")}" - ) - ) - ) { - // It's a LinkValue. - PermissionUtilADM.getUserPermissionV1( - entityIri = valueIri, - entityCreator = valueCreator, - entityProject = project, - entityPermissionLiteral = valuePermissions, - userProfile = userProfileV1 - ) - } else { - // It's not a LinkValue. - PermissionUtilADM.getUserPermissionV1( - entityIri = valueIri, - entityCreator = valueCreator, - entityProject = project, - entityPermissionLiteral = valuePermissions, - userProfile = userProfileV1 - ) - } + val valueIri = rowMap("value") + val valueCreator = rowMap("valueCreator") + val project = rowMap("project") + val valuePermissions = rowMap("valuePermissions") + + // Permission-checking on LinkValues is special, because they can be system-created rather than user-created. + val valuePermissionCode = + if ( + stringFormatter.optionStringToBoolean( + rowMap.get("isLinkValue"), + throw InconsistentRepositoryDataException( + s"Invalid boolean for isLinkValue: ${rowMap.get("isLinkValue")}" + ) + ) + ) { + // It's a LinkValue. + PermissionUtilADM.getUserPermissionV1( + entityIri = valueIri, + entityCreator = valueCreator, + entityProject = project, + entityPermissionLiteral = valuePermissions, + userProfile = userProfileV1 + ) + } else { + // It's not a LinkValue. + PermissionUtilADM.getUserPermissionV1( + entityIri = valueIri, + entityCreator = valueCreator, + entityProject = project, + entityPermissionLiteral = valuePermissions, + userProfile = userProfileV1 + ) + } - valuePermissionCode.nonEmpty - } + valuePermissionCode.nonEmpty + } // Make a set of the IRIs of the versions that the user has permission to see. visibleVersionIris = filteredVersionRowsVector.map(_("value")).toSet versionV1Vector = filteredVersionRowsVector.map { rowMap => - ValueVersionV1( - valueObjectIri = rowMap("value"), - valueCreationDate = rowMap.get("valueCreationDate"), - previousValue = rowMap.get("previousValue") match { - // Don't refer to a previous value that the user doesn't have permission to see. - case Some(previousValueIri) if visibleVersionIris.contains(previousValueIri) => Some(previousValueIri) - case _ => None - } - ) - } + ValueVersionV1( + valueObjectIri = rowMap("value"), + valueCreationDate = rowMap.get("valueCreationDate"), + previousValue = rowMap.get("previousValue") match { + // Don't refer to a previous value that the user doesn't have permission to see. + case Some(previousValueIri) if visibleVersionIris.contains(previousValueIri) => + Some(previousValueIri) + case _ => None + } + ) + } } yield ValueVersionHistoryGetResponseV1(valueVersions = versionV1Vector) } @@ -1560,41 +1634,44 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde ): Future[ValueGetResponseV1] = for { maybeValueQueryResult <- findLinkValueByLinkTriple( - subjectIri = subjectIri, - predicateIri = predicateIri, - objectIri = objectIri, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + subjectIri = subjectIri, + predicateIri = predicateIri, + objectIri = objectIri, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) linkValueResponse <- maybeValueQueryResult match { - case Some(valueQueryResult) => - for { - maybeValueCreatorProfile <- (responderManager ? UserProfileByIRIGetV1( - userIri = valueQueryResult.creatorIri, - userProfileType = UserProfileTypeV1.RESTRICTED, - featureFactoryConfig = featureFactoryConfig - )).mapTo[Option[UserProfileV1]] - - valueCreatorProfile = maybeValueCreatorProfile match { - case Some(up) => up - case None => throw NotFoundException(s"User ${valueQueryResult.creatorIri} not found") - } - } yield ValueGetResponseV1( - valuetype = valueQueryResult.value.valueTypeIri, - rights = valueQueryResult.permissionCode, - value = valueQueryResult.value, - valuecreator = valueCreatorProfile.userData.email.get, - valuecreatorname = valueCreatorProfile.userData.fullname.get, - valuecreationdate = valueQueryResult.creationDate, - comment = valueQueryResult.comment - ) - - case None => - throw NotFoundException( - s"No knora-base:LinkValue found describing a link from resource $subjectIri with predicate $predicateIri to resource $objectIri (it may have been deleted)" - ) - } + case Some(valueQueryResult) => + for { + maybeValueCreatorProfile <- (responderManager ? UserProfileByIRIGetV1( + userIri = valueQueryResult.creatorIri, + userProfileType = UserProfileTypeV1.RESTRICTED, + featureFactoryConfig = featureFactoryConfig + )).mapTo[Option[UserProfileV1]] + + valueCreatorProfile = maybeValueCreatorProfile match { + case Some(up) => up + case None => + throw NotFoundException( + s"User ${valueQueryResult.creatorIri} not found" + ) + } + } yield ValueGetResponseV1( + valuetype = valueQueryResult.value.valueTypeIri, + rights = valueQueryResult.permissionCode, + value = valueQueryResult.value, + valuecreator = valueCreatorProfile.userData.email.get, + valuecreatorname = valueCreatorProfile.userData.fullname.get, + valuecreationdate = valueQueryResult.creationDate, + comment = valueQueryResult.comment + ) + + case None => + throw NotFoundException( + s"No knora-base:LinkValue found describing a link from resource $subjectIri with predicate $predicateIri to resource $objectIri (it may have been deleted)" + ) + } } yield linkValueResponse ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -1689,33 +1766,33 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde ): Future[Option[ValueQueryResult]] = for { sparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getValue( - valueIri = valueIri - ) - .toString() - ) - - response <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getValue( + valueIri = valueIri + ) + .toString() + ) + + response <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] rows: Seq[VariableResultsRow] = response.results.bindings maybeValueQueryResult <- sparqlQueryResults2ValueQueryResult( - valueIri = valueIri, - rows = rows, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + valueIri = valueIri, + rows = rows, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) // If it's a link value, check that the user has permission to see the source and target resources. _ = maybeValueQueryResult match { - case Some(valueQueryResult) => - valueQueryResult.value match { - case _: LinkValueV1 => checkLinkValueSubjectAndObjectPermissions(valueIri, userProfile) - case _ => () - } + case Some(valueQueryResult) => + valueQueryResult.value match { + case _: LinkValueV1 => checkLinkValueSubjectAndObjectPermissions(valueIri, userProfile) + case _ => () + } - case None => () - } + case None => () + } } yield maybeValueQueryResult /** @@ -1730,41 +1807,43 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde for { sparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .getLinkSourceAndTargetPermissions( - linkValueIri = linkValueIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .getLinkSourceAndTargetPermissions( + linkValueIri = linkValueIri + ) + .toString() + ) response <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] - rows = response.results.bindings + rows = response.results.bindings _ = if (rows.isEmpty) { - throw NotFoundException(s"Link value $linkValueIri, or its source or target resource, was not found.") - } + throw NotFoundException(s"Link value $linkValueIri, or its source or target resource, was not found.") + } rowMap = rows.head.rowMap maybeSourcePermissionCode = PermissionUtilADM.getUserPermissionV1( - entityIri = rowMap("source"), - entityCreator = rowMap("sourceCreator"), - entityProject = rowMap("sourceProject"), - entityPermissionLiteral = rowMap("sourcePermissions"), - userProfile = userProfileV1 - ) + entityIri = rowMap("source"), + entityCreator = rowMap("sourceCreator"), + entityProject = rowMap("sourceProject"), + entityPermissionLiteral = rowMap("sourcePermissions"), + userProfile = userProfileV1 + ) maybeTargetPermissionCode = PermissionUtilADM.getUserPermissionV1( - entityIri = rowMap("target"), - entityCreator = rowMap("targetCreator"), - entityProject = rowMap("targetProject"), - entityPermissionLiteral = rowMap("targetPermissions"), - userProfile = userProfileV1 - ) + entityIri = rowMap("target"), + entityCreator = rowMap("targetCreator"), + entityProject = rowMap("targetProject"), + entityPermissionLiteral = rowMap("targetPermissions"), + userProfile = userProfileV1 + ) _ = if (maybeSourcePermissionCode.isEmpty || maybeTargetPermissionCode.isEmpty) { - throw ForbiddenException(s"User ${userProfile.id} does not have permission to view link value $linkValueIri") - } + throw ForbiddenException( + s"User ${userProfile.id} does not have permission to view link value $linkValueIri" + ) + } } yield () } @@ -1790,29 +1869,29 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde ): Future[Option[LinkValueQueryResult]] = for { sparqlQuery <- Future { - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .findLinkValueByIri( - subjectIri = subjectIri, - predicateIri = predicateIri, - maybeObjectIri = objectIri, - linkValueIri = linkValueIri - ) - .toString() - } - - response <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .findLinkValueByIri( + subjectIri = subjectIri, + predicateIri = predicateIri, + maybeObjectIri = objectIri, + linkValueIri = linkValueIri + ) + .toString() + } + + response <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] rows: Seq[VariableResultsRow] = response.results.bindings maybeLinkValueQueryResult <- sparqlQueryResults2LinkValueQueryResult( - rows = rows, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + rows = rows, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) // Check that the user has permission to see the source and target resources. _ = if (maybeLinkValueQueryResult.nonEmpty) { - checkLinkValueSubjectAndObjectPermissions(linkValueIri, userProfile) - } + checkLinkValueSubjectAndObjectPermissions(linkValueIri, userProfile) + } } yield maybeLinkValueQueryResult /** @@ -1836,30 +1915,30 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde ): Future[Option[LinkValueQueryResult]] = for { sparqlQuery <- Future { - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .findLinkValueByObject( - subjectIri = subjectIri, - predicateIri = predicateIri, - objectIri = objectIri - ) - .toString() - } - - response <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .findLinkValueByObject( + subjectIri = subjectIri, + predicateIri = predicateIri, + objectIri = objectIri + ) + .toString() + } + + response <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] rows: Seq[VariableResultsRow] = response.results.bindings maybeLinkValueQueryResult <- sparqlQueryResults2LinkValueQueryResult( - rows = rows, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + rows = rows, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) // Check that the user has permission to see the source and target resources. _ = maybeLinkValueQueryResult match { - case Some(linkValueQueryResult) => - checkLinkValueSubjectAndObjectPermissions(linkValueQueryResult.linkValueIri, userProfile) - case _ => () - } + case Some(linkValueQueryResult) => + checkLinkValueSubjectAndObjectPermissions(linkValueQueryResult.linkValueIri, userProfile) + case _ => () + } } yield maybeLinkValueQueryResult /** @@ -1887,40 +1966,43 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde val valueProps = valueUtilV1.createValueProps(valueIri, rows) for { - projectShortcode: String <- Future( - valueIri.toSmartIri.getProjectCode - .getOrElse(throw InconsistentRepositoryDataException(s"Invalid value IRI: $valueIri")) - ) + projectShortcode: String <- + Future( + valueIri.toSmartIri.getProjectCode + .getOrElse(throw InconsistentRepositoryDataException(s"Invalid value IRI: $valueIri")) + ) value <- valueUtilV1.makeValueV1( - valueProps = valueProps, - projectShortcode = projectShortcode, - responderManager = responderManager, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + valueProps = valueProps, + projectShortcode = projectShortcode, + responderManager = responderManager, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) // Get the value's class IRI. valueClassIri = getValuePredicateObject(predicateIri = OntologyConstants.Rdf.Type, rows = rows) - .getOrElse(throw InconsistentRepositoryDataException(s"Value $valueIri has no rdf:type")) + .getOrElse(throw InconsistentRepositoryDataException(s"Value $valueIri has no rdf:type")) // Get the IRI of the value's creator. - creatorIri = getValuePredicateObject(predicateIri = OntologyConstants.KnoraBase.AttachedToUser, rows = rows) - .getOrElse(throw InconsistentRepositoryDataException(s"Value $valueIri has no knora-base:attachedToUser")) + creatorIri = + getValuePredicateObject(predicateIri = OntologyConstants.KnoraBase.AttachedToUser, rows = rows) + .getOrElse(throw InconsistentRepositoryDataException(s"Value $valueIri has no knora-base:attachedToUser")) // Get the value's project IRI. projectIri = getValuePredicateObject(predicateIri = OntologyConstants.KnoraBase.AttachedToProject, rows = rows) - .getOrElse( - throw InconsistentRepositoryDataException( - s"The resource containing value $valueIri has no knora-base:attachedToProject" - ) - ) + .getOrElse( + throw InconsistentRepositoryDataException( + s"The resource containing value $valueIri has no knora-base:attachedToProject" + ) + ) // Get the value's creation date. - creationDate = getValuePredicateObject( - predicateIri = OntologyConstants.KnoraBase.ValueCreationDate, - rows = rows - ).getOrElse(throw InconsistentRepositoryDataException(s"Value $valueIri has no valueCreationDate")) + creationDate = + getValuePredicateObject( + predicateIri = OntologyConstants.KnoraBase.ValueCreationDate, + rows = rows + ).getOrElse(throw InconsistentRepositoryDataException(s"Value $valueIri has no valueCreationDate")) // Get the optional comment on the value. comment = getValuePredicateObject(predicateIri = OntologyConstants.KnoraBase.ValueHasComment, rows = rows) @@ -1936,28 +2018,35 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde // for checking the permissions on the source and target resources. maybePermissionCode = valueClassIri match { - case OntologyConstants.KnoraBase.LinkValue => - val linkPredicateIri = getValuePredicateObject(predicateIri = OntologyConstants.Rdf.Predicate, rows = rows) - .getOrElse(throw InconsistentRepositoryDataException(s"Link value $valueIri has no rdf:predicate")) - - PermissionUtilADM.getUserPermissionWithValuePropsV1( - valueIri = valueIri, - valueProps = valueProps, - entityProject = None, // no need to specify this here, because it's in valueProps - userProfile = userProfileV1 - ) + case OntologyConstants.KnoraBase.LinkValue => + val linkPredicateIri = + getValuePredicateObject(predicateIri = OntologyConstants.Rdf.Predicate, rows = rows) + .getOrElse( + throw InconsistentRepositoryDataException( + s"Link value $valueIri has no rdf:predicate" + ) + ) - case _ => - PermissionUtilADM.getUserPermissionFromAssertionsV1( - entityIri = valueIri, - assertions = assertions, - userProfile = userProfileV1 - ) - } + PermissionUtilADM.getUserPermissionWithValuePropsV1( + valueIri = valueIri, + valueProps = valueProps, + entityProject = None, // no need to specify this here, because it's in valueProps + userProfile = userProfileV1 + ) + + case _ => + PermissionUtilADM.getUserPermissionFromAssertionsV1( + entityIri = valueIri, + assertions = assertions, + userProfile = userProfileV1 + ) + } permissionCode = maybePermissionCode.getOrElse { - throw ForbiddenException(s"User ${userProfile.id} does not have permission to see value $valueIri") - } + throw ForbiddenException( + s"User ${userProfile.id} does not have permission to see value $valueIri" + ) + } } yield Some( BasicValueQueryResult( @@ -1991,52 +2080,57 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde val userProfileV1 = userProfile.asUserProfileV1 if (rows.nonEmpty) { - val firstRowMap = rows.head.rowMap + val firstRowMap = rows.head.rowMap val linkValueIri = firstRowMap("linkValue") // Convert the query results into a LinkValueV1. val valueProps = valueUtilV1.createValueProps(linkValueIri, rows) for { - projectShortcode: String <- Future( - linkValueIri.toSmartIri.getProjectCode - .getOrElse(throw InconsistentRepositoryDataException(s"Invalid value IRI: $linkValueIri")) - ) + projectShortcode: String <- + Future( + linkValueIri.toSmartIri.getProjectCode + .getOrElse(throw InconsistentRepositoryDataException(s"Invalid value IRI: $linkValueIri")) + ) linkValueMaybe <- valueUtilV1.makeValueV1( - valueProps = valueProps, - projectShortcode = projectShortcode, - responderManager = responderManager, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + valueProps = valueProps, + projectShortcode = projectShortcode, + responderManager = responderManager, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) linkValueV1: LinkValueV1 = linkValueMaybe match { - case linkValue: LinkValueV1 => linkValue - case other => - throw InconsistentRepositoryDataException( - s"Expected value $linkValueIri to be of type ${OntologyConstants.KnoraBase.LinkValue}, but it was read with type ${other.valueTypeIri}" - ) - } + case linkValue: LinkValueV1 => linkValue + case other => + throw InconsistentRepositoryDataException( + s"Expected value $linkValueIri to be of type ${OntologyConstants.KnoraBase.LinkValue}, but it was read with type ${other.valueTypeIri}" + ) + } // Get the IRI of the value's owner. - creatorIri = getValuePredicateObject(predicateIri = OntologyConstants.KnoraBase.AttachedToUser, rows = rows) - .getOrElse(throw InconsistentRepositoryDataException(s"Value $linkValueIri has no knora-base:attachedToUser")) + creatorIri = + getValuePredicateObject(predicateIri = OntologyConstants.KnoraBase.AttachedToUser, rows = rows) + .getOrElse( + throw InconsistentRepositoryDataException(s"Value $linkValueIri has no knora-base:attachedToUser") + ) // Get the value's project IRI. projectIri = getValuePredicateObject(predicateIri = OntologyConstants.KnoraBase.AttachedToProject, rows = rows) - .getOrElse( - throw InconsistentRepositoryDataException( - s"The resource containing value $linkValueIri has no knora-base:attachedToProject" - ) - ) + .getOrElse( + throw InconsistentRepositoryDataException( + s"The resource containing value $linkValueIri has no knora-base:attachedToProject" + ) + ) // Get the value's creation date. - creationDate = getValuePredicateObject( - predicateIri = OntologyConstants.KnoraBase.ValueCreationDate, - rows = rows - ) - .getOrElse(throw InconsistentRepositoryDataException(s"Value $linkValueIri has no valueCreationDate")) + creationDate = + getValuePredicateObject( + predicateIri = OntologyConstants.KnoraBase.ValueCreationDate, + rows = rows + ) + .getOrElse(throw InconsistentRepositoryDataException(s"Value $linkValueIri has no valueCreationDate")) // Get the optional comment on the value. comment = getValuePredicateObject(predicateIri = OntologyConstants.KnoraBase.ValueHasComment, rows = rows) @@ -2046,17 +2140,19 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde // Get the permission code representing the user's permissions on the value. permissionCode = PermissionUtilADM - .getUserPermissionWithValuePropsV1( - valueIri = linkValueIri, - valueProps = valueProps, - entityProject = None, // no need to specify this here, because it's in valueProps - userProfile = userProfileV1 - ) - .getOrElse { - throw ForbiddenException(s"User ${userProfile.id} does not have permission to see value $linkValueIri") - } - - directLinkExists = firstRowMap.get("directLinkExists").exists(_.toBoolean) + .getUserPermissionWithValuePropsV1( + valueIri = linkValueIri, + valueProps = valueProps, + entityProject = None, // no need to specify this here, because it's in valueProps + userProfile = userProfileV1 + ) + .getOrElse { + throw ForbiddenException( + s"User ${userProfile.id} does not have permission to see value $linkValueIri" + ) + } + + directLinkExists = firstRowMap.get("directLinkExists").exists(_.toBoolean) targetResourceClass = firstRowMap.get("targetResourceClass") } yield Some( @@ -2100,18 +2196,18 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde case linkUpdateV1: LinkUpdateV1 => for { linkValueQueryResult <- verifyLinkUpdate( - linkSourceIri = resourceIri, - linkPropertyIri = propertyIri, - linkTargetIri = linkUpdateV1.targetResourceIri, - linkValueIri = unverifiedValue.newValueIri, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + linkSourceIri = resourceIri, + linkPropertyIri = propertyIri, + linkTargetIri = linkUpdateV1.targetResourceIri, + linkValueIri = unverifiedValue.newValueIri, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) apiResponseValue = LinkV1( - targetResourceIri = linkUpdateV1.targetResourceIri, - valueResourceClass = linkValueQueryResult.targetResourceClass - ) + targetResourceIri = linkUpdateV1.targetResourceIri, + valueResourceClass = linkValueQueryResult.targetResourceClass + ) } yield CreateValueResponseV1( value = apiResponseValue, comment = linkValueQueryResult.comment, @@ -2122,12 +2218,12 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde case ordinaryUpdateValueV1 => for { verifyUpdateResult <- verifyOrdinaryValueUpdate( - resourceIri = resourceIri, - propertyIri = propertyIri, - searchValueIri = unverifiedValue.newValueIri, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + resourceIri = resourceIri, + propertyIri = propertyIri, + searchValueIri = unverifiedValue.newValueIri, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) } yield CreateValueResponseV1( value = verifyUpdateResult.value, @@ -2160,26 +2256,26 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde for { // Do a SPARQL query to look for the value in the resource's version history. sparqlQuery <- Future { - // Run the template function in a Future to handle exceptions (see http://git.iml.unibas.ch/salsah-suite/knora/wikis/futures-with-akka#handling-errors-with-futures) - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .findValueInVersions( - resourceIri = resourceIri, - propertyIri = propertyIri, - searchValueIri = searchValueIri - ) - .toString() - } + // Run the template function in a Future to handle exceptions (see http://git.iml.unibas.ch/salsah-suite/knora/wikis/futures-with-akka#handling-errors-with-futures) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .findValueInVersions( + resourceIri = resourceIri, + propertyIri = propertyIri, + searchValueIri = searchValueIri + ) + .toString() + } updateVerificationResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(sparqlQuery)) - .mapTo[SparqlSelectResult] + .mapTo[SparqlSelectResult] rows = updateVerificationResponse.results.bindings resultOption <- sparqlQueryResults2ValueQueryResult( - valueIri = searchValueIri, - rows = rows, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + valueIri = searchValueIri, + rows = rows, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) } yield resultOption.getOrElse( throw UpdateNotPerformedException( @@ -2211,27 +2307,27 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde ): Future[LinkValueQueryResult] = for { maybeLinkValueQueryResult <- findLinkValueByIri( - subjectIri = linkSourceIri, - predicateIri = linkPropertyIri, - objectIri = Some(linkTargetIri), - linkValueIri = linkValueIri, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + subjectIri = linkSourceIri, + predicateIri = linkPropertyIri, + objectIri = Some(linkTargetIri), + linkValueIri = linkValueIri, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) result = maybeLinkValueQueryResult match { - case Some(linkValueQueryResult) => - if (!linkValueQueryResult.directLinkExists || linkValueQueryResult.targetResourceClass.isEmpty) { - throw UpdateNotPerformedException() - } else { - linkValueQueryResult - } - - case None => - throw UpdateNotPerformedException( - s"The update to link value $linkValueIri with source IRI $linkSourceIri, link property $linkPropertyIri, and target $linkTargetIri was not performed. Please report this as a possible bug." - ) - } + case Some(linkValueQueryResult) => + if (!linkValueQueryResult.directLinkExists || linkValueQueryResult.targetResourceClass.isEmpty) { + throw UpdateNotPerformedException() + } else { + linkValueQueryResult + } + + case None => + throw UpdateNotPerformedException( + s"The update to link value $linkValueIri with source IRI $linkSourceIri, link property $linkPropertyIri, and target $linkTargetIri was not performed. Please report this as a possible bug." + ) + } } yield result /** @@ -2262,22 +2358,22 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde private def findResourceWithValue(valueIri: IRI): Future[FindResourceWithValueResult] = for { findResourceSparqlQuery <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .findResourceWithValue( - searchValueIri = valueIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v1.txt + .findResourceWithValue( + searchValueIri = valueIri + ) + .toString() + ) findResourceResponse <- (storeManager ? SparqlSelectRequest(findResourceSparqlQuery)).mapTo[SparqlSelectResult] _ = if (findResourceResponse.results.bindings.isEmpty) { - throw NotFoundException(s"No resource found containing value $valueIri") - } + throw NotFoundException(s"No resource found containing value $valueIri") + } resultRowMap = findResourceResponse.getFirstRow.rowMap resourceIri = resultRowMap("resource") - projectIri = resultRowMap("project") + projectIri = resultRowMap("project") propertyIri = resultRowMap("property") } yield FindResourceWithValueResult( resourceIri = resourceIri, @@ -2366,28 +2462,28 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde ): Future[UnverifiedValueV1] = for { sparqlTemplateLinkUpdate <- incrementLinkValue( - sourceResourceIri = resourceIri, - linkPropertyIri = propertyIri, - targetResourceIri = linkUpdateV1.targetResourceIri, - valueCreator = valueCreator, - valuePermissions = valuePermissions, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + sourceResourceIri = resourceIri, + linkPropertyIri = propertyIri, + targetResourceIri = linkUpdateV1.targetResourceIri, + valueCreator = valueCreator, + valuePermissions = valuePermissions, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) currentTime: Instant = Instant.now // Generate a SPARQL update string. sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .createLink( - dataNamedGraph = dataNamedGraph, - resourceIri = resourceIri, - linkUpdate = sparqlTemplateLinkUpdate, - creationDate = currentTime, - maybeComment = comment, - stringFormatter = stringFormatter - ) - .toString() + .createLink( + dataNamedGraph = dataNamedGraph, + resourceIri = resourceIri, + linkUpdate = sparqlTemplateLinkUpdate, + creationDate = currentTime, + maybeComment = comment, + stringFormatter = stringFormatter + ) + .toString() /* _ = println("================ Create link ===============") @@ -2426,52 +2522,56 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde userProfile: UserADM ): Future[UnverifiedValueV1] = { // Generate an IRI for the new value. - val newValueIri = stringFormatter.makeRandomValueIri(resourceIri) + val newValueIri = stringFormatter.makeRandomValueIri(resourceIri) val creationDate: Instant = Instant.now for { // If we're creating a text value, update direct links and LinkValues for any resource references in standoff. standoffLinkUpdates: Seq[SparqlTemplateLinkUpdate] <- value match { - case textValueV1: TextValueWithStandoffV1 => - // Make sure the text value's list of resource references is correct. - checkTextValueResourceRefs(textValueV1) - - // Construct a SparqlTemplateLinkUpdate for each reference that was added. - val standoffLinkUpdatesForAddedResourceRefs: Seq[Future[SparqlTemplateLinkUpdate]] = - textValueV1.resource_reference.map { targetResourceIri => - incrementLinkValue( - sourceResourceIri = resourceIri, - linkPropertyIri = OntologyConstants.KnoraBase.HasStandoffLinkTo, - targetResourceIri = targetResourceIri, - valueCreator = OntologyConstants.KnoraAdmin.SystemUser, - valuePermissions = standoffLinkValuePermissions, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) - }.toVector - - Future.sequence(standoffLinkUpdatesForAddedResourceRefs) - - case _ => Future(Vector.empty[SparqlTemplateLinkUpdate]) - } + case textValueV1: TextValueWithStandoffV1 => + // Make sure the text value's list of resource references is correct. + checkTextValueResourceRefs(textValueV1) + + // Construct a SparqlTemplateLinkUpdate for each reference that was added. + val standoffLinkUpdatesForAddedResourceRefs + : Seq[Future[SparqlTemplateLinkUpdate]] = + textValueV1.resource_reference.map { + targetResourceIri => + incrementLinkValue( + sourceResourceIri = resourceIri, + linkPropertyIri = + OntologyConstants.KnoraBase.HasStandoffLinkTo, + targetResourceIri = targetResourceIri, + valueCreator = + OntologyConstants.KnoraAdmin.SystemUser, + valuePermissions = standoffLinkValuePermissions, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) + }.toVector + + Future.sequence(standoffLinkUpdatesForAddedResourceRefs) + + case _ => Future(Vector.empty[SparqlTemplateLinkUpdate]) + } // Generate a SPARQL update string. sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .createValue( - dataNamedGraph = dataNamedGraph, - resourceIri = resourceIri, - propertyIri = propertyIri, - newValueIri = newValueIri, - valueTypeIri = value.valueTypeIri, - value = value, - linkUpdates = standoffLinkUpdates, - maybeComment = comment, - valueCreator = valueCreator, - valuePermissions = valuePermissions, - creationDate = creationDate, - stringFormatter = stringFormatter - ) - .toString() + .createValue( + dataNamedGraph = dataNamedGraph, + resourceIri = resourceIri, + propertyIri = propertyIri, + newValueIri = newValueIri, + valueTypeIri = value.valueTypeIri, + value = value, + linkUpdates = standoffLinkUpdates, + maybeComment = comment, + valueCreator = valueCreator, + valuePermissions = valuePermissions, + creationDate = creationDate, + stringFormatter = stringFormatter + ) + .toString() /* _ = println("================ Create value ================") @@ -2519,25 +2619,25 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde for { // Delete the existing link and decrement its LinkValue's reference count. sparqlTemplateLinkUpdateForCurrentLink <- decrementLinkValue( - sourceResourceIri = resourceIri, - linkPropertyIri = propertyIri, - targetResourceIri = currentLinkValueV1.objectIri, - valueCreator = valueCreator, - valuePermissions = valuePermissions, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + sourceResourceIri = resourceIri, + linkPropertyIri = propertyIri, + targetResourceIri = currentLinkValueV1.objectIri, + valueCreator = valueCreator, + valuePermissions = valuePermissions, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) // Create a new link, and create a new LinkValue for it. sparqlTemplateLinkUpdateForNewLink <- incrementLinkValue( - sourceResourceIri = resourceIri, - linkPropertyIri = propertyIri, - targetResourceIri = linkUpdateV1.targetResourceIri, - valueCreator = valueCreator, - valuePermissions = valuePermissions, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + sourceResourceIri = resourceIri, + linkPropertyIri = propertyIri, + targetResourceIri = linkUpdateV1.targetResourceIri, + valueCreator = valueCreator, + valuePermissions = valuePermissions, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) // Get project info maybeProjectInfo <- { @@ -2549,26 +2649,26 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde }.mapTo[Option[ProjectInfoV1]] projectInfo = maybeProjectInfo match { - case Some(pi) => pi - case None => throw NotFoundException(s"Project '$projectIri' not found.") - } + case Some(pi) => pi + case None => throw NotFoundException(s"Project '$projectIri' not found.") + } // Make a timestamp to indicate when the link value was updated. currentTime: String = Instant.now.toString // Generate a SPARQL update string. sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .changeLink( - dataNamedGraph = StringFormatter.getGeneralInstance.projectDataNamedGraphV1(projectInfo), - linkSourceIri = resourceIri, - linkUpdateForCurrentLink = sparqlTemplateLinkUpdateForCurrentLink, - linkUpdateForNewLink = sparqlTemplateLinkUpdateForNewLink, - maybeComment = comment, - currentTime = currentTime, - requestingUser = userProfile.id, - stringFormatter = stringFormatter - ) - .toString() + .changeLink( + dataNamedGraph = StringFormatter.getGeneralInstance.projectDataNamedGraphV1(projectInfo), + linkSourceIri = resourceIri, + linkUpdateForCurrentLink = sparqlTemplateLinkUpdateForCurrentLink, + linkUpdateForNewLink = sparqlTemplateLinkUpdateForNewLink, + maybeComment = comment, + currentTime = currentTime, + requestingUser = userProfile.id, + stringFormatter = stringFormatter + ) + .toString() /* _ = println("================ Update link ================") @@ -2581,18 +2681,18 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde // To find out whether the update succeeded, check that the new link is in the triplestore. linkValueQueryResult <- verifyLinkUpdate( - linkSourceIri = resourceIri, - linkPropertyIri = propertyIri, - linkTargetIri = linkUpdateV1.targetResourceIri, - linkValueIri = sparqlTemplateLinkUpdateForNewLink.newLinkValueIri, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + linkSourceIri = resourceIri, + linkPropertyIri = propertyIri, + linkTargetIri = linkUpdateV1.targetResourceIri, + linkValueIri = sparqlTemplateLinkUpdateForNewLink.newLinkValueIri, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) apiResponseValue = LinkV1( - targetResourceIri = linkUpdateV1.targetResourceIri, - valueResourceClass = linkValueQueryResult.targetResourceClass - ) + targetResourceIri = linkUpdateV1.targetResourceIri, + valueResourceClass = linkValueQueryResult.targetResourceClass + ) } yield ChangeValueResponseV1( value = apiResponseValue, @@ -2634,63 +2734,79 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde for { // If we're adding a text value, update direct links and LinkValues for any resource references in Standoff. standoffLinkUpdates: Seq[SparqlTemplateLinkUpdate] <- (currentValueV1, updateValueV1) match { - case (currentTextValue: TextValueV1, newTextValue: TextValueV1) => - // Make sure the new text value's list of resource references is correct. - - newTextValue match { - case newTextWithStandoff: TextValueWithStandoffV1 => - checkTextValueResourceRefs(newTextWithStandoff) - case textValueSimple: TextValueSimpleV1 => () - } - - // Identify the resource references that have been added or removed in the new version of - // the value. - val currentResourceRefs = currentTextValue match { - case textValueWithStandoff: TextValueWithStandoffV1 => - textValueWithStandoff.resource_reference - case textValueSimple: TextValueSimpleV1 => Set.empty[IRI] - } - - val newResourceRefs = newTextValue match { - case textValueWithStandoff: TextValueWithStandoffV1 => - textValueWithStandoff.resource_reference - case textValueSimple: TextValueSimpleV1 => Set.empty[IRI] - } - val addedResourceRefs = newResourceRefs -- currentResourceRefs - val removedResourceRefs = currentResourceRefs -- newResourceRefs - - // Construct a SparqlTemplateLinkUpdate for each reference that was added. - val standoffLinkUpdatesForAddedResourceRefs: Seq[Future[SparqlTemplateLinkUpdate]] = - addedResourceRefs.toVector.map { targetResourceIri => - incrementLinkValue( - sourceResourceIri = resourceIri, - linkPropertyIri = OntologyConstants.KnoraBase.HasStandoffLinkTo, - targetResourceIri = targetResourceIri, - valueCreator = OntologyConstants.KnoraAdmin.SystemUser, - valuePermissions = standoffLinkValuePermissions, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) - } - - // Construct a SparqlTemplateLinkUpdate for each reference that was removed. - val standoffLinkUpdatesForRemovedResourceRefs: Seq[Future[SparqlTemplateLinkUpdate]] = - removedResourceRefs.toVector.map { removedTargetResource => - decrementLinkValue( - sourceResourceIri = resourceIri, - linkPropertyIri = OntologyConstants.KnoraBase.HasStandoffLinkTo, - targetResourceIri = removedTargetResource, - valueCreator = OntologyConstants.KnoraAdmin.SystemUser, - valuePermissions = standoffLinkValuePermissions, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) - } - - Future.sequence(standoffLinkUpdatesForAddedResourceRefs ++ standoffLinkUpdatesForRemovedResourceRefs) - - case _ => Future(Vector.empty[SparqlTemplateLinkUpdate]) - } + case ( + currentTextValue: TextValueV1, + newTextValue: TextValueV1 + ) => + // Make sure the new text value's list of resource references is correct. + + newTextValue match { + case newTextWithStandoff: TextValueWithStandoffV1 => + checkTextValueResourceRefs(newTextWithStandoff) + case textValueSimple: TextValueSimpleV1 => () + } + + // Identify the resource references that have been added or removed in the new version of + // the value. + val currentResourceRefs = currentTextValue match { + case textValueWithStandoff: TextValueWithStandoffV1 => + textValueWithStandoff.resource_reference + case textValueSimple: TextValueSimpleV1 => + Set.empty[IRI] + } + + val newResourceRefs = newTextValue match { + case textValueWithStandoff: TextValueWithStandoffV1 => + textValueWithStandoff.resource_reference + case textValueSimple: TextValueSimpleV1 => + Set.empty[IRI] + } + val addedResourceRefs = + newResourceRefs -- currentResourceRefs + val removedResourceRefs = + currentResourceRefs -- newResourceRefs + + // Construct a SparqlTemplateLinkUpdate for each reference that was added. + val standoffLinkUpdatesForAddedResourceRefs + : Seq[Future[SparqlTemplateLinkUpdate]] = + addedResourceRefs.toVector.map { targetResourceIri => + incrementLinkValue( + sourceResourceIri = resourceIri, + linkPropertyIri = + OntologyConstants.KnoraBase.HasStandoffLinkTo, + targetResourceIri = targetResourceIri, + valueCreator = + OntologyConstants.KnoraAdmin.SystemUser, + valuePermissions = standoffLinkValuePermissions, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) + } + + // Construct a SparqlTemplateLinkUpdate for each reference that was removed. + val standoffLinkUpdatesForRemovedResourceRefs + : Seq[Future[SparqlTemplateLinkUpdate]] = + removedResourceRefs.toVector.map { + removedTargetResource => + decrementLinkValue( + sourceResourceIri = resourceIri, + linkPropertyIri = + OntologyConstants.KnoraBase.HasStandoffLinkTo, + targetResourceIri = removedTargetResource, + valueCreator = + OntologyConstants.KnoraAdmin.SystemUser, + valuePermissions = standoffLinkValuePermissions, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) + } + + Future.sequence( + standoffLinkUpdatesForAddedResourceRefs ++ standoffLinkUpdatesForRemovedResourceRefs + ) + + case _ => Future(Vector.empty[SparqlTemplateLinkUpdate]) + } // Get project info maybeProjectInfo <- { @@ -2702,32 +2818,32 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde }.mapTo[Option[ProjectInfoV1]] projectInfo = maybeProjectInfo match { - case Some(pi) => pi - case None => throw NotFoundException(s"Project '$projectIri' not found.") - } + case Some(pi) => pi + case None => throw NotFoundException(s"Project '$projectIri' not found.") + } // Make a timestamp to indicate when the value was updated. currentTime: String = Instant.now.toString // Generate a SPARQL update. sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v1.txt - .addValueVersion( - dataNamedGraph = StringFormatter.getGeneralInstance.projectDataNamedGraphV1(projectInfo), - resourceIri = resourceIri, - propertyIri = propertyIri, - currentValueIri = currentValueIri, - newValueIri = newValueIri, - valueTypeIri = updateValueV1.valueTypeIri, - value = updateValueV1, - valueCreator = valueCreator, - valuePermissions = valuePermissions, - maybeComment = comment, - linkUpdates = standoffLinkUpdates, - currentTime = currentTime, - requestingUser = userProfile.id, - stringFormatter = stringFormatter - ) - .toString() + .addValueVersion( + dataNamedGraph = StringFormatter.getGeneralInstance.projectDataNamedGraphV1(projectInfo), + resourceIri = resourceIri, + propertyIri = propertyIri, + currentValueIri = currentValueIri, + newValueIri = newValueIri, + valueTypeIri = updateValueV1.valueTypeIri, + value = updateValueV1, + valueCreator = valueCreator, + valuePermissions = valuePermissions, + maybeComment = comment, + linkUpdates = standoffLinkUpdates, + currentTime = currentTime, + requestingUser = userProfile.id, + stringFormatter = stringFormatter + ) + .toString() /* _ = println("================ Update value ================") @@ -2740,12 +2856,12 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde // To find out whether the update succeeded, look for the new value in the triplestore. verifyUpdateResult <- verifyOrdinaryValueUpdate( - resourceIri = resourceIri, - propertyIri = propertyIri, - searchValueIri = newValueIri, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + resourceIri = resourceIri, + propertyIri = propertyIri, + searchValueIri = newValueIri, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) } yield ChangeValueResponseV1( value = verifyUpdateResult.value, comment = verifyUpdateResult.comment, @@ -2789,64 +2905,64 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde for { // Check whether a LinkValue already exists for this link. maybeLinkValueQueryResult <- findLinkValueByLinkTriple( - subjectIri = sourceResourceIri, - predicateIri = linkPropertyIri, - objectIri = targetResourceIri, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + subjectIri = sourceResourceIri, + predicateIri = linkPropertyIri, + objectIri = targetResourceIri, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) // Check that the target resource actually exists and is a knora-base:Resource. targetIriCheckResult <- checkStandoffResourceReferenceTargets( - targetIris = Set(targetResourceIri), - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + targetIris = Set(targetResourceIri), + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) // Generate an IRI for the new LinkValue. newLinkValueIri = stringFormatter.makeRandomValueIri(sourceResourceIri) linkUpdate = maybeLinkValueQueryResult match { - case Some(linkValueQueryResult) => - // There's already a LinkValue for links between these two resources. Increment - // its reference count. - val currentReferenceCount = linkValueQueryResult.value.referenceCount - val newReferenceCount = currentReferenceCount + 1 - val insertDirectLink = !linkValueQueryResult.directLinkExists - - SparqlTemplateLinkUpdate( - linkPropertyIri = linkPropertyIri.toSmartIri, - directLinkExists = linkValueQueryResult.directLinkExists, - insertDirectLink = insertDirectLink, - deleteDirectLink = false, - linkValueExists = true, - linkTargetExists = true, - newLinkValueIri = newLinkValueIri, - linkTargetIri = targetResourceIri, - currentReferenceCount = currentReferenceCount, - newReferenceCount = newReferenceCount, - newLinkValueCreator = valueCreator, - newLinkValuePermissions = valuePermissions - ) - - case None => - // There's no LinkValue for links between these two resources, so create one, and give it - // a reference count of 1. - SparqlTemplateLinkUpdate( - linkPropertyIri = linkPropertyIri.toSmartIri, - directLinkExists = false, - insertDirectLink = true, - deleteDirectLink = false, - linkValueExists = false, - linkTargetExists = true, - newLinkValueIri = newLinkValueIri, - linkTargetIri = targetResourceIri, - currentReferenceCount = 0, - newReferenceCount = 1, - newLinkValueCreator = valueCreator, - newLinkValuePermissions = valuePermissions - ) - } + case Some(linkValueQueryResult) => + // There's already a LinkValue for links between these two resources. Increment + // its reference count. + val currentReferenceCount = linkValueQueryResult.value.referenceCount + val newReferenceCount = currentReferenceCount + 1 + val insertDirectLink = !linkValueQueryResult.directLinkExists + + SparqlTemplateLinkUpdate( + linkPropertyIri = linkPropertyIri.toSmartIri, + directLinkExists = linkValueQueryResult.directLinkExists, + insertDirectLink = insertDirectLink, + deleteDirectLink = false, + linkValueExists = true, + linkTargetExists = true, + newLinkValueIri = newLinkValueIri, + linkTargetIri = targetResourceIri, + currentReferenceCount = currentReferenceCount, + newReferenceCount = newReferenceCount, + newLinkValueCreator = valueCreator, + newLinkValuePermissions = valuePermissions + ) + + case None => + // There's no LinkValue for links between these two resources, so create one, and give it + // a reference count of 1. + SparqlTemplateLinkUpdate( + linkPropertyIri = linkPropertyIri.toSmartIri, + directLinkExists = false, + insertDirectLink = true, + deleteDirectLink = false, + linkValueExists = false, + linkTargetExists = true, + newLinkValueIri = newLinkValueIri, + linkTargetIri = targetResourceIri, + currentReferenceCount = 0, + newReferenceCount = 1, + newLinkValueCreator = valueCreator, + newLinkValuePermissions = valuePermissions + ) + } } yield linkUpdate /** @@ -2882,50 +2998,50 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde for { // Query the LinkValue to ensure that it exists and to get its contents. maybeLinkValueQueryResult <- findLinkValueByLinkTriple( - subjectIri = sourceResourceIri, - predicateIri = linkPropertyIri, - objectIri = targetResourceIri, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - ) + subjectIri = sourceResourceIri, + predicateIri = linkPropertyIri, + objectIri = targetResourceIri, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + ) // Did we find it? linkUpdate = maybeLinkValueQueryResult match { - case Some(linkValueQueryResult) => - // Yes. Make a SparqlTemplateLinkUpdate. - - // Decrement the LinkValue's reference count. - val currentReferenceCount = linkValueQueryResult.value.referenceCount - val newReferenceCount = currentReferenceCount - 1 - - // If the new reference count is 0, specify that the direct link between the source and target - // resources should be removed. - val deleteDirectLink = linkValueQueryResult.directLinkExists && newReferenceCount == 0 - - // Generate an IRI for the new LinkValue. - val newLinkValueIri = stringFormatter.makeRandomValueIri(sourceResourceIri) - - SparqlTemplateLinkUpdate( - linkPropertyIri = linkPropertyIri.toSmartIri, - directLinkExists = linkValueQueryResult.directLinkExists, - insertDirectLink = false, - deleteDirectLink = deleteDirectLink, - linkValueExists = true, - linkTargetExists = true, - newLinkValueIri = newLinkValueIri, - linkTargetIri = targetResourceIri, - currentReferenceCount = currentReferenceCount, - newReferenceCount = newReferenceCount, - newLinkValueCreator = valueCreator, - newLinkValuePermissions = valuePermissions - ) - - case None => - // We didn't find the LinkValue. This shouldn't happen. - throw InconsistentRepositoryDataException( - s"There should be a knora-base:LinkValue describing a direct link from resource $sourceResourceIri to resource $targetResourceIri using property $linkPropertyIri, but it seems to be missing" - ) - } + case Some(linkValueQueryResult) => + // Yes. Make a SparqlTemplateLinkUpdate. + + // Decrement the LinkValue's reference count. + val currentReferenceCount = linkValueQueryResult.value.referenceCount + val newReferenceCount = currentReferenceCount - 1 + + // If the new reference count is 0, specify that the direct link between the source and target + // resources should be removed. + val deleteDirectLink = linkValueQueryResult.directLinkExists && newReferenceCount == 0 + + // Generate an IRI for the new LinkValue. + val newLinkValueIri = stringFormatter.makeRandomValueIri(sourceResourceIri) + + SparqlTemplateLinkUpdate( + linkPropertyIri = linkPropertyIri.toSmartIri, + directLinkExists = linkValueQueryResult.directLinkExists, + insertDirectLink = false, + deleteDirectLink = deleteDirectLink, + linkValueExists = true, + linkTargetExists = true, + newLinkValueIri = newLinkValueIri, + linkTargetIri = targetResourceIri, + currentReferenceCount = currentReferenceCount, + newReferenceCount = newReferenceCount, + newLinkValueCreator = valueCreator, + newLinkValuePermissions = valuePermissions + ) + + case None => + // We didn't find the LinkValue. This shouldn't happen. + throw InconsistentRepositoryDataException( + s"There should be a knora-base:LinkValue describing a direct link from resource $sourceResourceIri to resource $targetResourceIri using property $linkPropertyIri, but it seems to be missing" + ) + } } yield linkUpdate /** @@ -2981,16 +3097,17 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde val targetIriCheckFutures: Set[Future[Unit]] = targetIris.map { targetIri => for { checkTargetClassResponse <- (responderManager ? ResourceCheckClassRequestV1( - resourceIri = targetIri, - owlClass = OntologyConstants.KnoraBase.Resource, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - )).mapTo[ResourceCheckClassResponseV1] - - _ = if (!checkTargetClassResponse.isInClass) - throw BadRequestException( - s"$targetIri cannot be the object of a standoff resource reference, because it is not a knora-base:Resource" - ) + resourceIri = targetIri, + owlClass = OntologyConstants.KnoraBase.Resource, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + )).mapTo[ResourceCheckClassResponseV1] + + _ = + if (!checkTargetClassResponse.isInClass) + throw BadRequestException( + s"$targetIri cannot be the object of a standoff resource reference, because it is not a knora-base:Resource" + ) } yield () } @@ -3019,33 +3136,33 @@ class ValuesResponderV1(responderData: ResponderData) extends Responder(responde ): Future[Unit] = for { result <- updateValueV1 match { - case linkUpdate: LinkUpdateV1 => - // We're creating a link. Ask the resources responder to check the OWL class of the target resource. - for { - checkTargetClassResponse <- (responderManager ? ResourceCheckClassRequestV1( - resourceIri = linkUpdate.targetResourceIri, - owlClass = propertyObjectClassConstraint, - featureFactoryConfig = featureFactoryConfig, - userProfile = userProfile - )).mapTo[ResourceCheckClassResponseV1] - - _ = if (!checkTargetClassResponse.isInClass) { - throw OntologyConstraintException( - s"Resource ${linkUpdate.targetResourceIri} cannot be the target of property $propertyIri, because it is not a member of OWL class $propertyObjectClassConstraint" - ) - } - } yield () - - case otherValue => - // We're creating an ordinary value. Check that its type is valid for the property's knora-base:objectClassConstraint. - valueUtilV1.checkValueTypeForPropertyObjectClassConstraint( - propertyIri = propertyIri, - propertyObjectClassConstraint = propertyObjectClassConstraint, - valueType = otherValue.valueTypeIri, - responderManager = responderManager, - userProfile = userProfile - ) - } + case linkUpdate: LinkUpdateV1 => + // We're creating a link. Ask the resources responder to check the OWL class of the target resource. + for { + checkTargetClassResponse <- (responderManager ? ResourceCheckClassRequestV1( + resourceIri = linkUpdate.targetResourceIri, + owlClass = propertyObjectClassConstraint, + featureFactoryConfig = featureFactoryConfig, + userProfile = userProfile + )).mapTo[ResourceCheckClassResponseV1] + + _ = if (!checkTargetClassResponse.isInClass) { + throw OntologyConstraintException( + s"Resource ${linkUpdate.targetResourceIri} cannot be the target of property $propertyIri, because it is not a member of OWL class $propertyObjectClassConstraint" + ) + } + } yield () + + case otherValue => + // We're creating an ordinary value. Check that its type is valid for the property's knora-base:objectClassConstraint. + valueUtilV1.checkValueTypeForPropertyObjectClassConstraint( + propertyIri = propertyIri, + propertyObjectClassConstraint = propertyObjectClassConstraint, + valueType = otherValue.valueTypeIri, + responderManager = responderManager, + userProfile = userProfile + ) + } } yield result /** diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v2/ListsResponderV2.scala b/webapi/src/main/scala/org/knora/webapi/responders/v2/ListsResponderV2.scala index 6a6838aea8..0bf70a1409 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/v2/ListsResponderV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v2/ListsResponderV2.scala @@ -52,10 +52,10 @@ class ListsResponderV2(responderData: ResponderData) extends Responder(responder ): Future[ListGetResponseV2] = for { listResponseADM: ListGetResponseADM <- (responderManager ? ListGetRequestADM( - iri = listIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - )).mapTo[ListGetResponseADM] + iri = listIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + )).mapTo[ListGetResponseADM] } yield ListGetResponseV2(list = listResponseADM.list, requestingUser.lang, settings.fallbackLanguage) @@ -74,10 +74,10 @@ class ListsResponderV2(responderData: ResponderData) extends Responder(responder ): Future[NodeGetResponseV2] = for { nodeResponse: ChildNodeInfoGetResponseADM <- (responderManager ? ListNodeInfoGetRequestADM( - iri = nodeIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - )).mapTo[ChildNodeInfoGetResponseADM] + iri = nodeIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + )).mapTo[ChildNodeInfoGetResponseADM] } yield NodeGetResponseV2(node = nodeResponse.nodeinfo, requestingUser.lang, settings.fallbackLanguage) } diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v2/OntologyResponderV2.scala b/webapi/src/main/scala/org/knora/webapi/responders/v2/OntologyResponderV2.scala index b322c1a5ad..07c7b0ba43 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/v2/OntologyResponderV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v2/OntologyResponderV2.scala @@ -160,58 +160,60 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon (standoffClassIris ++ standoffPropertyIris).filter(_.getOntologySchema.contains(ApiV2Simple)) _ = if (entitiesInWrongSchema.nonEmpty) { - throw NotFoundException( - s"Some requested standoff classes were not found: ${entitiesInWrongSchema.mkString(", ")}" - ) - } + throw NotFoundException( + s"Some requested standoff classes were not found: ${entitiesInWrongSchema.mkString(", ")}" + ) + } - classIrisForCache = standoffClassIris.map(_.toOntologySchema(InternalSchema)) + classIrisForCache = standoffClassIris.map(_.toOntologySchema(InternalSchema)) propertyIrisForCache = standoffPropertyIris.map(_.toOntologySchema(InternalSchema)) classOntologies: Iterable[ReadOntologyV2] = cacheData.ontologies.view - .filterKeys(classIrisForCache.map(_.getOntologyFromEntity)) - .values + .filterKeys(classIrisForCache.map(_.getOntologyFromEntity)) + .values propertyOntologies: Iterable[ReadOntologyV2] = cacheData.ontologies.view - .filterKeys(propertyIrisForCache.map(_.getOntologyFromEntity)) - .values + .filterKeys(propertyIrisForCache.map(_.getOntologyFromEntity)) + .values classDefsAvailable: Map[SmartIri, ReadClassInfoV2] = classOntologies.flatMap { ontology => - ontology.classes.filter { case (classIri, classDef) => - classDef.isStandoffClass && standoffClassIris.contains( - classIri - ) - } - }.toMap + ontology.classes.filter { case (classIri, classDef) => + classDef.isStandoffClass && standoffClassIris.contains( + classIri + ) + } + }.toMap propertyDefsAvailable: Map[SmartIri, ReadPropertyInfoV2] = propertyOntologies.flatMap { ontology => - ontology.properties.filter { case (propertyIri, _) => - standoffPropertyIris.contains( - propertyIri - ) && cacheData.standoffProperties.contains( - propertyIri - ) - } - }.toMap - - missingClassDefs = classIrisForCache -- classDefsAvailable.keySet + ontology.properties.filter { case (propertyIri, _) => + standoffPropertyIris.contains( + propertyIri + ) && cacheData.standoffProperties.contains( + propertyIri + ) + } + }.toMap + + missingClassDefs = classIrisForCache -- classDefsAvailable.keySet missingPropertyDefs = propertyIrisForCache -- propertyDefsAvailable.keySet _ = if (missingClassDefs.nonEmpty) { - throw NotFoundException( - s"Some requested standoff classes were not found: ${missingClassDefs.mkString(", ")}" - ) - } + throw NotFoundException( + s"Some requested standoff classes were not found: ${missingClassDefs.mkString(", ")}" + ) + } _ = if (missingPropertyDefs.nonEmpty) { - throw NotFoundException( - s"Some requested standoff properties were not found: ${missingPropertyDefs.mkString(", ")}" - ) - } + throw NotFoundException( + s"Some requested standoff properties were not found: ${missingPropertyDefs.mkString(", ")}" + ) + } response = StandoffEntityInfoGetResponseV2( - standoffClassInfoMap = new ErrorHandlingMap(classDefsAvailable, key => s"Resource class $key not found"), - standoffPropertyInfoMap = new ErrorHandlingMap(propertyDefsAvailable, key => s"Property $key not found") - ) + standoffClassInfoMap = + new ErrorHandlingMap(classDefsAvailable, key => s"Resource class $key not found"), + standoffPropertyInfoMap = + new ErrorHandlingMap(propertyDefsAvailable, key => s"Property $key not found") + ) } yield response /** @@ -261,11 +263,11 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon for { cacheData <- Cache.getCacheData response = CheckSubClassResponseV2( - isSubClass = cacheData.subClassOfRelations.get(subClassIri) match { - case Some(baseClasses) => baseClasses.contains(superClassIri) - case None => throw BadRequestException(s"Class $subClassIri not found") - } - ) + isSubClass = cacheData.subClassOfRelations.get(subClassIri) match { + case Some(baseClasses) => baseClasses.contains(superClassIri) + case None => throw BadRequestException(s"Class $subClassIri not found") + } + ) } yield response /** @@ -281,21 +283,21 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon subClassIris = cacheData.superClassOfRelations(classIri).toVector.sorted subClasses = subClassIris.map { subClassIri => - val classInfo: ReadClassInfoV2 = - cacheData.ontologies(subClassIri.getOntologyFromEntity).classes(subClassIri) - - SubClassInfoV2( - id = subClassIri, - label = classInfo.entityInfoContent - .getPredicateStringLiteralObject( - predicateIri = OntologyConstants.Rdfs.Label.toSmartIri, - preferredLangs = Some(requestingUser.lang, settings.fallbackLanguage) - ) - .getOrElse( - throw InconsistentRepositoryDataException(s"Resource class $subClassIri has no rdfs:label") - ) - ) - } + val classInfo: ReadClassInfoV2 = + cacheData.ontologies(subClassIri.getOntologyFromEntity).classes(subClassIri) + + SubClassInfoV2( + id = subClassIri, + label = classInfo.entityInfoContent + .getPredicateStringLiteralObject( + predicateIri = OntologyConstants.Rdfs.Label.toSmartIri, + preferredLangs = Some(requestingUser.lang, settings.fallbackLanguage) + ) + .getOrElse( + throw InconsistentRepositoryDataException(s"Resource class $subClassIri has no rdfs:label") + ) + ) + } } yield SubClassesGetResponseV2( subClasses = subClasses ) @@ -313,7 +315,7 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon ): Future[OntologyKnoraEntitiesIriInfoV2] = for { cacheData <- Cache.getCacheData - ontology = cacheData.ontologies(ontologyIri) + ontology = cacheData.ontologies(ontologyIri) } yield OntologyKnoraEntitiesIriInfoV2( ontologyIri = ontologyIri, propertyIris = ontology.properties.keySet.filter { propertyIri => @@ -340,7 +342,7 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon requestingUser: UserADM ): Future[ReadOntologyMetadataV2] = for { - cacheData <- Cache.getCacheData + cacheData <- Cache.getCacheData returnAllOntologies: Boolean = projectIris.isEmpty ontologyMetadata: Set[OntologyMetadataV2] = @@ -369,7 +371,7 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon requestingUser: UserADM ): Future[ReadOntologyMetadataV2] = for { - cacheData <- Cache.getCacheData + cacheData <- Cache.getCacheData returnAllOntologies: Boolean = ontologyIris.isEmpty ontologyMetadata: Set[OntologyMetadataV2] = @@ -416,13 +418,13 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon cacheData <- Cache.getCacheData _ = if (ontologyIri.getOntologyName == "standoff" && ontologyIri.getOntologySchema.contains(ApiV2Simple)) { - throw BadRequestException(s"The standoff ontology is not available in the API v2 simple schema") - } + throw BadRequestException(s"The standoff ontology is not available in the API v2 simple schema") + } ontology = cacheData.ontologies.get(ontologyIri.toOntologySchema(InternalSchema)) match { - case Some(cachedOntology) => cachedOntology - case None => throw NotFoundException(s"Ontology not found: $ontologyIri") - } + case Some(cachedOntology) => cachedOntology + case None => throw NotFoundException(s"Ontology not found: $ontologyIri") + } // Are we returning data in the user's preferred language, or in all available languages? userLang = @@ -469,8 +471,8 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon ontologyIris = propertyIris.map(_.getOntologyFromEntity) _ = if (ontologyIris.size != 1) { - throw BadRequestException(s"Only one ontology may be queried per request") - } + throw BadRequestException(s"Only one ontology may be queried per request") + } propertyInfoResponse: EntityInfoGetResponseV2 <- getEntityInfoResponseV2(propertyIris = propertyIris, requestingUser = requestingUser) @@ -504,17 +506,18 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Make sure the ontology doesn't already exist. existingOntologyMetadata: Option[OntologyMetadataV2] <- OntologyHelpers.loadOntologyMetadata( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - featureFactoryConfig = createOntologyRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + featureFactoryConfig = + createOntologyRequest.featureFactoryConfig + ) _ = if (existingOntologyMetadata.nonEmpty) { - throw BadRequestException( - s"Ontology ${internalOntologyIri.toOntologySchema(ApiV2Complex)} cannot be created, because it already exists" - ) - } + throw BadRequestException( + s"Ontology ${internalOntologyIri.toOntologySchema(ApiV2Complex)} cannot be created, because it already exists" + ) + } // If this is a shared ontology, make sure it's in the default shared ontologies project. _ = @@ -541,44 +544,45 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon currentTime: Instant = Instant.now createOntologySparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .createOntology( - ontologyNamedGraphIri = internalOntologyIri, - ontologyIri = internalOntologyIri, - projectIri = createOntologyRequest.projectIri, - isShared = createOntologyRequest.isShared, - ontologyLabel = createOntologyRequest.label, - ontologyComment = createOntologyRequest.comment, - currentTime = currentTime - ) - .toString + .createOntology( + ontologyNamedGraphIri = internalOntologyIri, + ontologyIri = internalOntologyIri, + projectIri = createOntologyRequest.projectIri, + isShared = createOntologyRequest.isShared, + ontologyLabel = createOntologyRequest.label, + ontologyComment = createOntologyRequest.comment, + currentTime = currentTime + ) + .toString _ <- (storeManager ? SparqlUpdateRequest(createOntologySparql)).mapTo[SparqlUpdateResponse] // Check that the update was successful. To do this, we have to undo the SPARQL-escaping of the input. unescapedNewMetadata = OntologyMetadataV2( - ontologyIri = internalOntologyIri, - projectIri = Some(createOntologyRequest.projectIri), - label = Some(createOntologyRequest.label), - comment = createOntologyRequest.comment, - lastModificationDate = Some(currentTime) - ).unescape + ontologyIri = internalOntologyIri, + projectIri = Some(createOntologyRequest.projectIri), + label = Some(createOntologyRequest.label), + comment = createOntologyRequest.comment, + lastModificationDate = Some(currentTime) + ).unescape maybeLoadedOntologyMetadata: Option[OntologyMetadataV2] <- OntologyHelpers.loadOntologyMetadata( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - featureFactoryConfig = createOntologyRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + featureFactoryConfig = + createOntologyRequest.featureFactoryConfig + ) _ = maybeLoadedOntologyMetadata match { - case Some(loadedOntologyMetadata) => - if (loadedOntologyMetadata != unescapedNewMetadata) { - throw UpdateNotPerformedException() - } + case Some(loadedOntologyMetadata) => + if (loadedOntologyMetadata != unescapedNewMetadata) { + throw UpdateNotPerformedException() + } - case None => throw UpdateNotPerformedException() - } + case None => throw UpdateNotPerformedException() + } // Update the ontology cache with the unescaped metadata. @@ -594,7 +598,7 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon for { requestingUser <- FastFuture.successful(createOntologyRequest.requestingUser) - projectIri = createOntologyRequest.projectIri + projectIri = createOntologyRequest.projectIri // check if the requesting user is allowed to create an ontology _ = @@ -610,10 +614,10 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Get project info for the shortcode. projectInfo: ProjectGetResponseADM <- (responderManager ? ProjectGetRequestADM( - identifier = ProjectIdentifierADM(maybeIri = Some(projectIri.toString)), - featureFactoryConfig = createOntologyRequest.featureFactoryConfig, - requestingUser = requestingUser - )).mapTo[ProjectGetResponseADM] + identifier = ProjectIdentifierADM(maybeIri = Some(projectIri.toString)), + featureFactoryConfig = createOntologyRequest.featureFactoryConfig, + requestingUser = requestingUser + )).mapTo[ProjectGetResponseADM] // Check that the ontology name is valid. validOntologyName = @@ -624,17 +628,17 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Make the internal ontology IRI. internalOntologyIri = stringFormatter.makeProjectSpecificInternalOntologyIri( - validOntologyName, - createOntologyRequest.isShared, - projectInfo.project.shortcode - ) + validOntologyName, + createOntologyRequest.isShared, + projectInfo.project.shortcode + ) // Do the remaining pre-update checks and the update while holding a global ontology cache lock. taskResult <- IriLocker.runWithIriLock( - apiRequestID = createOntologyRequest.apiRequestID, - iri = ONTOLOGY_CACHE_LOCK_IRI, - task = () => makeTaskFuture(internalOntologyIri) - ) + apiRequestID = createOntologyRequest.apiRequestID, + iri = ONTOLOGY_CACHE_LOCK_IRI, + task = () => makeTaskFuture(internalOntologyIri) + ) } yield taskResult } @@ -653,18 +657,18 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Check that the user has permission to update the ontology. projectIri <- OntologyHelpers.checkPermissionsForOntologyUpdate( - internalOntologyIri = internalOntologyIri, - requestingUser = changeOntologyMetadataRequest.requestingUser - ) + internalOntologyIri = internalOntologyIri, + requestingUser = changeOntologyMetadataRequest.requestingUser + ) // Check that the ontology exists and has not been updated by another user since the client last read its metadata. _ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = changeOntologyMetadataRequest.lastModificationDate, - featureFactoryConfig = changeOntologyMetadataRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = changeOntologyMetadataRequest.lastModificationDate, + featureFactoryConfig = changeOntologyMetadataRequest.featureFactoryConfig + ) // get the metadata of the ontology. oldMetadata: OntologyMetadataV2 = cacheData.ontologies(internalOntologyIri).ontologyMetadata @@ -676,17 +680,17 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon currentTime: Instant = Instant.now updateSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .changeOntologyMetadata( - ontologyNamedGraphIri = internalOntologyIri, - ontologyIri = internalOntologyIri, - newLabel = changeOntologyMetadataRequest.label, - hasOldComment = ontologyHasComment, - deleteOldComment = ontologyHasComment && changeOntologyMetadataRequest.comment.nonEmpty, - newComment = changeOntologyMetadataRequest.comment, - lastModificationDate = changeOntologyMetadataRequest.lastModificationDate, - currentTime = currentTime - ) - .toString() + .changeOntologyMetadata( + ontologyNamedGraphIri = internalOntologyIri, + ontologyIri = internalOntologyIri, + newLabel = changeOntologyMetadataRequest.label, + hasOldComment = ontologyHasComment, + deleteOldComment = ontologyHasComment && changeOntologyMetadataRequest.comment.nonEmpty, + newComment = changeOntologyMetadataRequest.comment, + lastModificationDate = changeOntologyMetadataRequest.lastModificationDate, + currentTime = currentTime + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(updateSparql)).mapTo[SparqlUpdateResponse] @@ -713,12 +717,12 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon } unescapedNewMetadata = OntologyMetadataV2( - ontologyIri = internalOntologyIri, - projectIri = Some(projectIri), - label = label, - comment = comment, - lastModificationDate = Some(currentTime) - ).unescape + ontologyIri = internalOntologyIri, + projectIri = Some(projectIri), + label = label, + comment = comment, + lastModificationDate = Some(currentTime) + ).unescape maybeLoadedOntologyMetadata: Option[OntologyMetadataV2] <- OntologyHelpers.loadOntologyMetadata( @@ -729,36 +733,36 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon ) _ = maybeLoadedOntologyMetadata match { - case Some(loadedOntologyMetadata) => - if (loadedOntologyMetadata != unescapedNewMetadata) { - throw UpdateNotPerformedException() - } + case Some(loadedOntologyMetadata) => + if (loadedOntologyMetadata != unescapedNewMetadata) { + throw UpdateNotPerformedException() + } - case None => throw UpdateNotPerformedException() - } + case None => throw UpdateNotPerformedException() + } // Update the ontology cache with the unescaped metadata. _ = Cache.storeCacheData( - cacheData.copy( - ontologies = cacheData.ontologies + (internalOntologyIri -> cacheData - .ontologies(internalOntologyIri) - .copy(ontologyMetadata = unescapedNewMetadata)) - ) - ) + cacheData.copy( + ontologies = cacheData.ontologies + (internalOntologyIri -> cacheData + .ontologies(internalOntologyIri) + .copy(ontologyMetadata = unescapedNewMetadata)) + ) + ) } yield ReadOntologyMetadataV2(ontologies = Set(unescapedNewMetadata)) for { - _ <- OntologyHelpers.checkExternalOntologyIriForUpdate(changeOntologyMetadataRequest.ontologyIri) + _ <- OntologyHelpers.checkExternalOntologyIriForUpdate(changeOntologyMetadataRequest.ontologyIri) internalOntologyIri = changeOntologyMetadataRequest.ontologyIri.toOntologySchema(InternalSchema) // Do the remaining pre-update checks and the update while holding a global ontology cache lock. taskResult <- IriLocker.runWithIriLock( - apiRequestID = changeOntologyMetadataRequest.apiRequestID, - iri = ONTOLOGY_CACHE_LOCK_IRI, - task = () => makeTaskFuture(internalOntologyIri = internalOntologyIri) - ) + apiRequestID = changeOntologyMetadataRequest.apiRequestID, + iri = ONTOLOGY_CACHE_LOCK_IRI, + task = () => makeTaskFuture(internalOntologyIri = internalOntologyIri) + ) } yield taskResult } @@ -771,18 +775,18 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Check that the user has permission to update the ontology. projectIri <- OntologyHelpers.checkPermissionsForOntologyUpdate( - internalOntologyIri = internalOntologyIri, - requestingUser = deleteOntologyCommentRequestV2.requestingUser - ) + internalOntologyIri = internalOntologyIri, + requestingUser = deleteOntologyCommentRequestV2.requestingUser + ) // Check that the ontology exists and has not been updated by another user since the client last read its metadata. _ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = deleteOntologyCommentRequestV2.lastModificationDate, - featureFactoryConfig = deleteOntologyCommentRequestV2.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = deleteOntologyCommentRequestV2.lastModificationDate, + featureFactoryConfig = deleteOntologyCommentRequestV2.featureFactoryConfig + ) // get the metadata of the ontology. oldMetadata: OntologyMetadataV2 = cacheData.ontologies(internalOntologyIri).ontologyMetadata @@ -794,29 +798,29 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon currentTime: Instant = Instant.now updateSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .changeOntologyMetadata( - ontologyNamedGraphIri = internalOntologyIri, - ontologyIri = internalOntologyIri, - newLabel = None, - hasOldComment = ontologyHasComment, - deleteOldComment = true, - newComment = None, - lastModificationDate = deleteOntologyCommentRequestV2.lastModificationDate, - currentTime = currentTime - ) - .toString() + .changeOntologyMetadata( + ontologyNamedGraphIri = internalOntologyIri, + ontologyIri = internalOntologyIri, + newLabel = None, + hasOldComment = ontologyHasComment, + deleteOldComment = true, + newComment = None, + lastModificationDate = deleteOntologyCommentRequestV2.lastModificationDate, + currentTime = currentTime + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(updateSparql)).mapTo[SparqlUpdateResponse] // Check that the update was successful. unescapedNewMetadata = OntologyMetadataV2( - ontologyIri = internalOntologyIri, - projectIri = Some(projectIri), - label = oldMetadata.label, - comment = None, - lastModificationDate = Some(currentTime) - ).unescape + ontologyIri = internalOntologyIri, + projectIri = Some(projectIri), + label = oldMetadata.label, + comment = None, + lastModificationDate = Some(currentTime) + ).unescape maybeLoadedOntologyMetadata: Option[OntologyMetadataV2] <- OntologyHelpers.loadOntologyMetadata( @@ -827,36 +831,36 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon ) _ = maybeLoadedOntologyMetadata match { - case Some(loadedOntologyMetadata) => - if (loadedOntologyMetadata != unescapedNewMetadata) { - throw UpdateNotPerformedException() - } + case Some(loadedOntologyMetadata) => + if (loadedOntologyMetadata != unescapedNewMetadata) { + throw UpdateNotPerformedException() + } - case None => throw UpdateNotPerformedException() - } + case None => throw UpdateNotPerformedException() + } // Update the ontology cache with the unescaped metadata. _ = Cache.storeCacheData( - cacheData.copy( - ontologies = cacheData.ontologies + (internalOntologyIri -> cacheData - .ontologies(internalOntologyIri) - .copy(ontologyMetadata = unescapedNewMetadata)) - ) - ) + cacheData.copy( + ontologies = cacheData.ontologies + (internalOntologyIri -> cacheData + .ontologies(internalOntologyIri) + .copy(ontologyMetadata = unescapedNewMetadata)) + ) + ) } yield ReadOntologyMetadataV2(ontologies = Set(unescapedNewMetadata)) for { - _ <- OntologyHelpers.checkExternalOntologyIriForUpdate(deleteOntologyCommentRequestV2.ontologyIri) + _ <- OntologyHelpers.checkExternalOntologyIriForUpdate(deleteOntologyCommentRequestV2.ontologyIri) internalOntologyIri = deleteOntologyCommentRequestV2.ontologyIri.toOntologySchema(InternalSchema) // Do the remaining pre-update checks and the update while holding a global ontology cache lock. taskResult <- IriLocker.runWithIriLock( - apiRequestID = deleteOntologyCommentRequestV2.apiRequestID, - iri = ONTOLOGY_CACHE_LOCK_IRI, - task = () => makeTaskFuture(internalOntologyIri = internalOntologyIri) - ) + apiRequestID = deleteOntologyCommentRequestV2.apiRequestID, + iri = ONTOLOGY_CACHE_LOCK_IRI, + task = () => makeTaskFuture(internalOntologyIri = internalOntologyIri) + ) } yield taskResult } @@ -869,40 +873,40 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon private def createClass(createClassRequest: CreateClassRequestV2): Future[ReadOntologyV2] = { def makeTaskFuture(internalClassIri: SmartIri, internalOntologyIri: SmartIri): Future[ReadOntologyV2] = { for { - cacheData <- Cache.getCacheData + cacheData <- Cache.getCacheData internalClassDef: ClassInfoContentV2 = createClassRequest.classInfoContent.toOntologySchema(InternalSchema) // Check that the ontology exists and has not been updated by another user since the client last read it. _ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = createClassRequest.lastModificationDate, - featureFactoryConfig = createClassRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = createClassRequest.lastModificationDate, + featureFactoryConfig = createClassRequest.featureFactoryConfig + ) // Check that the class's rdf:type is owl:Class. rdfType: SmartIri = internalClassDef.requireIriObject( - OntologyConstants.Rdf.Type.toSmartIri, - throw BadRequestException(s"No rdf:type specified") - ) + OntologyConstants.Rdf.Type.toSmartIri, + throw BadRequestException(s"No rdf:type specified") + ) _ = if (rdfType != OntologyConstants.Owl.Class.toSmartIri) { - throw BadRequestException(s"Invalid rdf:type for property: $rdfType") - } + throw BadRequestException(s"Invalid rdf:type for property: $rdfType") + } ontology = cacheData.ontologies(internalOntologyIri) // Check that the class doesn't exist yet. _ = if (ontology.classes.contains(internalClassIri)) { - throw BadRequestException(s"Class ${createClassRequest.classInfoContent.classIri} already exists") - } + throw BadRequestException(s"Class ${createClassRequest.classInfoContent.classIri} already exists") + } // Check that the class's IRI isn't already used for something else. _ = if (ontology.properties.contains(internalClassIri) || ontology.individuals.contains(internalClassIri)) { - throw BadRequestException(s"IRI ${createClassRequest.classInfoContent.classIri} is already used") - } + throw BadRequestException(s"IRI ${createClassRequest.classInfoContent.classIri} is already used") + } // Check that the base classes that have Knora IRIs are defined as Knora resource classes. @@ -912,34 +916,34 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon .filter(baseClassIri => !OntologyHelpers.isKnoraInternalResourceClass(baseClassIri, cacheData)) _ = if (missingBaseClasses.nonEmpty) { - throw BadRequestException( - s"One or more specified base classes are invalid: ${missingBaseClasses.mkString(", ")}" - ) - } + throw BadRequestException( + s"One or more specified base classes are invalid: ${missingBaseClasses.mkString(", ")}" + ) + } // Check for rdfs:subClassOf cycles. allBaseClassIrisWithoutSelf: Set[SmartIri] = internalClassDef.subClassOf.flatMap { baseClassIri => - cacheData.subClassOfRelations - .getOrElse(baseClassIri, Set.empty[SmartIri]) - .toSet - } + cacheData.subClassOfRelations + .getOrElse(baseClassIri, Set.empty[SmartIri]) + .toSet + } _ = if (allBaseClassIrisWithoutSelf.contains(internalClassIri)) { - throw BadRequestException( - s"Class ${createClassRequest.classInfoContent.classIri} would have a cyclical rdfs:subClassOf" - ) - } + throw BadRequestException( + s"Class ${createClassRequest.classInfoContent.classIri} would have a cyclical rdfs:subClassOf" + ) + } // Check that the class is a subclass of knora-base:Resource. allBaseClassIris: Seq[SmartIri] = internalClassIri +: allBaseClassIrisWithoutSelf.toSeq _ = if (!allBaseClassIris.contains(OntologyConstants.KnoraBase.Resource.toSmartIri)) { - throw BadRequestException( - s"Class ${createClassRequest.classInfoContent.classIri} would not be a subclass of knora-api:Resource" - ) - } + throw BadRequestException( + s"Class ${createClassRequest.classInfoContent.classIri} would not be a subclass of knora-api:Resource" + ) + } // Check that the cardinalities are valid, and add any inherited cardinalities. (internalClassDefWithLinkValueProps, cardinalitiesForClassWithInheritance) = @@ -952,12 +956,12 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Check that the class definition doesn't refer to any non-shared ontologies in other projects. _ = Cache.checkOntologyReferencesInClassDef( - ontologyCacheData = cacheData, - classDef = internalClassDefWithLinkValueProps, - errorFun = { msg: String => - throw BadRequestException(msg) - } - ) + ontologyCacheData = cacheData, + classDef = internalClassDefWithLinkValueProps, + errorFun = { msg: String => + throw BadRequestException(msg) + } + ) // Prepare to update the ontology cache, undoing the SPARQL-escaping of the input. @@ -971,121 +975,121 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon unescapedClassDefWithLinkValueProps = internalClassDefWithLinkValueProps.unescape readClassInfo = ReadClassInfoV2( - entityInfoContent = unescapedClassDefWithLinkValueProps, - allBaseClasses = allBaseClassIris, - isResourceClass = true, - canBeInstantiated = true, - inheritedCardinalities = inheritedCardinalities, - knoraResourceProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => - OntologyHelpers.isKnoraResourceProperty(propertyIri, cacheData) - ), - linkProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => - OntologyHelpers.isLinkProp(propertyIri, cacheData) - ), - linkValueProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => - OntologyHelpers.isLinkValueProp(propertyIri, cacheData) - ), - fileValueProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => - OntologyHelpers.isFileValueProp(propertyIri, cacheData) - ) - ) + entityInfoContent = unescapedClassDefWithLinkValueProps, + allBaseClasses = allBaseClassIris, + isResourceClass = true, + canBeInstantiated = true, + inheritedCardinalities = inheritedCardinalities, + knoraResourceProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => + OntologyHelpers.isKnoraResourceProperty(propertyIri, cacheData) + ), + linkProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => + OntologyHelpers.isLinkProp(propertyIri, cacheData) + ), + linkValueProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => + OntologyHelpers.isLinkValueProp(propertyIri, cacheData) + ), + fileValueProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => + OntologyHelpers.isFileValueProp(propertyIri, cacheData) + ) + ) // Add the SPARQL-escaped class to the triplestore. currentTime: Instant = Instant.now updateSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .createClass( - ontologyNamedGraphIri = internalOntologyIri, - ontologyIri = internalOntologyIri, - classDef = internalClassDefWithLinkValueProps, - lastModificationDate = createClassRequest.lastModificationDate, - currentTime = currentTime - ) - .toString() + .createClass( + ontologyNamedGraphIri = internalOntologyIri, + ontologyIri = internalOntologyIri, + classDef = internalClassDefWithLinkValueProps, + lastModificationDate = createClassRequest.lastModificationDate, + currentTime = currentTime + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(updateSparql)).mapTo[SparqlUpdateResponse] // Check that the ontology's last modification date was updated. _ <- OntologyHelpers.checkOntologyLastModificationDateAfterUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = currentTime, - featureFactoryConfig = createClassRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = currentTime, + featureFactoryConfig = createClassRequest.featureFactoryConfig + ) // Check that the data that was saved corresponds to the data that was submitted. loadedClassDef <- OntologyHelpers.loadClassDefinition( - settings, - storeManager, - classIri = internalClassIri, - featureFactoryConfig = createClassRequest.featureFactoryConfig - ) + settings, + storeManager, + classIri = internalClassIri, + featureFactoryConfig = createClassRequest.featureFactoryConfig + ) _ = if (loadedClassDef != unescapedClassDefWithLinkValueProps) { - throw InconsistentRepositoryDataException( - s"Attempted to save class definition $unescapedClassDefWithLinkValueProps, but $loadedClassDef was saved" - ) - } + throw InconsistentRepositoryDataException( + s"Attempted to save class definition $unescapedClassDefWithLinkValueProps, but $loadedClassDef was saved" + ) + } // Update the cache. - updatedSubClassOfRelations = cacheData.subClassOfRelations + (internalClassIri -> allBaseClassIris) + updatedSubClassOfRelations = cacheData.subClassOfRelations + (internalClassIri -> allBaseClassIris) updatedSuperClassOfRelations = OntologyHelpers.calculateSuperClassOfRelations(updatedSubClassOfRelations) updatedOntology = ontology.copy( - ontologyMetadata = ontology.ontologyMetadata.copy( - lastModificationDate = Some(currentTime) - ), - classes = ontology.classes + (internalClassIri -> readClassInfo) - ) + ontologyMetadata = ontology.ontologyMetadata.copy( + lastModificationDate = Some(currentTime) + ), + classes = ontology.classes + (internalClassIri -> readClassInfo) + ) _ = Cache.storeCacheData( - cacheData.copy( - ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology), - subClassOfRelations = updatedSubClassOfRelations, - superClassOfRelations = updatedSuperClassOfRelations - ) - ) + cacheData.copy( + ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology), + subClassOfRelations = updatedSubClassOfRelations, + superClassOfRelations = updatedSuperClassOfRelations + ) + ) // Read the data back from the cache. response <- getClassDefinitionsFromOntologyV2( - classIris = Set(internalClassIri), - allLanguages = true, - requestingUser = createClassRequest.requestingUser - ) + classIris = Set(internalClassIri), + allLanguages = true, + requestingUser = createClassRequest.requestingUser + ) } yield response } for { requestingUser <- FastFuture.successful(createClassRequest.requestingUser) - externalClassIri = createClassRequest.classInfoContent.classIri + externalClassIri = createClassRequest.classInfoContent.classIri externalOntologyIri = externalClassIri.getOntologyFromEntity _ <- OntologyHelpers.checkOntologyAndEntityIrisForUpdate( - externalOntologyIri = externalOntologyIri, - externalEntityIri = externalClassIri, - requestingUser = requestingUser - ) + externalOntologyIri = externalOntologyIri, + externalEntityIri = externalClassIri, + requestingUser = requestingUser + ) - internalClassIri = externalClassIri.toOntologySchema(InternalSchema) + internalClassIri = externalClassIri.toOntologySchema(InternalSchema) internalOntologyIri = externalOntologyIri.toOntologySchema(InternalSchema) // Do the remaining pre-update checks and the update while holding a global ontology cache lock. taskResult <- IriLocker.runWithIriLock( - apiRequestID = createClassRequest.apiRequestID, - iri = ONTOLOGY_CACHE_LOCK_IRI, - task = () => - makeTaskFuture( - internalClassIri = internalClassIri, - internalOntologyIri = internalOntologyIri - ) - ) + apiRequestID = createClassRequest.apiRequestID, + iri = ONTOLOGY_CACHE_LOCK_IRI, + task = () => + makeTaskFuture( + internalClassIri = internalClassIri, + internalOntologyIri = internalOntologyIri + ) + ) } yield taskResult } @@ -1098,28 +1102,28 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon private def changeGuiOrder(changeGuiOrderRequest: ChangeGuiOrderRequestV2): Future[ReadOntologyV2] = { def makeTaskFuture(internalClassIri: SmartIri, internalOntologyIri: SmartIri): Future[ReadOntologyV2] = { for { - cacheData <- Cache.getCacheData + cacheData <- Cache.getCacheData internalClassDef: ClassInfoContentV2 = changeGuiOrderRequest.classInfoContent.toOntologySchema(InternalSchema) // Check that the ontology exists and has not been updated by another user since the client last read it. _ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = changeGuiOrderRequest.lastModificationDate, - featureFactoryConfig = changeGuiOrderRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = changeGuiOrderRequest.lastModificationDate, + featureFactoryConfig = changeGuiOrderRequest.featureFactoryConfig + ) // Check that the class's rdf:type is owl:Class. rdfType: SmartIri = internalClassDef.requireIriObject( - OntologyConstants.Rdf.Type.toSmartIri, - throw BadRequestException(s"No rdf:type specified") - ) + OntologyConstants.Rdf.Type.toSmartIri, + throw BadRequestException(s"No rdf:type specified") + ) _ = if (rdfType != OntologyConstants.Owl.Class.toSmartIri) { - throw BadRequestException(s"Invalid rdf:type for property: $rdfType") - } + throw BadRequestException(s"Invalid rdf:type for property: $rdfType") + } // Check that the class exists. @@ -1138,26 +1142,26 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon internalClassDef.directCardinalities.keySet -- currentReadClassInfo.entityInfoContent.directCardinalities.keySet _ = if (wrongProperties.nonEmpty) { - throw BadRequestException( - s"One or more submitted properties do not have cardinalities in class ${changeGuiOrderRequest.classInfoContent.classIri}: ${wrongProperties - .map(_.toOntologySchema(ApiV2Complex)) - .mkString(", ")}" - ) - } + throw BadRequestException( + s"One or more submitted properties do not have cardinalities in class ${changeGuiOrderRequest.classInfoContent.classIri}: ${wrongProperties + .map(_.toOntologySchema(ApiV2Complex)) + .mkString(", ")}" + ) + } linkValuePropCardinalities = internalClassDef.directCardinalities.filter { - case (propertyIri: SmartIri, _: KnoraCardinalityInfo) => - val propertyDef = cacheData - .ontologies(propertyIri.getOntologyFromEntity) - .properties(propertyIri) - propertyDef.isLinkProp - }.map { - case ( - propertyIri: SmartIri, - cardinalityWithCurrentGuiOrder: KnoraCardinalityInfo - ) => - propertyIri.fromLinkPropToLinkValueProp -> cardinalityWithCurrentGuiOrder - } + case (propertyIri: SmartIri, _: KnoraCardinalityInfo) => + val propertyDef = cacheData + .ontologies(propertyIri.getOntologyFromEntity) + .properties(propertyIri) + propertyDef.isLinkProp + }.map { + case ( + propertyIri: SmartIri, + cardinalityWithCurrentGuiOrder: KnoraCardinalityInfo + ) => + propertyIri.fromLinkPropToLinkValueProp -> cardinalityWithCurrentGuiOrder + } internalClassDefWithLinkValueProps = internalClassDef.directCardinalities ++ linkValuePropCardinalities @@ -1183,70 +1187,70 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon currentTime: Instant = Instant.now updateSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .replaceClassCardinalities( - ontologyNamedGraphIri = internalOntologyIri, - ontologyIri = internalOntologyIri, - classIri = internalClassIri, - newCardinalities = newReadClassInfo.entityInfoContent.directCardinalities, - lastModificationDate = changeGuiOrderRequest.lastModificationDate, - currentTime = currentTime - ) - .toString() + .replaceClassCardinalities( + ontologyNamedGraphIri = internalOntologyIri, + ontologyIri = internalOntologyIri, + classIri = internalClassIri, + newCardinalities = newReadClassInfo.entityInfoContent.directCardinalities, + lastModificationDate = changeGuiOrderRequest.lastModificationDate, + currentTime = currentTime + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(updateSparql)).mapTo[SparqlUpdateResponse] // Check that the ontology's last modification date was updated. _ <- OntologyHelpers.checkOntologyLastModificationDateAfterUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = currentTime, - featureFactoryConfig = changeGuiOrderRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = currentTime, + featureFactoryConfig = changeGuiOrderRequest.featureFactoryConfig + ) // Check that the data that was saved corresponds to the data that was submitted. loadedClassDef: ClassInfoContentV2 <- OntologyHelpers.loadClassDefinition( - settings, - storeManager, - classIri = internalClassIri, - featureFactoryConfig = changeGuiOrderRequest.featureFactoryConfig - ) + settings, + storeManager, + classIri = internalClassIri, + featureFactoryConfig = changeGuiOrderRequest.featureFactoryConfig + ) _ = if (loadedClassDef != newReadClassInfo.entityInfoContent) { - throw InconsistentRepositoryDataException( - s"Attempted to save class definition ${newReadClassInfo.entityInfoContent}, but $loadedClassDef was saved" - ) - } + throw InconsistentRepositoryDataException( + s"Attempted to save class definition ${newReadClassInfo.entityInfoContent}, but $loadedClassDef was saved" + ) + } // Update the cache. updatedOntology = ontology.copy( - ontologyMetadata = ontology.ontologyMetadata.copy( - lastModificationDate = Some(currentTime) - ), - classes = ontology.classes + (internalClassIri -> newReadClassInfo) - ) + ontologyMetadata = ontology.ontologyMetadata.copy( + lastModificationDate = Some(currentTime) + ), + classes = ontology.classes + (internalClassIri -> newReadClassInfo) + ) // Update subclasses and write the cache. _ = Cache.storeCacheData( - Cache.updateSubClasses( - baseClassIri = internalClassIri, - cacheData = cacheData.copy( - ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology) + Cache.updateSubClasses( + baseClassIri = internalClassIri, + cacheData = cacheData.copy( + ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology) + ) + ) ) - ) - ) // Read the data back from the cache. response <- getClassDefinitionsFromOntologyV2( - classIris = Set(internalClassIri), - allLanguages = true, - requestingUser = changeGuiOrderRequest.requestingUser - ) + classIris = Set(internalClassIri), + allLanguages = true, + requestingUser = changeGuiOrderRequest.requestingUser + ) } yield response } @@ -1254,28 +1258,28 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon for { requestingUser <- FastFuture.successful(changeGuiOrderRequest.requestingUser) - externalClassIri = changeGuiOrderRequest.classInfoContent.classIri + externalClassIri = changeGuiOrderRequest.classInfoContent.classIri externalOntologyIri = externalClassIri.getOntologyFromEntity _ <- OntologyHelpers.checkOntologyAndEntityIrisForUpdate( - externalOntologyIri = externalOntologyIri, - externalEntityIri = externalClassIri, - requestingUser = requestingUser - ) + externalOntologyIri = externalOntologyIri, + externalEntityIri = externalClassIri, + requestingUser = requestingUser + ) - internalClassIri = externalClassIri.toOntologySchema(InternalSchema) + internalClassIri = externalClassIri.toOntologySchema(InternalSchema) internalOntologyIri = externalOntologyIri.toOntologySchema(InternalSchema) // Do the remaining pre-update checks and the update while holding a global ontology cache lock. taskResult <- IriLocker.runWithIriLock( - apiRequestID = changeGuiOrderRequest.apiRequestID, - iri = ONTOLOGY_CACHE_LOCK_IRI, - task = () => - makeTaskFuture( - internalClassIri = internalClassIri, - internalOntologyIri = internalOntologyIri - ) - ) + apiRequestID = changeGuiOrderRequest.apiRequestID, + iri = ONTOLOGY_CACHE_LOCK_IRI, + task = () => + makeTaskFuture( + internalClassIri = internalClassIri, + internalOntologyIri = internalOntologyIri + ) + ) } yield taskResult } @@ -1290,34 +1294,34 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon ): Future[ReadOntologyV2] = { def makeTaskFuture(internalClassIri: SmartIri, internalOntologyIri: SmartIri): Future[ReadOntologyV2] = { for { - cacheData <- Cache.getCacheData + cacheData <- Cache.getCacheData internalClassDef: ClassInfoContentV2 = addCardinalitiesRequest.classInfoContent.toOntologySchema(InternalSchema) // Check that the ontology exists and has not been updated by another user since the client last read it. _ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = addCardinalitiesRequest.lastModificationDate, - featureFactoryConfig = addCardinalitiesRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = addCardinalitiesRequest.lastModificationDate, + featureFactoryConfig = addCardinalitiesRequest.featureFactoryConfig + ) // Check that the class's rdf:type is owl:Class. rdfType: SmartIri = internalClassDef.requireIriObject( - OntologyConstants.Rdf.Type.toSmartIri, - throw BadRequestException(s"No rdf:type specified") - ) + OntologyConstants.Rdf.Type.toSmartIri, + throw BadRequestException(s"No rdf:type specified") + ) _ = if (rdfType != OntologyConstants.Owl.Class.toSmartIri) { - throw BadRequestException(s"Invalid rdf:type for property: $rdfType") - } + throw BadRequestException(s"Invalid rdf:type for property: $rdfType") + } // Check that cardinalities were submitted. _ = if (internalClassDef.directCardinalities.isEmpty) { - throw BadRequestException("No cardinalities specified") - } + throw BadRequestException("No cardinalities specified") + } // Check that the class exists, that it's a Knora resource class, and that the submitted cardinalities aren't for properties that already have cardinalities // directly defined on the class. @@ -1333,14 +1337,14 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon existingClassDef: ClassInfoContentV2 = existingReadClassInfo.entityInfoContent redundantCardinalities = existingClassDef.directCardinalities.keySet - .intersect(internalClassDef.directCardinalities.keySet) + .intersect(internalClassDef.directCardinalities.keySet) _ = if (redundantCardinalities.nonEmpty) { - throw BadRequestException( - s"The cardinalities of ${addCardinalitiesRequest.classInfoContent.classIri} already include the following property or properties: ${redundantCardinalities - .mkString(", ")}" - ) - } + throw BadRequestException( + s"The cardinalities of ${addCardinalitiesRequest.classInfoContent.classIri} already include the following property or properties: ${redundantCardinalities + .mkString(", ")}" + ) + } // Is there any property with minCardinality>0 or Cardinality=1? hasCardinality: Option[(SmartIri, KnoraCardinalityInfo)] = @@ -1350,31 +1354,32 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon } _ <- hasCardinality match { - // If there is, check that the class isn't used in data. - case Some((propIri: SmartIri, cardinality: KnoraCardinalityInfo)) => - throwIfClassIsUsedInData( - classIri = internalClassIri, - errorFun = throw BadRequestException( - s"Cardinality ${cardinality.toString} for $propIri cannot be added to class ${addCardinalitiesRequest.classInfoContent.classIri}, because it is used in data" - ) - ) - case None => Future.successful(()) - } + // If there is, check that the class isn't used in data. + case Some((propIri: SmartIri, cardinality: KnoraCardinalityInfo)) => + throwIfClassIsUsedInData( + classIri = internalClassIri, + errorFun = throw BadRequestException( + s"Cardinality ${cardinality.toString} for $propIri cannot be added to class ${addCardinalitiesRequest.classInfoContent.classIri}, because it is used in data" + ) + ) + case None => Future.successful(()) + } // Make an updated class definition. newInternalClassDef = existingClassDef.copy( - directCardinalities = existingClassDef.directCardinalities ++ internalClassDef.directCardinalities - ) + directCardinalities = + existingClassDef.directCardinalities ++ internalClassDef.directCardinalities + ) // Check that the new cardinalities are valid, and add any inherited cardinalities. allBaseClassIrisWithoutInternal: Seq[SmartIri] = newInternalClassDef.subClassOf.toSeq.flatMap { baseClassIri => - cacheData.subClassOfRelations.getOrElse( - baseClassIri, - Seq.empty[SmartIri] - ) - } + cacheData.subClassOfRelations.getOrElse( + baseClassIri, + Seq.empty[SmartIri] + ) + } allBaseClassIris: Seq[SmartIri] = internalClassIri +: allBaseClassIrisWithoutInternal @@ -1389,12 +1394,12 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Check that the class definition doesn't refer to any non-shared ontologies in other projects. _ = Cache.checkOntologyReferencesInClassDef( - ontologyCacheData = cacheData, - classDef = newInternalClassDefWithLinkValueProps, - errorFun = { msg: String => - throw BadRequestException(msg) - } - ) + ontologyCacheData = cacheData, + classDef = newInternalClassDefWithLinkValueProps, + errorFun = { msg: String => + throw BadRequestException(msg) + } + ) // Prepare to update the ontology cache. (No need to deal with SPARQL-escaping here, because there // isn't any text to escape in cardinalities.) @@ -1407,120 +1412,120 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon } readClassInfo = ReadClassInfoV2( - entityInfoContent = newInternalClassDefWithLinkValueProps, - allBaseClasses = allBaseClassIris, - isResourceClass = true, - canBeInstantiated = true, - inheritedCardinalities = inheritedCardinalities, - knoraResourceProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => - OntologyHelpers.isKnoraResourceProperty(propertyIri, cacheData) - ), - linkProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => - OntologyHelpers.isLinkProp(propertyIri, cacheData) - ), - linkValueProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => - OntologyHelpers.isLinkValueProp(propertyIri, cacheData) - ), - fileValueProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => - OntologyHelpers.isFileValueProp(propertyIri, cacheData) - ) - ) + entityInfoContent = newInternalClassDefWithLinkValueProps, + allBaseClasses = allBaseClassIris, + isResourceClass = true, + canBeInstantiated = true, + inheritedCardinalities = inheritedCardinalities, + knoraResourceProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => + OntologyHelpers.isKnoraResourceProperty(propertyIri, cacheData) + ), + linkProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => + OntologyHelpers.isLinkProp(propertyIri, cacheData) + ), + linkValueProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => + OntologyHelpers.isLinkValueProp(propertyIri, cacheData) + ), + fileValueProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => + OntologyHelpers.isFileValueProp(propertyIri, cacheData) + ) + ) // Add the cardinalities to the class definition in the triplestore. currentTime: Instant = Instant.now updateSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .addCardinalitiesToClass( - ontologyNamedGraphIri = internalOntologyIri, - ontologyIri = internalOntologyIri, - classIri = internalClassIri, - cardinalitiesToAdd = newInternalClassDefWithLinkValueProps.directCardinalities, - lastModificationDate = addCardinalitiesRequest.lastModificationDate, - currentTime = currentTime - ) - .toString() + .addCardinalitiesToClass( + ontologyNamedGraphIri = internalOntologyIri, + ontologyIri = internalOntologyIri, + classIri = internalClassIri, + cardinalitiesToAdd = newInternalClassDefWithLinkValueProps.directCardinalities, + lastModificationDate = addCardinalitiesRequest.lastModificationDate, + currentTime = currentTime + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(updateSparql)).mapTo[SparqlUpdateResponse] // Check that the ontology's last modification date was updated. _ <- OntologyHelpers.checkOntologyLastModificationDateAfterUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = currentTime, - featureFactoryConfig = addCardinalitiesRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = currentTime, + featureFactoryConfig = addCardinalitiesRequest.featureFactoryConfig + ) // Check that the data that was saved corresponds to the data that was submitted. loadedClassDef <- OntologyHelpers.loadClassDefinition( - settings, - storeManager, - classIri = internalClassIri, - featureFactoryConfig = addCardinalitiesRequest.featureFactoryConfig - ) + settings, + storeManager, + classIri = internalClassIri, + featureFactoryConfig = addCardinalitiesRequest.featureFactoryConfig + ) _ = if (loadedClassDef != newInternalClassDefWithLinkValueProps) { - throw InconsistentRepositoryDataException( - s"Attempted to save class definition $newInternalClassDefWithLinkValueProps, but $loadedClassDef was saved" - ) - } + throw InconsistentRepositoryDataException( + s"Attempted to save class definition $newInternalClassDefWithLinkValueProps, but $loadedClassDef was saved" + ) + } // Update subclasses and write the cache. updatedOntology = ontology.copy( - ontologyMetadata = ontology.ontologyMetadata.copy( - lastModificationDate = Some(currentTime) - ), - classes = ontology.classes + (internalClassIri -> readClassInfo) - ) + ontologyMetadata = ontology.ontologyMetadata.copy( + lastModificationDate = Some(currentTime) + ), + classes = ontology.classes + (internalClassIri -> readClassInfo) + ) _ = Cache.storeCacheData( - Cache.updateSubClasses( - baseClassIri = internalClassIri, - cacheData = cacheData.copy( - ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology) + Cache.updateSubClasses( + baseClassIri = internalClassIri, + cacheData = cacheData.copy( + ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology) + ) + ) ) - ) - ) // Read the data back from the cache. response <- getClassDefinitionsFromOntologyV2( - classIris = Set(internalClassIri), - allLanguages = true, - requestingUser = addCardinalitiesRequest.requestingUser - ) + classIris = Set(internalClassIri), + allLanguages = true, + requestingUser = addCardinalitiesRequest.requestingUser + ) } yield response } for { requestingUser <- FastFuture.successful(addCardinalitiesRequest.requestingUser) - externalClassIri = addCardinalitiesRequest.classInfoContent.classIri + externalClassIri = addCardinalitiesRequest.classInfoContent.classIri externalOntologyIri = externalClassIri.getOntologyFromEntity _ <- OntologyHelpers.checkOntologyAndEntityIrisForUpdate( - externalOntologyIri = externalOntologyIri, - externalEntityIri = externalClassIri, - requestingUser = requestingUser - ) + externalOntologyIri = externalOntologyIri, + externalEntityIri = externalClassIri, + requestingUser = requestingUser + ) - internalClassIri = externalClassIri.toOntologySchema(InternalSchema) + internalClassIri = externalClassIri.toOntologySchema(InternalSchema) internalOntologyIri = externalOntologyIri.toOntologySchema(InternalSchema) // Do the remaining pre-update checks and the update while holding a global ontology cache lock. taskResult <- IriLocker.runWithIriLock( - apiRequestID = addCardinalitiesRequest.apiRequestID, - iri = ONTOLOGY_CACHE_LOCK_IRI, - task = () => - makeTaskFuture( - internalClassIri = internalClassIri, - internalOntologyIri = internalOntologyIri - ) - ) + apiRequestID = addCardinalitiesRequest.apiRequestID, + iri = ONTOLOGY_CACHE_LOCK_IRI, + task = () => + makeTaskFuture( + internalClassIri = internalClassIri, + internalOntologyIri = internalOntologyIri + ) + ) } yield taskResult } @@ -1533,31 +1538,31 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon private def canChangeClassCardinalities( canChangeCardinalitiesRequest: CanChangeCardinalitiesRequestV2 ): Future[CanDoResponseV2] = { - val internalClassIri: SmartIri = canChangeCardinalitiesRequest.classIri.toOntologySchema(InternalSchema) + val internalClassIri: SmartIri = canChangeCardinalitiesRequest.classIri.toOntologySchema(InternalSchema) val internalOntologyIri: SmartIri = internalClassIri.getOntologyFromEntity for { cacheData <- Cache.getCacheData ontology = cacheData.ontologies.getOrElse( - internalOntologyIri, - throw BadRequestException( - s"Ontology ${canChangeCardinalitiesRequest.classIri.getOntologyFromEntity} does not exist" - ) - ) + internalOntologyIri, + throw BadRequestException( + s"Ontology ${canChangeCardinalitiesRequest.classIri.getOntologyFromEntity} does not exist" + ) + ) _ = if (!ontology.classes.contains(internalClassIri)) { - throw BadRequestException(s"Class ${canChangeCardinalitiesRequest.classIri} does not exist") - } + throw BadRequestException(s"Class ${canChangeCardinalitiesRequest.classIri} does not exist") + } userCanUpdateOntology <- OntologyHelpers.canUserUpdateOntology(internalOntologyIri, canChangeCardinalitiesRequest.requestingUser) classIsUsed <- isEntityUsed( - entityIri = internalClassIri, - ignoreKnoraConstraints = - true // It's OK if a property refers to the class via knora-base:subjectClassConstraint or knora-base:objectClassConstraint. - ) + entityIri = internalClassIri, + ignoreKnoraConstraints = + true // It's OK if a property refers to the class via knora-base:subjectClassConstraint or knora-base:objectClassConstraint. + ) } yield CanDoResponseV2(userCanUpdateOntology && !classIsUsed) } @@ -1578,23 +1583,23 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Check that the ontology exists and has not been updated by another user since the client last read it. _ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = changeCardinalitiesRequest.lastModificationDate, - featureFactoryConfig = changeCardinalitiesRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = changeCardinalitiesRequest.lastModificationDate, + featureFactoryConfig = changeCardinalitiesRequest.featureFactoryConfig + ) // Check that the class's rdf:type is owl:Class. rdfType: SmartIri = internalClassDef.requireIriObject( - OntologyConstants.Rdf.Type.toSmartIri, - throw BadRequestException(s"No rdf:type specified") - ) + OntologyConstants.Rdf.Type.toSmartIri, + throw BadRequestException(s"No rdf:type specified") + ) _ = if (rdfType != OntologyConstants.Owl.Class.toSmartIri) { - throw BadRequestException(s"Invalid rdf:type for property: $rdfType") - } + throw BadRequestException(s"Invalid rdf:type for property: $rdfType") + } // Check that the class exists. @@ -1612,28 +1617,28 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // TODO: If class is used in data, check additionally if the property(ies) being removed is(are) truly used and if not, then allow. _ <- throwIfEntityIsUsed( - entityIri = internalClassIri, - errorFun = throw BadRequestException( - s"The cardinalities of class ${changeCardinalitiesRequest.classInfoContent.classIri} cannot be changed, because it is used in data or has a subclass" - ), - ignoreKnoraConstraints = - true // It's OK if a property refers to the class via knora-base:subjectClassConstraint or knora-base:objectClassConstraint. - ) + entityIri = internalClassIri, + errorFun = throw BadRequestException( + s"The cardinalities of class ${changeCardinalitiesRequest.classInfoContent.classIri} cannot be changed, because it is used in data or has a subclass" + ), + ignoreKnoraConstraints = + true // It's OK if a property refers to the class via knora-base:subjectClassConstraint or knora-base:objectClassConstraint. + ) // Make an updated class definition. newInternalClassDef = existingClassDef.copy( - directCardinalities = internalClassDef.directCardinalities - ) + directCardinalities = internalClassDef.directCardinalities + ) // Check that the new cardinalities are valid, and don't add any inherited cardinalities. allBaseClassIrisWithoutInternal: Seq[SmartIri] = newInternalClassDef.subClassOf.toSeq.flatMap { baseClassIri => - cacheData.subClassOfRelations.getOrElse( - baseClassIri, - Seq.empty[SmartIri] - ) - } + cacheData.subClassOfRelations.getOrElse( + baseClassIri, + Seq.empty[SmartIri] + ) + } allBaseClassIris: Seq[SmartIri] = internalClassIri +: allBaseClassIrisWithoutInternal @@ -1647,12 +1652,12 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Check that the class definition doesn't refer to any non-shared ontologies in other projects. _ = Cache.checkOntologyReferencesInClassDef( - ontologyCacheData = cacheData, - classDef = newInternalClassDefWithLinkValueProps, - errorFun = { msg: String => - throw BadRequestException(msg) - } - ) + ontologyCacheData = cacheData, + classDef = newInternalClassDefWithLinkValueProps, + errorFun = { msg: String => + throw BadRequestException(msg) + } + ) // Prepare to update the ontology cache. (No need to deal with SPARQL-escaping here, because there // isn't any text to escape in cardinalities.) @@ -1665,117 +1670,117 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon } readClassInfo = ReadClassInfoV2( - entityInfoContent = newInternalClassDefWithLinkValueProps, - allBaseClasses = allBaseClassIris, - isResourceClass = true, - canBeInstantiated = true, - inheritedCardinalities = inheritedCardinalities, - knoraResourceProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => - OntologyHelpers.isKnoraResourceProperty(propertyIri, cacheData) - ), - linkProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => - OntologyHelpers.isLinkProp(propertyIri, cacheData) - ), - linkValueProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => - OntologyHelpers.isLinkValueProp(propertyIri, cacheData) - ), - fileValueProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => - OntologyHelpers.isFileValueProp(propertyIri, cacheData) - ) - ) + entityInfoContent = newInternalClassDefWithLinkValueProps, + allBaseClasses = allBaseClassIris, + isResourceClass = true, + canBeInstantiated = true, + inheritedCardinalities = inheritedCardinalities, + knoraResourceProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => + OntologyHelpers.isKnoraResourceProperty(propertyIri, cacheData) + ), + linkProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => + OntologyHelpers.isLinkProp(propertyIri, cacheData) + ), + linkValueProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => + OntologyHelpers.isLinkValueProp(propertyIri, cacheData) + ), + fileValueProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => + OntologyHelpers.isFileValueProp(propertyIri, cacheData) + ) + ) // Add the cardinalities to the class definition in the triplestore. currentTime: Instant = Instant.now updateSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .replaceClassCardinalities( - ontologyNamedGraphIri = internalOntologyIri, - ontologyIri = internalOntologyIri, - classIri = internalClassIri, - newCardinalities = newInternalClassDefWithLinkValueProps.directCardinalities, - lastModificationDate = changeCardinalitiesRequest.lastModificationDate, - currentTime = currentTime - ) - .toString() + .replaceClassCardinalities( + ontologyNamedGraphIri = internalOntologyIri, + ontologyIri = internalOntologyIri, + classIri = internalClassIri, + newCardinalities = newInternalClassDefWithLinkValueProps.directCardinalities, + lastModificationDate = changeCardinalitiesRequest.lastModificationDate, + currentTime = currentTime + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(updateSparql)).mapTo[SparqlUpdateResponse] // Check that the ontology's last modification date was updated. _ <- OntologyHelpers.checkOntologyLastModificationDateAfterUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = currentTime, - featureFactoryConfig = changeCardinalitiesRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = currentTime, + featureFactoryConfig = changeCardinalitiesRequest.featureFactoryConfig + ) // Check that the data that was saved corresponds to the data that was submitted. loadedClassDef <- OntologyHelpers.loadClassDefinition( - settings, - storeManager, - classIri = internalClassIri, - featureFactoryConfig = changeCardinalitiesRequest.featureFactoryConfig - ) + settings, + storeManager, + classIri = internalClassIri, + featureFactoryConfig = changeCardinalitiesRequest.featureFactoryConfig + ) _ = if (loadedClassDef != newInternalClassDefWithLinkValueProps) { - throw InconsistentRepositoryDataException( - s"Attempted to save class definition $newInternalClassDefWithLinkValueProps, but $loadedClassDef was saved" - ) - } + throw InconsistentRepositoryDataException( + s"Attempted to save class definition $newInternalClassDefWithLinkValueProps, but $loadedClassDef was saved" + ) + } // Update the cache. updatedOntology = ontology.copy( - ontologyMetadata = ontology.ontologyMetadata.copy( - lastModificationDate = Some(currentTime) - ), - classes = ontology.classes + (internalClassIri -> readClassInfo) - ) + ontologyMetadata = ontology.ontologyMetadata.copy( + lastModificationDate = Some(currentTime) + ), + classes = ontology.classes + (internalClassIri -> readClassInfo) + ) _ = Cache.storeCacheData( - cacheData.copy( - ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology) - ) - ) + cacheData.copy( + ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology) + ) + ) // Read the data back from the cache. response <- getClassDefinitionsFromOntologyV2( - classIris = Set(internalClassIri), - allLanguages = true, - requestingUser = changeCardinalitiesRequest.requestingUser - ) + classIris = Set(internalClassIri), + allLanguages = true, + requestingUser = changeCardinalitiesRequest.requestingUser + ) } yield response } for { requestingUser <- FastFuture.successful(changeCardinalitiesRequest.requestingUser) - externalClassIri = changeCardinalitiesRequest.classInfoContent.classIri + externalClassIri = changeCardinalitiesRequest.classInfoContent.classIri externalOntologyIri = externalClassIri.getOntologyFromEntity _ <- OntologyHelpers.checkOntologyAndEntityIrisForUpdate( - externalOntologyIri = externalOntologyIri, - externalEntityIri = externalClassIri, - requestingUser = requestingUser - ) + externalOntologyIri = externalOntologyIri, + externalEntityIri = externalClassIri, + requestingUser = requestingUser + ) - internalClassIri = externalClassIri.toOntologySchema(InternalSchema) + internalClassIri = externalClassIri.toOntologySchema(InternalSchema) internalOntologyIri = externalOntologyIri.toOntologySchema(InternalSchema) // Do the remaining pre-update checks and the update while holding a global ontology cache lock. taskResult <- IriLocker.runWithIriLock( - apiRequestID = changeCardinalitiesRequest.apiRequestID, - iri = ONTOLOGY_CACHE_LOCK_IRI, - task = () => - makeTaskFuture( - internalClassIri = internalClassIri, - internalOntologyIri = internalOntologyIri - ) - ) + apiRequestID = changeCardinalitiesRequest.apiRequestID, + iri = ONTOLOGY_CACHE_LOCK_IRI, + task = () => + makeTaskFuture( + internalClassIri = internalClassIri, + internalOntologyIri = internalOntologyIri + ) + ) } yield taskResult } @@ -1792,31 +1797,31 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon for { requestingUser <- FastFuture.successful(canDeleteCardinalitiesFromClassRequest.requestingUser) - externalClassIri = canDeleteCardinalitiesFromClassRequest.classInfoContent.classIri + externalClassIri = canDeleteCardinalitiesFromClassRequest.classInfoContent.classIri externalOntologyIri = externalClassIri.getOntologyFromEntity _ <- OntologyHelpers.checkOntologyAndEntityIrisForUpdate( - externalOntologyIri = externalOntologyIri, - externalEntityIri = externalClassIri, - requestingUser = requestingUser - ) + externalOntologyIri = externalOntologyIri, + externalEntityIri = externalClassIri, + requestingUser = requestingUser + ) - internalClassIri = externalClassIri.toOntologySchema(InternalSchema) + internalClassIri = externalClassIri.toOntologySchema(InternalSchema) internalOntologyIri = externalOntologyIri.toOntologySchema(InternalSchema) // Do the remaining pre-update checks and the update while holding a global ontology cache lock. taskResult <- IriLocker.runWithIriLock( - apiRequestID = canDeleteCardinalitiesFromClassRequest.apiRequestID, - iri = ONTOLOGY_CACHE_LOCK_IRI, - task = () => - Cardinalities.canDeleteCardinalitiesFromClass( - settings, - storeManager, - deleteCardinalitiesFromClassRequest = canDeleteCardinalitiesFromClassRequest, - internalClassIri = internalClassIri, - internalOntologyIri = internalOntologyIri - ) - ) + apiRequestID = canDeleteCardinalitiesFromClassRequest.apiRequestID, + iri = ONTOLOGY_CACHE_LOCK_IRI, + task = () => + Cardinalities.canDeleteCardinalitiesFromClass( + settings, + storeManager, + deleteCardinalitiesFromClassRequest = canDeleteCardinalitiesFromClassRequest, + internalClassIri = internalClassIri, + internalOntologyIri = internalOntologyIri + ) + ) } yield taskResult /** @@ -1832,31 +1837,31 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon for { requestingUser <- FastFuture.successful(deleteCardinalitiesFromClassRequest.requestingUser) - externalClassIri = deleteCardinalitiesFromClassRequest.classInfoContent.classIri + externalClassIri = deleteCardinalitiesFromClassRequest.classInfoContent.classIri externalOntologyIri = externalClassIri.getOntologyFromEntity _ <- OntologyHelpers.checkOntologyAndEntityIrisForUpdate( - externalOntologyIri = externalOntologyIri, - externalEntityIri = externalClassIri, - requestingUser = requestingUser - ) + externalOntologyIri = externalOntologyIri, + externalEntityIri = externalClassIri, + requestingUser = requestingUser + ) - internalClassIri = externalClassIri.toOntologySchema(InternalSchema) + internalClassIri = externalClassIri.toOntologySchema(InternalSchema) internalOntologyIri = externalOntologyIri.toOntologySchema(InternalSchema) // Do the remaining pre-update checks and the update while holding a global ontology cache lock. taskResult <- IriLocker.runWithIriLock( - apiRequestID = deleteCardinalitiesFromClassRequest.apiRequestID, - iri = ONTOLOGY_CACHE_LOCK_IRI, - task = () => - Cardinalities.deleteCardinalitiesFromClass( - settings, - storeManager, - deleteCardinalitiesFromClassRequest = deleteCardinalitiesFromClassRequest, - internalClassIri = internalClassIri, - internalOntologyIri = internalOntologyIri - ) - ) + apiRequestID = deleteCardinalitiesFromClassRequest.apiRequestID, + iri = ONTOLOGY_CACHE_LOCK_IRI, + task = () => + Cardinalities.deleteCardinalitiesFromClass( + settings, + storeManager, + deleteCardinalitiesFromClassRequest = deleteCardinalitiesFromClassRequest, + internalClassIri = internalClassIri, + internalOntologyIri = internalOntologyIri + ) + ) } yield taskResult /** @@ -1866,7 +1871,7 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon * @return a [[CanDoResponseV2]]. */ private def canDeleteClass(canDeleteClassRequest: CanDeleteClassRequestV2): Future[CanDoResponseV2] = { - val internalClassIri: SmartIri = canDeleteClassRequest.classIri.toOntologySchema(InternalSchema) + val internalClassIri: SmartIri = canDeleteClassRequest.classIri.toOntologySchema(InternalSchema) val internalOntologyIri: SmartIri = internalClassIri.getOntologyFromEntity for { @@ -1879,8 +1884,8 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon ) _ = if (!ontology.classes.contains(internalClassIri)) { - throw BadRequestException(s"Class ${canDeleteClassRequest.classIri} does not exist") - } + throw BadRequestException(s"Class ${canDeleteClassRequest.classIri} does not exist") + } userCanUpdateOntology <- OntologyHelpers.canUserUpdateOntology(internalOntologyIri, canDeleteClassRequest.requestingUser) @@ -1901,64 +1906,64 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Check that the ontology exists and has not been updated by another user since the client last read it. _ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = deleteClassRequest.lastModificationDate, - featureFactoryConfig = deleteClassRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = deleteClassRequest.lastModificationDate, + featureFactoryConfig = deleteClassRequest.featureFactoryConfig + ) // Check that the class exists. ontology = cacheData.ontologies(internalOntologyIri) _ = if (!ontology.classes.contains(internalClassIri)) { - throw BadRequestException(s"Class ${deleteClassRequest.classIri} does not exist") - } + throw BadRequestException(s"Class ${deleteClassRequest.classIri} does not exist") + } // Check that the class isn't used in data or ontologies. _ <- throwIfEntityIsUsed( - entityIri = internalClassIri, - errorFun = throw BadRequestException( - s"Class ${deleteClassRequest.classIri} cannot be deleted, because it is used in data or ontologies" - ) - ) + entityIri = internalClassIri, + errorFun = throw BadRequestException( + s"Class ${deleteClassRequest.classIri} cannot be deleted, because it is used in data or ontologies" + ) + ) // Delete the class from the triplestore. currentTime: Instant = Instant.now updateSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .deleteClass( - ontologyNamedGraphIri = internalOntologyIri, - ontologyIri = internalOntologyIri, - classIri = internalClassIri, - lastModificationDate = deleteClassRequest.lastModificationDate, - currentTime = currentTime - ) - .toString() + .deleteClass( + ontologyNamedGraphIri = internalOntologyIri, + ontologyIri = internalOntologyIri, + classIri = internalClassIri, + lastModificationDate = deleteClassRequest.lastModificationDate, + currentTime = currentTime + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(updateSparql)).mapTo[SparqlUpdateResponse] // Check that the ontology's last modification date was updated. _ <- OntologyHelpers.checkOntologyLastModificationDateAfterUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = currentTime, - featureFactoryConfig = deleteClassRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = currentTime, + featureFactoryConfig = deleteClassRequest.featureFactoryConfig + ) // Update the cache. updatedOntology = ontology.copy( - ontologyMetadata = ontology.ontologyMetadata.copy( - lastModificationDate = Some(currentTime) - ), - classes = ontology.classes - internalClassIri - ) + ontologyMetadata = ontology.ontologyMetadata.copy( + lastModificationDate = Some(currentTime) + ), + classes = ontology.classes - internalClassIri + ) updatedSubClassOfRelations = (cacheData.subClassOfRelations - internalClassIri).map { case (subClass, baseClasses) => @@ -1968,39 +1973,39 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon updatedSuperClassOfRelations = OntologyHelpers.calculateSuperClassOfRelations(updatedSubClassOfRelations) _ = Cache.storeCacheData( - cacheData.copy( - ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology), - subClassOfRelations = updatedSubClassOfRelations, - superClassOfRelations = updatedSuperClassOfRelations - ) - ) + cacheData.copy( + ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology), + subClassOfRelations = updatedSubClassOfRelations, + superClassOfRelations = updatedSuperClassOfRelations + ) + ) } yield ReadOntologyMetadataV2(Set(updatedOntology.ontologyMetadata)) for { requestingUser <- FastFuture.successful(deleteClassRequest.requestingUser) - externalClassIri = deleteClassRequest.classIri + externalClassIri = deleteClassRequest.classIri externalOntologyIri = externalClassIri.getOntologyFromEntity _ <- OntologyHelpers.checkOntologyAndEntityIrisForUpdate( - externalOntologyIri = externalOntologyIri, - externalEntityIri = externalClassIri, - requestingUser = requestingUser - ) + externalOntologyIri = externalOntologyIri, + externalEntityIri = externalClassIri, + requestingUser = requestingUser + ) - internalClassIri = externalClassIri.toOntologySchema(InternalSchema) + internalClassIri = externalClassIri.toOntologySchema(InternalSchema) internalOntologyIri = externalOntologyIri.toOntologySchema(InternalSchema) // Do the remaining pre-update checks and the update while holding a global ontology cache lock. taskResult <- IriLocker.runWithIriLock( - apiRequestID = deleteClassRequest.apiRequestID, - iri = ONTOLOGY_CACHE_LOCK_IRI, - task = () => - makeTaskFuture( - internalClassIri = internalClassIri, - internalOntologyIri = internalOntologyIri - ) - ) + apiRequestID = deleteClassRequest.apiRequestID, + iri = ONTOLOGY_CACHE_LOCK_IRI, + task = () => + makeTaskFuture( + internalClassIri = internalClassIri, + internalOntologyIri = internalOntologyIri + ) + ) } yield taskResult } @@ -2018,11 +2023,11 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon cacheData <- Cache.getCacheData ontology = cacheData.ontologies.getOrElse( - internalOntologyIri, - throw BadRequestException( - s"Ontology ${canDeletePropertyRequest.propertyIri.getOntologyFromEntity} does not exist" - ) - ) + internalOntologyIri, + throw BadRequestException( + s"Ontology ${canDeletePropertyRequest.propertyIri.getOntologyFromEntity} does not exist" + ) + ) propertyDef: ReadPropertyInfoV2 = ontology.properties.getOrElse( @@ -2031,10 +2036,10 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon ) _ = if (propertyDef.isLinkValueProp) { - throw BadRequestException( - s"A link value property cannot be deleted directly; check the corresponding link property instead" - ) - } + throw BadRequestException( + s"A link value property cannot be deleted directly; check the corresponding link property instead" + ) + } userCanUpdateOntology <- OntologyHelpers.canUserUpdateOntology(internalOntologyIri, canDeletePropertyRequest.requestingUser) @@ -2055,12 +2060,12 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Check that the ontology exists and has not been updated by another user since the client last read it. _ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = deletePropertyRequest.lastModificationDate, - featureFactoryConfig = deletePropertyRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = deletePropertyRequest.lastModificationDate, + featureFactoryConfig = deletePropertyRequest.featureFactoryConfig + ) // Check that the property exists. @@ -2072,10 +2077,10 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon ) _ = if (propertyDef.isLinkValueProp) { - throw BadRequestException( - s"A link value property cannot be deleted directly; delete the corresponding link property instead" - ) - } + throw BadRequestException( + s"A link value property cannot be deleted directly; delete the corresponding link property instead" + ) + } maybeInternalLinkValuePropertyIri: Option[SmartIri] = if (propertyDef.isLinkProp) { @@ -2087,62 +2092,62 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Check that the property isn't used in data or ontologies. _ <- throwIfEntityIsUsed( - entityIri = internalPropertyIri, - errorFun = throw BadRequestException( - s"Property ${deletePropertyRequest.propertyIri} cannot be deleted, because it is used in data or ontologies" - ) - ) + entityIri = internalPropertyIri, + errorFun = throw BadRequestException( + s"Property ${deletePropertyRequest.propertyIri} cannot be deleted, because it is used in data or ontologies" + ) + ) _ <- maybeInternalLinkValuePropertyIri match { - case Some(internalLinkValuePropertyIri) => - throwIfEntityIsUsed( - entityIri = internalLinkValuePropertyIri, - errorFun = throw BadRequestException( - s"Property ${deletePropertyRequest.propertyIri} cannot be deleted, because the corresponding link value property, ${internalLinkValuePropertyIri - .toOntologySchema(ApiV2Complex)}, is used in data or ontologies" - ) - ) - - case None => FastFuture.successful(()) - } + case Some(internalLinkValuePropertyIri) => + throwIfEntityIsUsed( + entityIri = internalLinkValuePropertyIri, + errorFun = throw BadRequestException( + s"Property ${deletePropertyRequest.propertyIri} cannot be deleted, because the corresponding link value property, ${internalLinkValuePropertyIri + .toOntologySchema(ApiV2Complex)}, is used in data or ontologies" + ) + ) + + case None => FastFuture.successful(()) + } // Delete the property from the triplestore. currentTime: Instant = Instant.now updateSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .deleteProperty( - ontologyNamedGraphIri = internalOntologyIri, - ontologyIri = internalOntologyIri, - propertyIri = internalPropertyIri, - maybeLinkValuePropertyIri = maybeInternalLinkValuePropertyIri, - lastModificationDate = deletePropertyRequest.lastModificationDate, - currentTime = currentTime - ) - .toString() + .deleteProperty( + ontologyNamedGraphIri = internalOntologyIri, + ontologyIri = internalOntologyIri, + propertyIri = internalPropertyIri, + maybeLinkValuePropertyIri = maybeInternalLinkValuePropertyIri, + lastModificationDate = deletePropertyRequest.lastModificationDate, + currentTime = currentTime + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(updateSparql)).mapTo[SparqlUpdateResponse] // Check that the ontology's last modification date was updated. _ <- OntologyHelpers.checkOntologyLastModificationDateAfterUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = currentTime, - featureFactoryConfig = deletePropertyRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = currentTime, + featureFactoryConfig = deletePropertyRequest.featureFactoryConfig + ) // Update the cache. propertiesToRemoveFromCache = Set(internalPropertyIri) ++ maybeInternalLinkValuePropertyIri updatedOntology = ontology.copy( - ontologyMetadata = ontology.ontologyMetadata.copy( - lastModificationDate = Some(currentTime) - ), - properties = ontology.properties -- propertiesToRemoveFromCache - ) + ontologyMetadata = ontology.ontologyMetadata.copy( + lastModificationDate = Some(currentTime) + ), + properties = ontology.properties -- propertiesToRemoveFromCache + ) updatedSubPropertyOfRelations = (cacheData.subPropertyOfRelations -- propertiesToRemoveFromCache).map { case (subProperty, baseProperties) => @@ -2150,11 +2155,11 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon } _ = Cache.storeCacheData( - cacheData.copy( - ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology), - subPropertyOfRelations = updatedSubPropertyOfRelations - ) - ) + cacheData.copy( + ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology), + subPropertyOfRelations = updatedSubPropertyOfRelations + ) + ) } yield ReadOntologyMetadataV2(Set(updatedOntology.ontologyMetadata)) for { @@ -2164,24 +2169,24 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon externalOntologyIri = externalPropertyIri.getOntologyFromEntity _ <- OntologyHelpers.checkOntologyAndEntityIrisForUpdate( - externalOntologyIri = externalOntologyIri, - externalEntityIri = externalPropertyIri, - requestingUser = requestingUser - ) + externalOntologyIri = externalOntologyIri, + externalEntityIri = externalPropertyIri, + requestingUser = requestingUser + ) internalPropertyIri = externalPropertyIri.toOntologySchema(InternalSchema) internalOntologyIri = externalOntologyIri.toOntologySchema(InternalSchema) // Do the remaining pre-update checks and the update while holding a global ontology cache lock. taskResult <- IriLocker.runWithIriLock( - apiRequestID = deletePropertyRequest.apiRequestID, - iri = ONTOLOGY_CACHE_LOCK_IRI, - task = () => - makeTaskFuture( - internalPropertyIri = internalPropertyIri, - internalOntologyIri = internalOntologyIri - ) - ) + apiRequestID = deletePropertyRequest.apiRequestID, + iri = ONTOLOGY_CACHE_LOCK_IRI, + task = () => + makeTaskFuture( + internalPropertyIri = internalPropertyIri, + internalOntologyIri = internalOntologyIri + ) + ) } yield taskResult } @@ -2198,11 +2203,11 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon cacheData <- Cache.getCacheData ontology = cacheData.ontologies.getOrElse( - internalOntologyIri, - throw BadRequestException( - s"Ontology ${canDeleteOntologyRequest.ontologyIri.getOntologyFromEntity} does not exist" - ) - ) + internalOntologyIri, + throw BadRequestException( + s"Ontology ${canDeleteOntologyRequest.ontologyIri.getOntologyFromEntity} does not exist" + ) + ) userCanUpdateOntology <- OntologyHelpers.canUserUpdateOntology(internalOntologyIri, canDeleteOntologyRequest.requestingUser) @@ -2217,103 +2222,103 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Check that the user has permission to update the ontology. _ <- OntologyHelpers.checkPermissionsForOntologyUpdate( - internalOntologyIri = internalOntologyIri, - requestingUser = deleteOntologyRequest.requestingUser - ) + internalOntologyIri = internalOntologyIri, + requestingUser = deleteOntologyRequest.requestingUser + ) // Check that the ontology exists and has not been updated by another user since the client last read it. _ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = deleteOntologyRequest.lastModificationDate, - featureFactoryConfig = deleteOntologyRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = deleteOntologyRequest.lastModificationDate, + featureFactoryConfig = deleteOntologyRequest.featureFactoryConfig + ) // Check that none of the entities in the ontology are used in data or in other ontologies. - ontology = cacheData.ontologies(internalOntologyIri) + ontology = cacheData.ontologies(internalOntologyIri) subjectsUsingOntology: Set[IRI] <- OntologyHelpers.getSubjectsUsingOntology(settings, storeManager, ontology) _ = if (subjectsUsingOntology.nonEmpty) { - val sortedSubjects: Seq[IRI] = subjectsUsingOntology.map(s => "<" + s + ">").toVector.sorted + val sortedSubjects: Seq[IRI] = subjectsUsingOntology.map(s => "<" + s + ">").toVector.sorted - throw BadRequestException( - s"Ontology ${internalOntologyIri.toOntologySchema(ApiV2Complex)} cannot be deleted, because of subjects that refer to it: ${sortedSubjects - .mkString(", ")}" - ) - } + throw BadRequestException( + s"Ontology ${internalOntologyIri.toOntologySchema(ApiV2Complex)} cannot be deleted, because of subjects that refer to it: ${sortedSubjects + .mkString(", ")}" + ) + } // Delete everything in the ontology's named graph. updateSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .deleteOntology( - ontologyNamedGraphIri = internalOntologyIri - ) - .toString() + .deleteOntology( + ontologyNamedGraphIri = internalOntologyIri + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(updateSparql)).mapTo[SparqlUpdateResponse] // Check that the ontology has been deleted. maybeOntologyMetadata <- OntologyHelpers.loadOntologyMetadata( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - featureFactoryConfig = deleteOntologyRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + featureFactoryConfig = deleteOntologyRequest.featureFactoryConfig + ) _ = if (maybeOntologyMetadata.nonEmpty) { - throw UpdateNotPerformedException( - s"Ontology ${internalOntologyIri.toOntologySchema(ApiV2Complex)} was not deleted. Please report this as a possible bug." - ) - } + throw UpdateNotPerformedException( + s"Ontology ${internalOntologyIri.toOntologySchema(ApiV2Complex)} was not deleted. Please report this as a possible bug." + ) + } // Remove the ontology from the cache. updatedSubClassOfRelations = cacheData.subClassOfRelations.filterNot { case (subClass, _) => - subClass.getOntologyFromEntity == internalOntologyIri - }.map { case (subClass, baseClasses) => - subClass -> baseClasses.filterNot(_.getOntologyFromEntity == internalOntologyIri) - } + subClass.getOntologyFromEntity == internalOntologyIri + }.map { case (subClass, baseClasses) => + subClass -> baseClasses.filterNot(_.getOntologyFromEntity == internalOntologyIri) + } updatedSuperClassOfRelations = OntologyHelpers.calculateSuperClassOfRelations(updatedSubClassOfRelations) updatedSubPropertyOfRelations = cacheData.subPropertyOfRelations.filterNot { case (subProperty, _) => - subProperty.getOntologyFromEntity == internalOntologyIri - }.map { case (subProperty, baseProperties) => - subProperty -> baseProperties.filterNot( - _.getOntologyFromEntity == internalOntologyIri - ) - } + subProperty.getOntologyFromEntity == internalOntologyIri + }.map { case (subProperty, baseProperties) => + subProperty -> baseProperties.filterNot( + _.getOntologyFromEntity == internalOntologyIri + ) + } updatedStandoffProperties = cacheData.standoffProperties.filterNot(_.getOntologyFromEntity == internalOntologyIri) updatedCacheData = cacheData.copy( - ontologies = cacheData.ontologies - internalOntologyIri, - subClassOfRelations = updatedSubClassOfRelations, - superClassOfRelations = updatedSuperClassOfRelations, - subPropertyOfRelations = updatedSubPropertyOfRelations, - standoffProperties = updatedStandoffProperties - ) + ontologies = cacheData.ontologies - internalOntologyIri, + subClassOfRelations = updatedSubClassOfRelations, + superClassOfRelations = updatedSuperClassOfRelations, + subPropertyOfRelations = updatedSubPropertyOfRelations, + standoffProperties = updatedStandoffProperties + ) _ = Cache.storeCacheData(updatedCacheData) } yield SuccessResponseV2(s"Ontology ${internalOntologyIri.toOntologySchema(ApiV2Complex)} has been deleted") for { - _ <- OntologyHelpers.checkExternalOntologyIriForUpdate(deleteOntologyRequest.ontologyIri) + _ <- OntologyHelpers.checkExternalOntologyIriForUpdate(deleteOntologyRequest.ontologyIri) internalOntologyIri = deleteOntologyRequest.ontologyIri.toOntologySchema(InternalSchema) // Do the remaining pre-update checks and the update while holding a global ontology cache lock. taskResult <- IriLocker.runWithIriLock( - apiRequestID = deleteOntologyRequest.apiRequestID, - iri = ONTOLOGY_CACHE_LOCK_IRI, - task = () => - makeTaskFuture( - internalOntologyIri = internalOntologyIri - ) - ) + apiRequestID = deleteOntologyRequest.apiRequestID, + iri = ONTOLOGY_CACHE_LOCK_IRI, + task = () => + makeTaskFuture( + internalOntologyIri = internalOntologyIri + ) + ) } yield taskResult } @@ -2326,119 +2331,119 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon private def createProperty(createPropertyRequest: CreatePropertyRequestV2): Future[ReadOntologyV2] = { def makeTaskFuture(internalPropertyIri: SmartIri, internalOntologyIri: SmartIri): Future[ReadOntologyV2] = { for { - cacheData <- Cache.getCacheData + cacheData <- Cache.getCacheData internalPropertyDef = createPropertyRequest.propertyInfoContent.toOntologySchema(InternalSchema) // Check that the ontology exists and has not been updated by another user since the client last read it. _ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = createPropertyRequest.lastModificationDate, - featureFactoryConfig = createPropertyRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = createPropertyRequest.lastModificationDate, + featureFactoryConfig = createPropertyRequest.featureFactoryConfig + ) // Check that the property's rdf:type is owl:ObjectProperty. rdfType: SmartIri = internalPropertyDef.requireIriObject( - OntologyConstants.Rdf.Type.toSmartIri, - throw BadRequestException(s"No rdf:type specified") - ) + OntologyConstants.Rdf.Type.toSmartIri, + throw BadRequestException(s"No rdf:type specified") + ) _ = if (rdfType != OntologyConstants.Owl.ObjectProperty.toSmartIri) { - throw BadRequestException(s"Invalid rdf:type for property: $rdfType") - } + throw BadRequestException(s"Invalid rdf:type for property: $rdfType") + } // Check that the property doesn't exist yet. ontology = cacheData.ontologies(internalOntologyIri) _ = if (ontology.properties.contains(internalPropertyIri)) { - throw BadRequestException( - s"Property ${createPropertyRequest.propertyInfoContent.propertyIri} already exists" - ) - } + throw BadRequestException( + s"Property ${createPropertyRequest.propertyInfoContent.propertyIri} already exists" + ) + } // Check that the property's IRI isn't already used for something else. _ = if (ontology.classes.contains(internalPropertyIri) || ontology.individuals.contains(internalPropertyIri)) { - throw BadRequestException(s"IRI ${createPropertyRequest.propertyInfoContent.propertyIri} is already used") - } + throw BadRequestException(s"IRI ${createPropertyRequest.propertyInfoContent.propertyIri} is already used") + } // Check that the base properties that have Knora IRIs are defined as Knora resource properties. knoraSuperProperties = internalPropertyDef.subPropertyOf.filter(_.isKnoraInternalEntityIri) invalidSuperProperties = knoraSuperProperties.filterNot(baseProperty => - OntologyHelpers - .isKnoraResourceProperty( - baseProperty, - cacheData - ) && baseProperty.toString != OntologyConstants.KnoraBase.ResourceProperty - ) + OntologyHelpers + .isKnoraResourceProperty( + baseProperty, + cacheData + ) && baseProperty.toString != OntologyConstants.KnoraBase.ResourceProperty + ) _ = if (invalidSuperProperties.nonEmpty) { - throw BadRequestException( - s"One or more specified base properties are invalid: ${invalidSuperProperties.mkString(", ")}" - ) - } + throw BadRequestException( + s"One or more specified base properties are invalid: ${invalidSuperProperties.mkString(", ")}" + ) + } // Check for rdfs:subPropertyOf cycles. allKnoraSuperPropertyIrisWithoutSelf: Set[SmartIri] = knoraSuperProperties.flatMap { superPropertyIri => - cacheData.subPropertyOfRelations.getOrElse( - superPropertyIri, - Set.empty[SmartIri] - ) - } + cacheData.subPropertyOfRelations.getOrElse( + superPropertyIri, + Set.empty[SmartIri] + ) + } _ = if (allKnoraSuperPropertyIrisWithoutSelf.contains(internalPropertyIri)) { - throw BadRequestException( - s"Property ${createPropertyRequest.propertyInfoContent.propertyIri} would have a cyclical rdfs:subPropertyOf" - ) - } + throw BadRequestException( + s"Property ${createPropertyRequest.propertyInfoContent.propertyIri} would have a cyclical rdfs:subPropertyOf" + ) + } // Check the property is a subproperty of knora-base:hasValue or knora-base:hasLinkTo, but not both. allKnoraSuperPropertyIris: Set[SmartIri] = allKnoraSuperPropertyIrisWithoutSelf + internalPropertyIri - isValueProp = allKnoraSuperPropertyIris.contains(OntologyConstants.KnoraBase.HasValue.toSmartIri) - isLinkProp = allKnoraSuperPropertyIris.contains(OntologyConstants.KnoraBase.HasLinkTo.toSmartIri) + isValueProp = allKnoraSuperPropertyIris.contains(OntologyConstants.KnoraBase.HasValue.toSmartIri) + isLinkProp = allKnoraSuperPropertyIris.contains(OntologyConstants.KnoraBase.HasLinkTo.toSmartIri) isLinkValueProp = allKnoraSuperPropertyIris.contains(OntologyConstants.KnoraBase.HasLinkToValue.toSmartIri) isFileValueProp = allKnoraSuperPropertyIris.contains(OntologyConstants.KnoraBase.HasFileValue.toSmartIri) _ = if (!(isValueProp || isLinkProp)) { - throw BadRequestException( - s"Property ${createPropertyRequest.propertyInfoContent.propertyIri} would not be a subproperty of knora-api:hasValue or knora-api:hasLinkTo" - ) - } + throw BadRequestException( + s"Property ${createPropertyRequest.propertyInfoContent.propertyIri} would not be a subproperty of knora-api:hasValue or knora-api:hasLinkTo" + ) + } _ = if (isValueProp && isLinkProp) { - throw BadRequestException( - s"Property ${createPropertyRequest.propertyInfoContent.propertyIri} would be a subproperty of both knora-api:hasValue and knora-api:hasLinkTo" - ) - } + throw BadRequestException( + s"Property ${createPropertyRequest.propertyInfoContent.propertyIri} would be a subproperty of both knora-api:hasValue and knora-api:hasLinkTo" + ) + } // Don't allow new file value properties to be created. _ = if (isFileValueProp) { - throw BadRequestException("New file value properties cannot be created") - } + throw BadRequestException("New file value properties cannot be created") + } // Don't allow new link value properties to be created directly, because we do that automatically when creating a link property. _ = if (isLinkValueProp) { - throw BadRequestException( - "New link value properties cannot be created directly. Create a link property instead." - ) - } + throw BadRequestException( + "New link value properties cannot be created directly. Create a link property instead." + ) + } // Check the property's salsah-gui:guiElement and salsah-gui:guiAttribute. _ = OntologyHelpers.validateGuiAttributes( - propertyInfoContent = internalPropertyDef, - allGuiAttributeDefinitions = cacheData.guiAttributeDefinitions, - errorFun = { msg: String => - throw BadRequestException(msg) - } - ) + propertyInfoContent = internalPropertyDef, + allGuiAttributeDefinitions = cacheData.guiAttributeDefinitions, + errorFun = { msg: String => + throw BadRequestException(msg) + } + ) // If we're creating a link property, make the definition of the corresponding link value property. maybeLinkValuePropertyDef: Option[PropertyInfoContentV2] = @@ -2468,45 +2473,62 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon maybeSubjectClassConstraintPred: Option[PredicateInfoV2] = internalPropertyDef.predicates.get(OntologyConstants.KnoraBase.SubjectClassConstraint.toSmartIri) maybeSubjectClassConstraint = maybeSubjectClassConstraintPred.map( - _.requireIriObject(throw BadRequestException("Invalid knora-api:subjectType")) - ) + _.requireIriObject(throw BadRequestException("Invalid knora-api:subjectType")) + ) _ = maybeSubjectClassConstraint.foreach { subjectClassConstraint => - if (!OntologyHelpers.isKnoraInternalResourceClass(subjectClassConstraint, cacheData)) { - throw BadRequestException( - s"Invalid subject class constraint: ${subjectClassConstraint.toOntologySchema(ApiV2Complex)}" - ) - } - } + if (!OntologyHelpers.isKnoraInternalResourceClass(subjectClassConstraint, cacheData)) { + throw BadRequestException( + s"Invalid subject class constraint: ${subjectClassConstraint.toOntologySchema(ApiV2Complex)}" + ) + } + } // Check that the object class constraint designates an appropriate class that exists. objectClassConstraint: SmartIri = internalPropertyDef.requireIriObject( - OntologyConstants.KnoraBase.ObjectClassConstraint.toSmartIri, - throw BadRequestException(s"No knora-api:objectType specified") - ) + OntologyConstants.KnoraBase.ObjectClassConstraint.toSmartIri, + throw BadRequestException(s"No knora-api:objectType specified") + ) // If this is a value property, ensure its object class constraint is not LinkValue or a file value class. _ = if (!isLinkProp) { - if ( - objectClassConstraint.toString == OntologyConstants.KnoraBase.LinkValue || - OntologyConstants.KnoraBase.FileValueClasses.contains(objectClassConstraint.toString) - ) { - throw BadRequestException( - s"Invalid object class constraint for value property: ${objectClassConstraint.toOntologySchema(ApiV2Complex)}" - ) - } - } + if ( + objectClassConstraint.toString == OntologyConstants.KnoraBase.LinkValue || + OntologyConstants.KnoraBase.FileValueClasses.contains(objectClassConstraint.toString) + ) { + throw BadRequestException( + s"Invalid object class constraint for value property: ${objectClassConstraint.toOntologySchema(ApiV2Complex)}" + ) + } + } // Check that the subject class, if provided, is a subclass of the subject classes of the base properties. _ = maybeSubjectClassConstraint match { - case Some(subjectClassConstraint) => - Cache.checkPropertyConstraint( + case Some(subjectClassConstraint) => + Cache.checkPropertyConstraint( + cacheData = cacheData, + internalPropertyIri = internalPropertyIri, + constraintPredicateIri = OntologyConstants.KnoraBase.SubjectClassConstraint.toSmartIri, + constraintValueToBeChecked = subjectClassConstraint, + allSuperPropertyIris = allKnoraSuperPropertyIris, + errorSchema = ApiV2Complex, + errorFun = { msg: String => + throw BadRequestException(msg) + } + ) + + case None => () + } + + // Check that the object class is a subclass of the object classes of the base properties. + + _ = Cache.checkPropertyConstraint( cacheData = cacheData, internalPropertyIri = internalPropertyIri, - constraintPredicateIri = OntologyConstants.KnoraBase.SubjectClassConstraint.toSmartIri, - constraintValueToBeChecked = subjectClassConstraint, + constraintPredicateIri = OntologyConstants.KnoraBase.ObjectClassConstraint.toSmartIri, + constraintValueToBeChecked = objectClassConstraint, allSuperPropertyIris = allKnoraSuperPropertyIris, errorSchema = ApiV2Complex, errorFun = { msg: String => @@ -2514,76 +2536,59 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon } ) - case None => () - } - - // Check that the object class is a subclass of the object classes of the base properties. - - _ = Cache.checkPropertyConstraint( - cacheData = cacheData, - internalPropertyIri = internalPropertyIri, - constraintPredicateIri = OntologyConstants.KnoraBase.ObjectClassConstraint.toSmartIri, - constraintValueToBeChecked = objectClassConstraint, - allSuperPropertyIris = allKnoraSuperPropertyIris, - errorSchema = ApiV2Complex, - errorFun = { msg: String => - throw BadRequestException(msg) - } - ) - // Check that the property definition doesn't refer to any non-shared ontologies in other projects. _ = Cache.checkOntologyReferencesInPropertyDef( - ontologyCacheData = cacheData, - propertyDef = internalPropertyDef, - errorFun = { msg: String => - throw BadRequestException(msg) - } - ) + ontologyCacheData = cacheData, + propertyDef = internalPropertyDef, + errorFun = { msg: String => + throw BadRequestException(msg) + } + ) // Add the property (and the link value property if needed) to the triplestore. currentTime: Instant = Instant.now updateSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .createProperty( - ontologyNamedGraphIri = internalOntologyIri, - ontologyIri = internalOntologyIri, - propertyDef = internalPropertyDef, - maybeLinkValuePropertyDef = maybeLinkValuePropertyDef, - lastModificationDate = createPropertyRequest.lastModificationDate, - currentTime = currentTime - ) - .toString() + .createProperty( + ontologyNamedGraphIri = internalOntologyIri, + ontologyIri = internalOntologyIri, + propertyDef = internalPropertyDef, + maybeLinkValuePropertyDef = maybeLinkValuePropertyDef, + lastModificationDate = createPropertyRequest.lastModificationDate, + currentTime = currentTime + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(updateSparql)).mapTo[SparqlUpdateResponse] // Check that the ontology's last modification date was updated. _ <- OntologyHelpers.checkOntologyLastModificationDateAfterUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = currentTime, - featureFactoryConfig = createPropertyRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = currentTime, + featureFactoryConfig = createPropertyRequest.featureFactoryConfig + ) // Check that the data that was saved corresponds to the data that was submitted. To make this comparison, // we have to undo the SPARQL-escaping of the input. loadedPropertyDef <- OntologyHelpers.loadPropertyDefinition( - settings, - storeManager, - propertyIri = internalPropertyIri, - featureFactoryConfig = createPropertyRequest.featureFactoryConfig - ) + settings, + storeManager, + propertyIri = internalPropertyIri, + featureFactoryConfig = createPropertyRequest.featureFactoryConfig + ) unescapedInputPropertyDef = internalPropertyDef.unescape _ = if (loadedPropertyDef != unescapedInputPropertyDef) { - throw InconsistentRepositoryDataException( - s"Attempted to save property definition $unescapedInputPropertyDef, but $loadedPropertyDef was saved" - ) - } + throw InconsistentRepositoryDataException( + s"Attempted to save property definition $unescapedInputPropertyDef, but $loadedPropertyDef was saved" + ) + } maybeLoadedLinkValuePropertyDefFuture: Option[Future[PropertyInfoContentV2]] = maybeLinkValuePropertyDef.map { linkValuePropertyDef => @@ -2600,24 +2605,24 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon maybeUnescapedNewLinkValuePropertyDef = maybeLinkValuePropertyDef.map(_.unescape) _ = (maybeLoadedLinkValuePropertyDef, maybeUnescapedNewLinkValuePropertyDef) match { - case (Some(loadedLinkValuePropertyDef), Some(unescapedNewLinkPropertyDef)) => - if (loadedLinkValuePropertyDef != unescapedNewLinkPropertyDef) { - throw InconsistentRepositoryDataException( - s"Attempted to save link value property definition $unescapedNewLinkPropertyDef, but $loadedLinkValuePropertyDef was saved" - ) + case (Some(loadedLinkValuePropertyDef), Some(unescapedNewLinkPropertyDef)) => + if (loadedLinkValuePropertyDef != unescapedNewLinkPropertyDef) { + throw InconsistentRepositoryDataException( + s"Attempted to save link value property definition $unescapedNewLinkPropertyDef, but $loadedLinkValuePropertyDef was saved" + ) + } + + case _ => () } - case _ => () - } - // Update the ontology cache, using the unescaped definition(s). readPropertyInfo = ReadPropertyInfoV2( - entityInfoContent = unescapedInputPropertyDef, - isEditable = true, - isResourceProp = true, - isLinkProp = isLinkProp - ) + entityInfoContent = unescapedInputPropertyDef, + isEditable = true, + isResourceProp = true, + isLinkProp = isLinkProp + ) maybeLinkValuePropertyCacheEntry: Option[(SmartIri, ReadPropertyInfoV2)] = maybeUnescapedNewLinkValuePropertyDef.map { unescapedNewLinkPropertyDef => @@ -2630,8 +2635,8 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon } updatedOntologyMetadata = ontology.ontologyMetadata.copy( - lastModificationDate = Some(currentTime) - ) + lastModificationDate = Some(currentTime) + ) updatedOntology = ontology.copy( @@ -2657,18 +2662,18 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon } _ = Cache.storeCacheData( - cacheData.copy( - ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology), - subPropertyOfRelations = cacheData.subPropertyOfRelations ++ newSubPropertyOfRelations - ) - ) + cacheData.copy( + ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology), + subPropertyOfRelations = cacheData.subPropertyOfRelations ++ newSubPropertyOfRelations + ) + ) // Read the data back from the cache. response <- getPropertyDefinitionsFromOntologyV2( - propertyIris = Set(internalPropertyIri), - allLanguages = true, - requestingUser = createPropertyRequest.requestingUser - ) + propertyIris = Set(internalPropertyIri), + allLanguages = true, + requestingUser = createPropertyRequest.requestingUser + ) } yield response } @@ -2679,24 +2684,24 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon externalOntologyIri = externalPropertyIri.getOntologyFromEntity _ <- OntologyHelpers.checkOntologyAndEntityIrisForUpdate( - externalOntologyIri = externalOntologyIri, - externalEntityIri = externalPropertyIri, - requestingUser = requestingUser - ) + externalOntologyIri = externalOntologyIri, + externalEntityIri = externalPropertyIri, + requestingUser = requestingUser + ) internalPropertyIri = externalPropertyIri.toOntologySchema(InternalSchema) internalOntologyIri = externalOntologyIri.toOntologySchema(InternalSchema) // Do the remaining pre-update checks and the update while holding a global ontology cache lock. taskResult <- IriLocker.runWithIriLock( - apiRequestID = createPropertyRequest.apiRequestID, - iri = ONTOLOGY_CACHE_LOCK_IRI, - task = () => - makeTaskFuture( - internalPropertyIri = internalPropertyIri, - internalOntologyIri = internalOntologyIri - ) - ) + apiRequestID = createPropertyRequest.apiRequestID, + iri = ONTOLOGY_CACHE_LOCK_IRI, + task = () => + makeTaskFuture( + internalPropertyIri = internalPropertyIri, + internalOntologyIri = internalOntologyIri + ) + ) } yield taskResult } @@ -2723,12 +2728,12 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Check that the ontology exists and has not been updated by another user since the client last read it. _ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = changePropertyGuiElementRequest.lastModificationDate, - featureFactoryConfig = changePropertyGuiElementRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = changePropertyGuiElementRequest.lastModificationDate, + featureFactoryConfig = changePropertyGuiElementRequest.featureFactoryConfig + ) // If this is a link property, also change the GUI element and attribute of the corresponding link value property. @@ -2753,39 +2758,40 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon currentTime: Instant = Instant.now updateSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .changePropertyGuiElement( - ontologyNamedGraphIri = internalOntologyIri, - ontologyIri = internalOntologyIri, - propertyIri = internalPropertyIri, - maybeLinkValuePropertyIri = maybeCurrentLinkValueReadPropertyInfo.map(_.entityInfoContent.propertyIri), - maybeNewGuiElement = changePropertyGuiElementRequest.newGuiElement, - newGuiAttributes = changePropertyGuiElementRequest.newGuiAttributes, - lastModificationDate = changePropertyGuiElementRequest.lastModificationDate, - currentTime = currentTime - ) - .toString() + .changePropertyGuiElement( + ontologyNamedGraphIri = internalOntologyIri, + ontologyIri = internalOntologyIri, + propertyIri = internalPropertyIri, + maybeLinkValuePropertyIri = + maybeCurrentLinkValueReadPropertyInfo.map(_.entityInfoContent.propertyIri), + maybeNewGuiElement = changePropertyGuiElementRequest.newGuiElement, + newGuiAttributes = changePropertyGuiElementRequest.newGuiAttributes, + lastModificationDate = changePropertyGuiElementRequest.lastModificationDate, + currentTime = currentTime + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(updateSparql)).mapTo[SparqlUpdateResponse] // Check that the ontology's last modification date was updated. _ <- OntologyHelpers.checkOntologyLastModificationDateAfterUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = currentTime, - featureFactoryConfig = changePropertyGuiElementRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = currentTime, + featureFactoryConfig = changePropertyGuiElementRequest.featureFactoryConfig + ) // Check that the data that was saved corresponds to the data that was submitted. To make this comparison, // we have to undo the SPARQL-escaping of the input. loadedPropertyDef <- OntologyHelpers.loadPropertyDefinition( - settings, - storeManager, - propertyIri = internalPropertyIri, - featureFactoryConfig = changePropertyGuiElementRequest.featureFactoryConfig - ) + settings, + storeManager, + propertyIri = internalPropertyIri, + featureFactoryConfig = changePropertyGuiElementRequest.featureFactoryConfig + ) maybeNewGuiElementPredicate: Option[(SmartIri, PredicateInfoV2)] = changePropertyGuiElementRequest.newGuiElement.map { guiElement: SmartIri => @@ -2808,18 +2814,19 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon } unescapedNewPropertyDef: PropertyInfoContentV2 = currentReadPropertyInfo.entityInfoContent.copy( - predicates = currentReadPropertyInfo.entityInfoContent.predicates - - OntologyConstants.SalsahGui.GuiElementProp.toSmartIri - - OntologyConstants.SalsahGui.GuiAttribute.toSmartIri ++ - maybeNewGuiElementPredicate ++ - maybeUnescapedNewGuiAttributePredicate - ) + predicates = + currentReadPropertyInfo.entityInfoContent.predicates - + OntologyConstants.SalsahGui.GuiElementProp.toSmartIri - + OntologyConstants.SalsahGui.GuiAttribute.toSmartIri ++ + maybeNewGuiElementPredicate ++ + maybeUnescapedNewGuiAttributePredicate + ) _ = if (loadedPropertyDef != unescapedNewPropertyDef) { - throw InconsistentRepositoryDataException( - s"Attempted to save property definition $unescapedNewPropertyDef, but $loadedPropertyDef was saved" - ) - } + throw InconsistentRepositoryDataException( + s"Attempted to save property definition $unescapedNewPropertyDef, but $loadedPropertyDef was saved" + ) + } maybeLoadedLinkValuePropertyDefFuture: Option[Future[PropertyInfoContentV2]] = maybeCurrentLinkValueReadPropertyInfo.map { linkValueReadPropertyInfo => @@ -2856,11 +2863,11 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Update the ontology cache, using the unescaped definition(s). newReadPropertyInfo = ReadPropertyInfoV2( - entityInfoContent = unescapedNewPropertyDef, - isEditable = true, - isResourceProp = true, - isLinkProp = currentReadPropertyInfo.isLinkProp - ) + entityInfoContent = unescapedNewPropertyDef, + isEditable = true, + isResourceProp = true, + isLinkProp = currentReadPropertyInfo.isLinkProp + ) maybeLinkValuePropertyCacheEntry: Option[(SmartIri, ReadPropertyInfoV2)] = maybeUnescapedNewLinkValuePropertyDef.map { unescapedNewLinkPropertyDef => @@ -2872,8 +2879,8 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon } updatedOntologyMetadata = ontology.ontologyMetadata.copy( - lastModificationDate = Some(currentTime) - ) + lastModificationDate = Some(currentTime) + ) updatedOntology = ontology.copy( @@ -2883,18 +2890,18 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon ) _ = Cache.storeCacheData( - cacheData.copy( - ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology) - ) - ) + cacheData.copy( + ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology) + ) + ) // Read the data back from the cache. response <- getPropertyDefinitionsFromOntologyV2( - propertyIris = Set(internalPropertyIri), - allLanguages = true, - requestingUser = changePropertyGuiElementRequest.requestingUser - ) + propertyIris = Set(internalPropertyIri), + allLanguages = true, + requestingUser = changePropertyGuiElementRequest.requestingUser + ) } yield response } @@ -2905,24 +2912,24 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon externalOntologyIri = externalPropertyIri.getOntologyFromEntity _ <- OntologyHelpers.checkOntologyAndEntityIrisForUpdate( - externalOntologyIri = externalOntologyIri, - externalEntityIri = externalPropertyIri, - requestingUser = requestingUser - ) + externalOntologyIri = externalOntologyIri, + externalEntityIri = externalPropertyIri, + requestingUser = requestingUser + ) internalPropertyIri = externalPropertyIri.toOntologySchema(InternalSchema) internalOntologyIri = externalOntologyIri.toOntologySchema(InternalSchema) // Do the remaining pre-update checks and the update while holding a global ontology cache lock. taskResult <- IriLocker.runWithIriLock( - apiRequestID = changePropertyGuiElementRequest.apiRequestID, - iri = ONTOLOGY_CACHE_LOCK_IRI, - task = () => - makeTaskFuture( - internalPropertyIri = internalPropertyIri, - internalOntologyIri = internalOntologyIri - ) - ) + apiRequestID = changePropertyGuiElementRequest.apiRequestID, + iri = ONTOLOGY_CACHE_LOCK_IRI, + task = () => + makeTaskFuture( + internalPropertyIri = internalPropertyIri, + internalOntologyIri = internalOntologyIri + ) + ) } yield taskResult } @@ -2949,12 +2956,12 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Check that the ontology exists and has not been updated by another user since the client last read it. _ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = changePropertyLabelsOrCommentsRequest.lastModificationDate, - featureFactoryConfig = changePropertyLabelsOrCommentsRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = changePropertyLabelsOrCommentsRequest.lastModificationDate, + featureFactoryConfig = changePropertyLabelsOrCommentsRequest.featureFactoryConfig + ) // If this is a link property, also change the labels/comments of the corresponding link value property. @@ -2979,39 +2986,40 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon currentTime: Instant = Instant.now updateSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .changePropertyLabelsOrComments( - ontologyNamedGraphIri = internalOntologyIri, - ontologyIri = internalOntologyIri, - propertyIri = internalPropertyIri, - maybeLinkValuePropertyIri = maybeCurrentLinkValueReadPropertyInfo.map(_.entityInfoContent.propertyIri), - predicateToUpdate = changePropertyLabelsOrCommentsRequest.predicateToUpdate, - newObjects = changePropertyLabelsOrCommentsRequest.newObjects, - lastModificationDate = changePropertyLabelsOrCommentsRequest.lastModificationDate, - currentTime = currentTime - ) - .toString() + .changePropertyLabelsOrComments( + ontologyNamedGraphIri = internalOntologyIri, + ontologyIri = internalOntologyIri, + propertyIri = internalPropertyIri, + maybeLinkValuePropertyIri = + maybeCurrentLinkValueReadPropertyInfo.map(_.entityInfoContent.propertyIri), + predicateToUpdate = changePropertyLabelsOrCommentsRequest.predicateToUpdate, + newObjects = changePropertyLabelsOrCommentsRequest.newObjects, + lastModificationDate = changePropertyLabelsOrCommentsRequest.lastModificationDate, + currentTime = currentTime + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(updateSparql)).mapTo[SparqlUpdateResponse] // Check that the ontology's last modification date was updated. _ <- OntologyHelpers.checkOntologyLastModificationDateAfterUpdate( - settings = settings, - storeManager = storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = currentTime, - featureFactoryConfig = changePropertyLabelsOrCommentsRequest.featureFactoryConfig - ) + settings = settings, + storeManager = storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = currentTime, + featureFactoryConfig = changePropertyLabelsOrCommentsRequest.featureFactoryConfig + ) // Check that the data that was saved corresponds to the data that was submitted. To make this comparison, // we have to undo the SPARQL-escaping of the input. loadedPropertyDef <- OntologyHelpers.loadPropertyDefinition( - settings, - storeManager, - propertyIri = internalPropertyIri, - featureFactoryConfig = changePropertyLabelsOrCommentsRequest.featureFactoryConfig - ) + settings, + storeManager, + propertyIri = internalPropertyIri, + featureFactoryConfig = changePropertyLabelsOrCommentsRequest.featureFactoryConfig + ) unescapedNewLabelOrCommentPredicate: PredicateInfoV2 = PredicateInfoV2( @@ -3026,10 +3034,10 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon ) _ = if (loadedPropertyDef != unescapedNewPropertyDef) { - throw InconsistentRepositoryDataException( - s"Attempted to save property definition $unescapedNewPropertyDef, but $loadedPropertyDef was saved" - ) - } + throw InconsistentRepositoryDataException( + s"Attempted to save property definition $unescapedNewPropertyDef, but $loadedPropertyDef was saved" + ) + } maybeLoadedLinkValuePropertyDefFuture: Option[Future[PropertyInfoContentV2]] = maybeCurrentLinkValueReadPropertyInfo.map { linkValueReadPropertyInfo => @@ -3063,11 +3071,11 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Update the ontology cache, using the unescaped definition(s). newReadPropertyInfo = ReadPropertyInfoV2( - entityInfoContent = unescapedNewPropertyDef, - isEditable = true, - isResourceProp = true, - isLinkProp = currentReadPropertyInfo.isLinkProp - ) + entityInfoContent = unescapedNewPropertyDef, + isEditable = true, + isResourceProp = true, + isLinkProp = currentReadPropertyInfo.isLinkProp + ) maybeLinkValuePropertyCacheEntry: Option[(SmartIri, ReadPropertyInfoV2)] = maybeUnescapedNewLinkValuePropertyDef.map { unescapedNewLinkPropertyDef => @@ -3079,8 +3087,8 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon } updatedOntologyMetadata = ontology.ontologyMetadata.copy( - lastModificationDate = Some(currentTime) - ) + lastModificationDate = Some(currentTime) + ) updatedOntology = ontology.copy( @@ -3090,18 +3098,18 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon ) _ = Cache.storeCacheData( - cacheData.copy( - ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology) - ) - ) + cacheData.copy( + ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology) + ) + ) // Read the data back from the cache. response <- getPropertyDefinitionsFromOntologyV2( - propertyIris = Set(internalPropertyIri), - allLanguages = true, - requestingUser = changePropertyLabelsOrCommentsRequest.requestingUser - ) + propertyIris = Set(internalPropertyIri), + allLanguages = true, + requestingUser = changePropertyLabelsOrCommentsRequest.requestingUser + ) } yield response } @@ -3112,24 +3120,24 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon externalOntologyIri = externalPropertyIri.getOntologyFromEntity _ <- OntologyHelpers.checkOntologyAndEntityIrisForUpdate( - externalOntologyIri = externalOntologyIri, - externalEntityIri = externalPropertyIri, - requestingUser = requestingUser - ) + externalOntologyIri = externalOntologyIri, + externalEntityIri = externalPropertyIri, + requestingUser = requestingUser + ) internalPropertyIri = externalPropertyIri.toOntologySchema(InternalSchema) internalOntologyIri = externalOntologyIri.toOntologySchema(InternalSchema) // Do the remaining pre-update checks and the update while holding a global ontology cache lock. taskResult <- IriLocker.runWithIriLock( - apiRequestID = changePropertyLabelsOrCommentsRequest.apiRequestID, - iri = ONTOLOGY_CACHE_LOCK_IRI, - task = () => - makeTaskFuture( - internalPropertyIri = internalPropertyIri, - internalOntologyIri = internalOntologyIri - ) - ) + apiRequestID = changePropertyLabelsOrCommentsRequest.apiRequestID, + iri = ONTOLOGY_CACHE_LOCK_IRI, + task = () => + makeTaskFuture( + internalPropertyIri = internalPropertyIri, + internalOntologyIri = internalOntologyIri + ) + ) } yield taskResult } @@ -3155,55 +3163,56 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Check that the ontology exists and has not been updated by another user since the client last read it. _ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = changeClassLabelsOrCommentsRequest.lastModificationDate, - featureFactoryConfig = changeClassLabelsOrCommentsRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = changeClassLabelsOrCommentsRequest.lastModificationDate, + featureFactoryConfig = changeClassLabelsOrCommentsRequest.featureFactoryConfig + ) // Do the update. currentTime: Instant = Instant.now updateSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .changeClassLabelsOrComments( - ontologyNamedGraphIri = internalOntologyIri, - ontologyIri = internalOntologyIri, - classIri = internalClassIri, - predicateToUpdate = changeClassLabelsOrCommentsRequest.predicateToUpdate, - newObjects = changeClassLabelsOrCommentsRequest.newObjects, - lastModificationDate = changeClassLabelsOrCommentsRequest.lastModificationDate, - currentTime = currentTime - ) - .toString() + .changeClassLabelsOrComments( + ontologyNamedGraphIri = internalOntologyIri, + ontologyIri = internalOntologyIri, + classIri = internalClassIri, + predicateToUpdate = changeClassLabelsOrCommentsRequest.predicateToUpdate, + newObjects = changeClassLabelsOrCommentsRequest.newObjects, + lastModificationDate = changeClassLabelsOrCommentsRequest.lastModificationDate, + currentTime = currentTime + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(updateSparql)).mapTo[SparqlUpdateResponse] // Check that the ontology's last modification date was updated. _ <- OntologyHelpers.checkOntologyLastModificationDateAfterUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = currentTime, - featureFactoryConfig = changeClassLabelsOrCommentsRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = currentTime, + featureFactoryConfig = changeClassLabelsOrCommentsRequest.featureFactoryConfig + ) // Check that the data that was saved corresponds to the data that was submitted. To make this comparison, // we have to undo the SPARQL-escaping of the input. loadedClassDef: ClassInfoContentV2 <- OntologyHelpers.loadClassDefinition( - settings, - storeManager, - classIri = internalClassIri, - featureFactoryConfig = changeClassLabelsOrCommentsRequest.featureFactoryConfig - ) + settings, + storeManager, + classIri = internalClassIri, + featureFactoryConfig = + changeClassLabelsOrCommentsRequest.featureFactoryConfig + ) unescapedNewLabelOrCommentPredicate = PredicateInfoV2( - predicateIri = changeClassLabelsOrCommentsRequest.predicateToUpdate, - objects = changeClassLabelsOrCommentsRequest.newObjects - ).unescape + predicateIri = changeClassLabelsOrCommentsRequest.predicateToUpdate, + objects = changeClassLabelsOrCommentsRequest.newObjects + ).unescape unescapedNewClassDef: ClassInfoContentV2 = currentReadClassInfo.entityInfoContent.copy( @@ -3212,64 +3221,64 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon ) _ = if (loadedClassDef != unescapedNewClassDef) { - throw InconsistentRepositoryDataException( - s"Attempted to save class definition $unescapedNewClassDef, but $loadedClassDef was saved" - ) - } + throw InconsistentRepositoryDataException( + s"Attempted to save class definition $unescapedNewClassDef, but $loadedClassDef was saved" + ) + } // Update the ontology cache, using the unescaped definition(s). newReadClassInfo = currentReadClassInfo.copy( - entityInfoContent = unescapedNewClassDef - ) + entityInfoContent = unescapedNewClassDef + ) updatedOntology = ontology.copy( - ontologyMetadata = ontology.ontologyMetadata.copy( - lastModificationDate = Some(currentTime) - ), - classes = ontology.classes + (internalClassIri -> newReadClassInfo) - ) + ontologyMetadata = ontology.ontologyMetadata.copy( + lastModificationDate = Some(currentTime) + ), + classes = ontology.classes + (internalClassIri -> newReadClassInfo) + ) _ = Cache.storeCacheData( - cacheData.copy( - ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology) - ) - ) + cacheData.copy( + ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology) + ) + ) // Read the data back from the cache. response <- getClassDefinitionsFromOntologyV2( - classIris = Set(internalClassIri), - allLanguages = true, - requestingUser = changeClassLabelsOrCommentsRequest.requestingUser - ) + classIris = Set(internalClassIri), + allLanguages = true, + requestingUser = changeClassLabelsOrCommentsRequest.requestingUser + ) } yield response for { requestingUser <- FastFuture.successful(changeClassLabelsOrCommentsRequest.requestingUser) - externalClassIri = changeClassLabelsOrCommentsRequest.classIri + externalClassIri = changeClassLabelsOrCommentsRequest.classIri externalOntologyIri = externalClassIri.getOntologyFromEntity _ <- OntologyHelpers.checkOntologyAndEntityIrisForUpdate( - externalOntologyIri = externalOntologyIri, - externalEntityIri = externalClassIri, - requestingUser = requestingUser - ) + externalOntologyIri = externalOntologyIri, + externalEntityIri = externalClassIri, + requestingUser = requestingUser + ) - internalClassIri = externalClassIri.toOntologySchema(InternalSchema) + internalClassIri = externalClassIri.toOntologySchema(InternalSchema) internalOntologyIri = externalOntologyIri.toOntologySchema(InternalSchema) // Do the remaining pre-update checks and the update while holding a global ontology cache lock. taskResult <- IriLocker.runWithIriLock( - apiRequestID = changeClassLabelsOrCommentsRequest.apiRequestID, - iri = ONTOLOGY_CACHE_LOCK_IRI, - task = () => - makeTaskFuture( - internalClassIri = internalClassIri, - internalOntologyIri = internalOntologyIri - ) - ) + apiRequestID = changeClassLabelsOrCommentsRequest.apiRequestID, + iri = ONTOLOGY_CACHE_LOCK_IRI, + task = () => + makeTaskFuture( + internalClassIri = internalClassIri, + internalOntologyIri = internalOntologyIri + ) + ) } yield taskResult } @@ -3293,12 +3302,12 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Check that the ontology exists and has not been updated by another user since the client last read its metadata. _ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = deletePropertyCommentRequest.lastModificationDate, - featureFactoryConfig = deletePropertyCommentRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = deletePropertyCommentRequest.lastModificationDate, + featureFactoryConfig = deletePropertyCommentRequest.featureFactoryConfig + ) // If this is a link property, also delete the comment of the corresponding link value property. maybeLinkValueOfPropertyToUpdate: Option[ReadPropertyInfoV2] = @@ -3327,34 +3336,35 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Delete the comment updateSparql: String = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .deletePropertyComment( - ontologyNamedGraphIri = internalOntologyIri, - ontologyIri = internalOntologyIri, - propertyIri = internalPropertyIri, - maybeLinkValuePropertyIri = maybeLinkValueOfPropertyToUpdateIri, - lastModificationDate = deletePropertyCommentRequest.lastModificationDate, - currentTime = currentTime - ) - .toString() + .deletePropertyComment( + ontologyNamedGraphIri = internalOntologyIri, + ontologyIri = internalOntologyIri, + propertyIri = internalPropertyIri, + maybeLinkValuePropertyIri = maybeLinkValueOfPropertyToUpdateIri, + lastModificationDate = deletePropertyCommentRequest.lastModificationDate, + currentTime = currentTime + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(updateSparql)).mapTo[SparqlUpdateResponse] // Check that the ontology's last modification date was updated. _ <- OntologyHelpers.checkOntologyLastModificationDateAfterUpdate( - settings = settings, - storeManager = storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = currentTime, - featureFactoryConfig = deletePropertyCommentRequest.featureFactoryConfig - ) + settings = settings, + storeManager = storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = currentTime, + featureFactoryConfig = deletePropertyCommentRequest.featureFactoryConfig + ) // Check that the update was successful. loadedPropertyDef: PropertyInfoContentV2 <- OntologyHelpers.loadPropertyDefinition( - settings, - storeManager, - propertyIri = internalPropertyIri, - featureFactoryConfig = deletePropertyCommentRequest.featureFactoryConfig - ) + settings, + storeManager, + propertyIri = internalPropertyIri, + featureFactoryConfig = + deletePropertyCommentRequest.featureFactoryConfig + ) propertyDefWithoutComment: PropertyInfoContentV2 = propertyToUpdate.entityInfoContent.copy( @@ -3364,10 +3374,10 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon ) _ = if (loadedPropertyDef != propertyDefWithoutComment) { - throw InconsistentRepositoryDataException( - s"Attempted to save property definition $propertyDefWithoutComment, but $loadedPropertyDef was saved" - ) - } + throw InconsistentRepositoryDataException( + s"Attempted to save property definition $propertyDefWithoutComment, but $loadedPropertyDef was saved" + ) + } maybeLoadedLinkValuePropertyDefFuture: Option[Future[PropertyInfoContentV2]] = maybeLinkValueOfPropertyToUpdate.map { linkValueReadPropertyInfo: ReadPropertyInfoV2 => @@ -3401,11 +3411,11 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Update the ontology cache using the new property definition. newReadPropertyInfo: ReadPropertyInfoV2 = ReadPropertyInfoV2( - entityInfoContent = loadedPropertyDef, - isEditable = true, - isResourceProp = true, - isLinkProp = propertyToUpdate.isLinkProp - ) + entityInfoContent = loadedPropertyDef, + isEditable = true, + isResourceProp = true, + isLinkProp = propertyToUpdate.isLinkProp + ) maybeLinkValuePropertyCacheEntry: Option[(SmartIri, ReadPropertyInfoV2)] = maybeNewLinkValuePropertyDef.map { newLinkPropertyDef: PropertyInfoContentV2 => @@ -3417,8 +3427,8 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon } updatedOntologyMetadata: OntologyMetadataV2 = ontology.ontologyMetadata.copy( - lastModificationDate = Some(currentTime) - ) + lastModificationDate = Some(currentTime) + ) updatedOntology: ReadOntologyV2 = ontology.copy( @@ -3428,18 +3438,18 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon ) _ = Cache.storeCacheData( - cacheData.copy( - ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology) - ) - ) + cacheData.copy( + ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology) + ) + ) // Read the data back from the cache. response: ReadOntologyV2 <- getPropertyDefinitionsFromOntologyV2( - propertyIris = Set(internalPropertyIri), - allLanguages = true, - requestingUser = deletePropertyCommentRequest.requestingUser - ) + propertyIris = Set(internalPropertyIri), + allLanguages = true, + requestingUser = deletePropertyCommentRequest.requestingUser + ) } yield response @@ -3450,10 +3460,10 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon externalOntologyIri: SmartIri = externalPropertyIri.getOntologyFromEntity _ <- OntologyHelpers.checkOntologyAndEntityIrisForUpdate( - externalOntologyIri = externalOntologyIri, - externalEntityIri = externalPropertyIri, - requestingUser = requestingUser - ) + externalOntologyIri = externalOntologyIri, + externalEntityIri = externalPropertyIri, + requestingUser = requestingUser + ) internalPropertyIri: SmartIri = externalPropertyIri.toOntologySchema(InternalSchema) internalOntologyIri: SmartIri = externalOntologyIri.toOntologySchema(InternalSchema) @@ -3469,24 +3479,24 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon ) hasComment: Boolean = propertyToUpdate.entityInfoContent.predicates.contains( - OntologyConstants.Rdfs.Comment.toSmartIri - ) + OntologyConstants.Rdfs.Comment.toSmartIri + ) taskResult: ReadOntologyV2 <- if (hasComment) for { // Do the remaining pre-update checks and the update while holding a global ontology cache lock. taskResult: ReadOntologyV2 <- IriLocker.runWithIriLock( - apiRequestID = deletePropertyCommentRequest.apiRequestID, - iri = ONTOLOGY_CACHE_LOCK_IRI, - task = () => - makeTaskFuture( - cacheData = cacheData, - internalPropertyIri = internalPropertyIri, - internalOntologyIri = internalOntologyIri, - ontology = ontology, - propertyToUpdate = propertyToUpdate - ) - ) + apiRequestID = deletePropertyCommentRequest.apiRequestID, + iri = ONTOLOGY_CACHE_LOCK_IRI, + task = () => + makeTaskFuture( + cacheData = cacheData, + internalPropertyIri = internalPropertyIri, + internalOntologyIri = internalOntologyIri, + ontology = ontology, + propertyToUpdate = propertyToUpdate + ) + ) } yield taskResult else { // not change anything if property has no comment @@ -3519,44 +3529,44 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon // Check that the ontology exists and has not been updated by another user since the client last read its metadata. _ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = deleteClassCommentRequest.lastModificationDate, - featureFactoryConfig = deleteClassCommentRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = deleteClassCommentRequest.lastModificationDate, + featureFactoryConfig = deleteClassCommentRequest.featureFactoryConfig + ) currentTime: Instant = Instant.now // Delete the comment updateSparql: String = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .deleteClassComment( - ontologyNamedGraphIri = internalOntologyIri, - ontologyIri = internalOntologyIri, - classIri = internalClassIri, - lastModificationDate = deleteClassCommentRequest.lastModificationDate, - currentTime = currentTime - ) - .toString() + .deleteClassComment( + ontologyNamedGraphIri = internalOntologyIri, + ontologyIri = internalOntologyIri, + classIri = internalClassIri, + lastModificationDate = deleteClassCommentRequest.lastModificationDate, + currentTime = currentTime + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(updateSparql)).mapTo[SparqlUpdateResponse] // Check that the ontology's last modification date was updated. _ <- OntologyHelpers.checkOntologyLastModificationDateAfterUpdate( - settings = settings, - storeManager = storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = currentTime, - featureFactoryConfig = deleteClassCommentRequest.featureFactoryConfig - ) + settings = settings, + storeManager = storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = currentTime, + featureFactoryConfig = deleteClassCommentRequest.featureFactoryConfig + ) // Check that the update was successful. loadedClassDef: ClassInfoContentV2 <- OntologyHelpers.loadClassDefinition( - settings, - storeManager, - classIri = internalClassIri, - featureFactoryConfig = deleteClassCommentRequest.featureFactoryConfig - ) + settings, + storeManager, + classIri = internalClassIri, + featureFactoryConfig = deleteClassCommentRequest.featureFactoryConfig + ) classDefWithoutComment: ClassInfoContentV2 = classToUpdate.entityInfoContent.copy( @@ -3566,20 +3576,20 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon ) _ = if (loadedClassDef != classDefWithoutComment) { - throw InconsistentRepositoryDataException( - s"Attempted to save class definition $classDefWithoutComment, but $loadedClassDef was saved" - ) - } + throw InconsistentRepositoryDataException( + s"Attempted to save class definition $classDefWithoutComment, but $loadedClassDef was saved" + ) + } // Update the ontology cache using the new class definition. newReadClassInfo: ReadClassInfoV2 = ReadClassInfoV2( - entityInfoContent = loadedClassDef, - allBaseClasses = classToUpdate.allBaseClasses - ) + entityInfoContent = loadedClassDef, + allBaseClasses = classToUpdate.allBaseClasses + ) updatedOntologyMetadata: OntologyMetadataV2 = ontology.ontologyMetadata.copy( - lastModificationDate = Some(currentTime) - ) + lastModificationDate = Some(currentTime) + ) updatedOntology: ReadOntologyV2 = ontology.copy( @@ -3588,34 +3598,34 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon ) _ = Cache.storeCacheData( - cacheData.copy( - ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology) - ) - ) + cacheData.copy( + ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology) + ) + ) // Read the data back from the cache. response: ReadOntologyV2 <- getClassDefinitionsFromOntologyV2( - classIris = Set(internalClassIri), - allLanguages = true, - requestingUser = deleteClassCommentRequest.requestingUser - ) + classIris = Set(internalClassIri), + allLanguages = true, + requestingUser = deleteClassCommentRequest.requestingUser + ) } yield response for { requestingUser: UserADM <- FastFuture.successful(deleteClassCommentRequest.requestingUser) - externalClassIri: SmartIri = deleteClassCommentRequest.classIri + externalClassIri: SmartIri = deleteClassCommentRequest.classIri externalOntologyIri: SmartIri = externalClassIri.getOntologyFromEntity _ <- OntologyHelpers.checkOntologyAndEntityIrisForUpdate( - externalOntologyIri = externalOntologyIri, - externalEntityIri = externalClassIri, - requestingUser = requestingUser - ) + externalOntologyIri = externalOntologyIri, + externalEntityIri = externalClassIri, + requestingUser = requestingUser + ) - internalClassIri: SmartIri = externalClassIri.toOntologySchema(InternalSchema) + internalClassIri: SmartIri = externalClassIri.toOntologySchema(InternalSchema) internalOntologyIri: SmartIri = externalOntologyIri.toOntologySchema(InternalSchema) cacheData: Cache.OntologyCacheData <- Cache.getCacheData @@ -3629,24 +3639,24 @@ class OntologyResponderV2(responderData: ResponderData) extends Responder(respon ) hasComment: Boolean = classToUpdate.entityInfoContent.predicates.contains( - OntologyConstants.Rdfs.Comment.toSmartIri - ) + OntologyConstants.Rdfs.Comment.toSmartIri + ) taskResult: ReadOntologyV2 <- if (hasComment) for { // Do the remaining pre-update checks and the update while holding a global ontology cache lock. taskResult: ReadOntologyV2 <- IriLocker.runWithIriLock( - apiRequestID = deleteClassCommentRequest.apiRequestID, - iri = ONTOLOGY_CACHE_LOCK_IRI, - task = () => - makeTaskFuture( - cacheData = cacheData, - internalClassIri = internalClassIri, - internalOntologyIri = internalOntologyIri, - ontology = ontology, - classToUpdate = classToUpdate - ) - ) + apiRequestID = deleteClassCommentRequest.apiRequestID, + iri = ONTOLOGY_CACHE_LOCK_IRI, + task = () => + makeTaskFuture( + cacheData = cacheData, + internalClassIri = internalClassIri, + internalOntologyIri = internalOntologyIri, + ontology = ontology, + classToUpdate = classToUpdate + ) + ) } yield taskResult else { // not change anything if class has no comment diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v2/ResourceUtilV2.scala b/webapi/src/main/scala/org/knora/webapi/responders/v2/ResourceUtilV2.scala index edf831344b..d61ce06eeb 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/v2/ResourceUtilV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v2/ResourceUtilV2.scala @@ -137,16 +137,16 @@ object ResourceUtilV2 { ): Future[Unit] = for { askString <- Future( - org.knora.webapi.messages.twirl.queries.sparql.admin.txt - .checkListNodeExistsByIri(listNodeIri = listNodeIri) - .toString - ) + org.knora.webapi.messages.twirl.queries.sparql.admin.txt + .checkListNodeExistsByIri(listNodeIri = listNodeIri) + .toString + ) checkListNodeExistsResponse <- (storeManager ? SparqlAskRequest(askString)).mapTo[SparqlAskResponse] _ = if (!checkListNodeExistsResponse.result) { - throw NotFoundException(s"<$listNodeIri> does not exist or is not a ListNode") - } + throw NotFoundException(s"<$listNodeIri> does not exist or is not a ListNode") + } } yield () /** diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v2/ResourcesResponderV2.scala b/webapi/src/main/scala/org/knora/webapi/responders/v2/ResourcesResponderV2.scala index 0c175e5292..9dd42c5994 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/v2/ResourcesResponderV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v2/ResourcesResponderV2.scala @@ -172,76 +172,82 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt result <- stringFormatter.checkIriExists(resourceIri, storeManager) _ = if (result) { - throw DuplicateValueException(s"Resource IRI: '${resourceIri}' already exists.") - } + throw DuplicateValueException(s"Resource IRI: '${resourceIri}' already exists.") + } // Convert the resource to the internal ontology schema. - internalCreateResource: CreateResourceV2 <- Future( - createResourceRequestV2.createResource.toOntologySchema(InternalSchema) - ) + internalCreateResource: CreateResourceV2 <- + Future( + createResourceRequestV2.createResource.toOntologySchema(InternalSchema) + ) // Check link targets and list nodes that should exist. _ <- checkStandoffLinkTargets( - values = internalCreateResource.flatValues, - featureFactoryConfig = createResourceRequestV2.featureFactoryConfig, - requestingUser = createResourceRequestV2.requestingUser - ) + values = internalCreateResource.flatValues, + featureFactoryConfig = createResourceRequestV2.featureFactoryConfig, + requestingUser = createResourceRequestV2.requestingUser + ) _ <- checkListNodes(internalCreateResource.flatValues, createResourceRequestV2.requestingUser) // Get the class IRIs of all the link targets in the request. linkTargetClasses: Map[IRI, SmartIri] <- getLinkTargetClasses( - resourceIri: IRI, - internalCreateResources = Seq(internalCreateResource), - featureFactoryConfig = createResourceRequestV2.featureFactoryConfig, - requestingUser = createResourceRequestV2.requestingUser - ) + resourceIri: IRI, + internalCreateResources = Seq(internalCreateResource), + featureFactoryConfig = createResourceRequestV2.featureFactoryConfig, + requestingUser = createResourceRequestV2.requestingUser + ) // Get the definitions of the resource class and its properties, as well as of the classes of all // resources that are link targets. - resourceClassEntityInfoResponse: EntityInfoGetResponseV2 <- (responderManager ? EntityInfoGetRequestV2( - classIris = linkTargetClasses.values.toSet + internalCreateResource.resourceClassIri, - requestingUser = createResourceRequestV2.requestingUser - )).mapTo[EntityInfoGetResponseV2] + resourceClassEntityInfoResponse: EntityInfoGetResponseV2 <- + (responderManager ? EntityInfoGetRequestV2( + classIris = linkTargetClasses.values.toSet + internalCreateResource.resourceClassIri, + requestingUser = createResourceRequestV2.requestingUser + )).mapTo[EntityInfoGetResponseV2] resourceClassInfo: ReadClassInfoV2 = resourceClassEntityInfoResponse.classInfoMap( - internalCreateResource.resourceClassIri - ) + internalCreateResource.resourceClassIri + ) - propertyEntityInfoResponse: EntityInfoGetResponseV2 <- (responderManager ? EntityInfoGetRequestV2( - propertyIris = resourceClassInfo.knoraResourceProperties, - requestingUser = createResourceRequestV2.requestingUser - )).mapTo[EntityInfoGetResponseV2] + propertyEntityInfoResponse: EntityInfoGetResponseV2 <- + (responderManager ? EntityInfoGetRequestV2( + propertyIris = resourceClassInfo.knoraResourceProperties, + requestingUser = createResourceRequestV2.requestingUser + )).mapTo[EntityInfoGetResponseV2] allEntityInfo = EntityInfoGetResponseV2( - classInfoMap = resourceClassEntityInfoResponse.classInfoMap, - propertyInfoMap = propertyEntityInfoResponse.propertyInfoMap - ) + classInfoMap = resourceClassEntityInfoResponse.classInfoMap, + propertyInfoMap = propertyEntityInfoResponse.propertyInfoMap + ) // Get the default permissions of the resource class. defaultResourcePermissionsMap <- getResourceClassDefaultPermissions( - projectIri = createResourceRequestV2.createResource.projectADM.id, - resourceClassIris = Set(internalCreateResource.resourceClassIri), - requestingUser = createResourceRequestV2.requestingUser - ) + projectIri = createResourceRequestV2.createResource.projectADM.id, + resourceClassIris = Set(internalCreateResource.resourceClassIri), + requestingUser = createResourceRequestV2.requestingUser + ) defaultResourcePermissions: String = defaultResourcePermissionsMap(internalCreateResource.resourceClassIri) // Get the default permissions of each property used. defaultPropertyPermissionsMap: Map[SmartIri, Map[SmartIri, String]] <- getDefaultPropertyPermissions( - projectIri = createResourceRequestV2.createResource.projectADM.id, - resourceClassProperties = - Map(internalCreateResource.resourceClassIri -> internalCreateResource.values.keySet), - requestingUser = createResourceRequestV2.requestingUser - ) + projectIri = + createResourceRequestV2.createResource.projectADM.id, + resourceClassProperties = Map( + internalCreateResource.resourceClassIri -> internalCreateResource.values.keySet + ), + requestingUser = + createResourceRequestV2.requestingUser + ) defaultPropertyPermissions: Map[SmartIri, String] = defaultPropertyPermissionsMap( - internalCreateResource.resourceClassIri - ) + internalCreateResource.resourceClassIri + ) // Make a versionDate for the resource and its values. creationDate: Instant = internalCreateResource.creationDate.getOrElse(Instant.now) @@ -249,114 +255,122 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt // Do the remaining pre-update checks and make a ResourceReadyToCreate describing the SPARQL // for creating the resource. resourceReadyToCreate: ResourceReadyToCreate <- generateResourceReadyToCreate( - resourceIri = resourceIri, - internalCreateResource = internalCreateResource, - linkTargetClasses = linkTargetClasses, - entityInfo = allEntityInfo, - clientResourceIDs = Map.empty[IRI, String], - defaultResourcePermissions = defaultResourcePermissions, - defaultPropertyPermissions = defaultPropertyPermissions, - creationDate = creationDate, - featureFactoryConfig = createResourceRequestV2.featureFactoryConfig, - requestingUser = createResourceRequestV2.requestingUser - ) + resourceIri = resourceIri, + internalCreateResource = internalCreateResource, + linkTargetClasses = linkTargetClasses, + entityInfo = allEntityInfo, + clientResourceIDs = Map.empty[IRI, String], + defaultResourcePermissions = defaultResourcePermissions, + defaultPropertyPermissions = defaultPropertyPermissions, + creationDate = creationDate, + featureFactoryConfig = + createResourceRequestV2.featureFactoryConfig, + requestingUser = createResourceRequestV2.requestingUser + ) // Get the IRI of the named graph in which the resource will be created. dataNamedGraph: IRI = stringFormatter.projectDataNamedGraphV2(createResourceRequestV2.createResource.projectADM) // Generate SPARQL for creating the resource. sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .createNewResources( - dataNamedGraph = dataNamedGraph, - resourcesToCreate = Seq(resourceReadyToCreate.sparqlTemplateResourceToCreate), - projectIri = createResourceRequestV2.createResource.projectADM.id, - creatorIri = createResourceRequestV2.requestingUser.id - ) - .toString() + .createNewResources( + dataNamedGraph = dataNamedGraph, + resourcesToCreate = Seq(resourceReadyToCreate.sparqlTemplateResourceToCreate), + projectIri = createResourceRequestV2.createResource.projectADM.id, + creatorIri = createResourceRequestV2.requestingUser.id + ) + .toString() // Do the update. _ <- (storeManager ? SparqlUpdateRequest(sparqlUpdate)).mapTo[SparqlUpdateResponse] // Verify that the resource was created correctly. previewOfCreatedResource: ReadResourcesSequenceV2 <- verifyResource( - resourceReadyToCreate = resourceReadyToCreate, - projectIri = createResourceRequestV2.createResource.projectADM.id, - featureFactoryConfig = createResourceRequestV2.featureFactoryConfig, - requestingUser = createResourceRequestV2.requestingUser - ) + resourceReadyToCreate = resourceReadyToCreate, + projectIri = + createResourceRequestV2.createResource.projectADM.id, + featureFactoryConfig = + createResourceRequestV2.featureFactoryConfig, + requestingUser = createResourceRequestV2.requestingUser + ) } yield previewOfCreatedResource } val triplestoreUpdateFuture: Future[ReadResourcesSequenceV2] = for { // Don't allow anonymous users to create resources. _ <- Future { - if (createResourceRequestV2.requestingUser.isAnonymousUser) { - throw ForbiddenException("Anonymous users aren't allowed to create resources") - } else { - createResourceRequestV2.requestingUser.id - } - } + if (createResourceRequestV2.requestingUser.isAnonymousUser) { + throw ForbiddenException("Anonymous users aren't allowed to create resources") + } else { + createResourceRequestV2.requestingUser.id + } + } // Ensure that the project isn't the system project or the shared ontologies project. projectIri = createResourceRequestV2.createResource.projectADM.id - _ = if ( - projectIri == OntologyConstants.KnoraAdmin.SystemProject || projectIri == OntologyConstants.KnoraAdmin.DefaultSharedOntologiesProject - ) { - throw BadRequestException(s"Resources cannot be created in project <$projectIri>") - } + _ = + if ( + projectIri == OntologyConstants.KnoraAdmin.SystemProject || projectIri == OntologyConstants.KnoraAdmin.DefaultSharedOntologiesProject + ) { + throw BadRequestException(s"Resources cannot be created in project <$projectIri>") + } // Ensure that the resource class isn't from a non-shared ontology in another project. resourceClassOntologyIri: SmartIri = createResourceRequestV2.createResource.resourceClassIri.getOntologyFromEntity readOntologyMetadataV2: ReadOntologyMetadataV2 <- (responderManager ? OntologyMetadataGetByIriRequestV2( - Set(resourceClassOntologyIri), - createResourceRequestV2.requestingUser - )).mapTo[ReadOntologyMetadataV2] - ontologyMetadata: OntologyMetadataV2 = readOntologyMetadataV2.ontologies.headOption - .getOrElse(throw BadRequestException(s"Ontology $resourceClassOntologyIri not found")) - ontologyProjectIri: IRI = ontologyMetadata.projectIri - .getOrElse(throw InconsistentRepositoryDataException(s"Ontology $resourceClassOntologyIri has no project")) - .toString - - _ = if ( - projectIri != ontologyProjectIri && !(ontologyMetadata.ontologyIri.isKnoraBuiltInDefinitionIri || ontologyMetadata.ontologyIri.isKnoraSharedDefinitionIri) - ) { - throw BadRequestException( - s"Cannot create a resource in project <$projectIri> with resource class <${createResourceRequestV2.createResource.resourceClassIri}>, which is defined in a non-shared ontology in another project" - ) - } + Set(resourceClassOntologyIri), + createResourceRequestV2.requestingUser + )).mapTo[ReadOntologyMetadataV2] + ontologyMetadata: OntologyMetadataV2 = + readOntologyMetadataV2.ontologies.headOption + .getOrElse(throw BadRequestException(s"Ontology $resourceClassOntologyIri not found")) + ontologyProjectIri: IRI = + ontologyMetadata.projectIri + .getOrElse(throw InconsistentRepositoryDataException(s"Ontology $resourceClassOntologyIri has no project")) + .toString + + _ = + if ( + projectIri != ontologyProjectIri && !(ontologyMetadata.ontologyIri.isKnoraBuiltInDefinitionIri || ontologyMetadata.ontologyIri.isKnoraSharedDefinitionIri) + ) { + throw BadRequestException( + s"Cannot create a resource in project <$projectIri> with resource class <${createResourceRequestV2.createResource.resourceClassIri}>, which is defined in a non-shared ontology in another project" + ) + } // Check user's PermissionProfile (part of UserADM) to see if the user has the permission to // create a new resource in the given project. internalResourceClassIri: SmartIri = createResourceRequestV2.createResource.resourceClassIri - .toOntologySchema(InternalSchema) + .toOntologySchema(InternalSchema) _ = if ( - !createResourceRequestV2.requestingUser.permissions.hasPermissionFor( - ResourceCreateOperation(internalResourceClassIri.toString), - projectIri, - None - ) - ) { - throw ForbiddenException( - s"User ${createResourceRequestV2.requestingUser.username} does not have permission to create a resource of class <${createResourceRequestV2.createResource.resourceClassIri}> in project <$projectIri>" - ) - } + !createResourceRequestV2.requestingUser.permissions.hasPermissionFor( + ResourceCreateOperation(internalResourceClassIri.toString), + projectIri, + None + ) + ) { + throw ForbiddenException( + s"User ${createResourceRequestV2.requestingUser.username} does not have permission to create a resource of class <${createResourceRequestV2.createResource.resourceClassIri}> in project <$projectIri>" + ) + } - resourceIri: IRI <- checkOrCreateEntityIri( - createResourceRequestV2.createResource.resourceIri, - stringFormatter.makeRandomResourceIri(createResourceRequestV2.createResource.projectADM.shortcode) - ) + resourceIri: IRI <- + checkOrCreateEntityIri( + createResourceRequestV2.createResource.resourceIri, + stringFormatter.makeRandomResourceIri(createResourceRequestV2.createResource.projectADM.shortcode) + ) // Do the remaining pre-update checks and the update while holding an update lock on the resource to be created. taskResult <- IriLocker.runWithIriLock( - createResourceRequestV2.apiRequestID, - resourceIri, - () => makeTaskFuture(resourceIri) - ) + createResourceRequestV2.apiRequestID, + resourceIri, + () => makeTaskFuture(resourceIri) + ) } yield taskResult // If the request includes file values, tell Sipi to move the files to permanent storage if the update @@ -381,74 +395,82 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt for { // Get the metadata of the resource to be updated. resourcesSeq: ReadResourcesSequenceV2 <- getResourcePreviewV2( - resourceIris = Seq(updateResourceMetadataRequestV2.resourceIri), - targetSchema = ApiV2Complex, - featureFactoryConfig = updateResourceMetadataRequestV2.featureFactoryConfig, - requestingUser = updateResourceMetadataRequestV2.requestingUser - ) + resourceIris = Seq(updateResourceMetadataRequestV2.resourceIri), + targetSchema = ApiV2Complex, + featureFactoryConfig = + updateResourceMetadataRequestV2.featureFactoryConfig, + requestingUser = updateResourceMetadataRequestV2.requestingUser + ) resource: ReadResourceV2 = resourcesSeq.toResource(updateResourceMetadataRequestV2.resourceIri) internalResourceClassIri = updateResourceMetadataRequestV2.resourceClassIri.toOntologySchema(InternalSchema) // Make sure that the resource's class is what the client thinks it is. _ = if (resource.resourceClassIri != internalResourceClassIri) { - throw BadRequestException( - s"Resource <${resource.resourceIri}> is not a member of class <${updateResourceMetadataRequestV2.resourceClassIri}>" - ) - } + throw BadRequestException( + s"Resource <${resource.resourceIri}> is not a member of class <${updateResourceMetadataRequestV2.resourceClassIri}>" + ) + } // If resource has already been modified, make sure that its lastModificationDate is given in the request body. - _ = if ( - resource.lastModificationDate.nonEmpty && updateResourceMetadataRequestV2.maybeLastModificationDate.isEmpty - ) { - throw EditConflictException( - s"Resource <${resource.resourceIri}> has been modified in the past. Its lastModificationDate " + - s"${resource.lastModificationDate.get} must be included in the request body." - ) - } + _ = + if ( + resource.lastModificationDate.nonEmpty && updateResourceMetadataRequestV2.maybeLastModificationDate.isEmpty + ) { + throw EditConflictException( + s"Resource <${resource.resourceIri}> has been modified in the past. Its lastModificationDate " + + s"${resource.lastModificationDate.get} must be included in the request body." + ) + } // Make sure that the resource hasn't been updated since the client got its last modification date. _ = if ( - updateResourceMetadataRequestV2.maybeLastModificationDate.nonEmpty && - resource.lastModificationDate != updateResourceMetadataRequestV2.maybeLastModificationDate - ) { - throw EditConflictException(s"Resource <${resource.resourceIri}> has been modified since you last read it") - } + updateResourceMetadataRequestV2.maybeLastModificationDate.nonEmpty && + resource.lastModificationDate != updateResourceMetadataRequestV2.maybeLastModificationDate + ) { + throw EditConflictException( + s"Resource <${resource.resourceIri}> has been modified since you last read it" + ) + } // Check that the user has permission to modify the resource. _ = ResourceUtilV2.checkResourcePermission( - resourceInfo = resource, - permissionNeeded = ModifyPermission, - requestingUser = updateResourceMetadataRequestV2.requestingUser - ) + resourceInfo = resource, + permissionNeeded = ModifyPermission, + requestingUser = updateResourceMetadataRequestV2.requestingUser + ) // Get the IRI of the named graph in which the resource is stored. dataNamedGraph: IRI = stringFormatter.projectDataNamedGraphV2(resource.projectADM) newModificationDate: Instant = updateResourceMetadataRequestV2.maybeNewModificationDate match { - case Some(submittedNewModificationDate) => - if (resource.lastModificationDate.exists(_.isAfter(submittedNewModificationDate))) { - throw BadRequestException( - s"Submitted knora-api:newModificationDate is before the resource's current knora-api:lastModificationDate" - ) - } else { - submittedNewModificationDate - } - case None => Instant.now - } + case Some(submittedNewModificationDate) => + if ( + resource.lastModificationDate.exists( + _.isAfter(submittedNewModificationDate) + ) + ) { + throw BadRequestException( + s"Submitted knora-api:newModificationDate is before the resource's current knora-api:lastModificationDate" + ) + } else { + submittedNewModificationDate + } + case None => Instant.now + } // Generate SPARQL for updating the resource. sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .changeResourceMetadata( - dataNamedGraph = dataNamedGraph, - resourceIri = updateResourceMetadataRequestV2.resourceIri, - resourceClassIri = internalResourceClassIri, - maybeLastModificationDate = updateResourceMetadataRequestV2.maybeLastModificationDate, - newModificationDate = newModificationDate, - maybeLabel = updateResourceMetadataRequestV2.maybeLabel, - maybePermissions = updateResourceMetadataRequestV2.maybePermissions - ) - .toString() + .changeResourceMetadata( + dataNamedGraph = dataNamedGraph, + resourceIri = updateResourceMetadataRequestV2.resourceIri, + resourceClassIri = internalResourceClassIri, + maybeLastModificationDate = updateResourceMetadataRequestV2.maybeLastModificationDate, + newModificationDate = newModificationDate, + maybeLabel = updateResourceMetadataRequestV2.maybeLabel, + maybePermissions = updateResourceMetadataRequestV2.maybePermissions + ) + .toString() // Do the update. _ <- (storeManager ? SparqlUpdateRequest(sparqlUpdate)).mapTo[SparqlUpdateResponse] @@ -456,55 +478,58 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt // Verify that the resource was updated correctly. updatedResourcesSeq: ReadResourcesSequenceV2 <- getResourcePreviewV2( - resourceIris = Seq(updateResourceMetadataRequestV2.resourceIri), - targetSchema = ApiV2Complex, - featureFactoryConfig = updateResourceMetadataRequestV2.featureFactoryConfig, - requestingUser = updateResourceMetadataRequestV2.requestingUser - ) + resourceIris = + Seq(updateResourceMetadataRequestV2.resourceIri), + targetSchema = ApiV2Complex, + featureFactoryConfig = + updateResourceMetadataRequestV2.featureFactoryConfig, + requestingUser = + updateResourceMetadataRequestV2.requestingUser + ) _ = if (updatedResourcesSeq.resources.size != 1) { - throw AssertionException(s"Expected one resource, got ${resourcesSeq.resources.size}") - } + throw AssertionException(s"Expected one resource, got ${resourcesSeq.resources.size}") + } updatedResource: ReadResourceV2 = updatedResourcesSeq.resources.head _ = if (!updatedResource.lastModificationDate.contains(newModificationDate)) { - throw UpdateNotPerformedException( - s"Updated resource has last modification date ${updatedResource.lastModificationDate}, expected $newModificationDate" - ) - } + throw UpdateNotPerformedException( + s"Updated resource has last modification date ${updatedResource.lastModificationDate}, expected $newModificationDate" + ) + } _ = updateResourceMetadataRequestV2.maybeLabel match { - case Some(newLabel) => - if (!updatedResource.label.contains(stringFormatter.fromSparqlEncodedString(newLabel))) { - throw UpdateNotPerformedException() - } + case Some(newLabel) => + if (!updatedResource.label.contains(stringFormatter.fromSparqlEncodedString(newLabel))) { + throw UpdateNotPerformedException() + } - case None => () - } + case None => () + } _ = updateResourceMetadataRequestV2.maybePermissions match { - case Some(newPermissions) => - if ( - PermissionUtilADM - .parsePermissions(updatedResource.permissions) != PermissionUtilADM.parsePermissions(newPermissions) - ) { - throw UpdateNotPerformedException() - } + case Some(newPermissions) => + if ( + PermissionUtilADM + .parsePermissions(updatedResource.permissions) != PermissionUtilADM.parsePermissions(newPermissions) + ) { + throw UpdateNotPerformedException() + } - case None => () - } + case None => () + } // If the resource's label was changed, update the full-text search index. _ <- updateResourceMetadataRequestV2.maybeLabel match { - case Some(_) => - for { - _ <- (storeManager ? SearchIndexUpdateRequest(Some(updateResourceMetadataRequestV2.resourceIri))) - .mapTo[SparqlUpdateResponse] - } yield () - - case None => FastFuture.successful(()) - } + case Some(_) => + for { + _ <- (storeManager ? SearchIndexUpdateRequest(Some(updateResourceMetadataRequestV2.resourceIri))) + .mapTo[SparqlUpdateResponse] + } yield () + + case None => FastFuture.successful(()) + } } yield UpdateResourceMetadataResponseV2( resourceIri = updateResourceMetadataRequestV2.resourceIri, resourceClassIri = updateResourceMetadataRequestV2.resourceClassIri, @@ -518,10 +543,10 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt for { // Do the remaining pre-update checks and the update while holding an update lock on the resource. taskResult <- IriLocker.runWithIriLock( - updateResourceMetadataRequestV2.apiRequestID, - updateResourceMetadataRequestV2.resourceIri, - () => makeTaskFuture - ) + updateResourceMetadataRequestV2.apiRequestID, + updateResourceMetadataRequestV2.resourceIri, + () => makeTaskFuture + ) } yield taskResult } @@ -550,58 +575,60 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt for { // Get the metadata of the resource to be updated. resourcesSeq: ReadResourcesSequenceV2 <- getResourcePreviewV2( - resourceIris = Seq(deleteResourceV2.resourceIri), - targetSchema = ApiV2Complex, - featureFactoryConfig = deleteResourceV2.featureFactoryConfig, - requestingUser = deleteResourceV2.requestingUser - ) + resourceIris = Seq(deleteResourceV2.resourceIri), + targetSchema = ApiV2Complex, + featureFactoryConfig = deleteResourceV2.featureFactoryConfig, + requestingUser = deleteResourceV2.requestingUser + ) resource: ReadResourceV2 = resourcesSeq.toResource(deleteResourceV2.resourceIri) internalResourceClassIri = deleteResourceV2.resourceClassIri.toOntologySchema(InternalSchema) // Make sure that the resource's class is what the client thinks it is. _ = if (resource.resourceClassIri != internalResourceClassIri) { - throw BadRequestException( - s"Resource <${resource.resourceIri}> is not a member of class <${deleteResourceV2.resourceClassIri}>" - ) - } + throw BadRequestException( + s"Resource <${resource.resourceIri}> is not a member of class <${deleteResourceV2.resourceClassIri}>" + ) + } // Make sure that the resource hasn't been updated since the client got its last modification date. _ = if (resource.lastModificationDate != deleteResourceV2.maybeLastModificationDate) { - throw EditConflictException(s"Resource <${resource.resourceIri}> has been modified since you last read it") - } + throw EditConflictException( + s"Resource <${resource.resourceIri}> has been modified since you last read it" + ) + } // If a custom delete date was provided, make sure it's later than the resource's most recent timestamp. _ = if ( - deleteResourceV2.maybeDeleteDate.exists( - !_.isAfter(resource.lastModificationDate.getOrElse(resource.creationDate)) - ) - ) { - throw BadRequestException( - s"A custom delete date must be later than the date when the resource was created or last modified" - ) - } + deleteResourceV2.maybeDeleteDate.exists( + !_.isAfter(resource.lastModificationDate.getOrElse(resource.creationDate)) + ) + ) { + throw BadRequestException( + s"A custom delete date must be later than the date when the resource was created or last modified" + ) + } // Check that the user has permission to mark the resource as deleted. _ = ResourceUtilV2.checkResourcePermission( - resourceInfo = resource, - permissionNeeded = DeletePermission, - requestingUser = deleteResourceV2.requestingUser - ) + resourceInfo = resource, + permissionNeeded = DeletePermission, + requestingUser = deleteResourceV2.requestingUser + ) // Get the IRI of the named graph in which the resource is stored. dataNamedGraph: IRI = stringFormatter.projectDataNamedGraphV2(resource.projectADM) // Generate SPARQL for marking the resource as deleted. sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .deleteResource( - dataNamedGraph = dataNamedGraph, - resourceIri = deleteResourceV2.resourceIri, - maybeDeleteComment = deleteResourceV2.maybeDeleteComment, - currentTime = deleteResourceV2.maybeDeleteDate.getOrElse(Instant.now), - requestingUser = deleteResourceV2.requestingUser.id - ) - .toString() + .deleteResource( + dataNamedGraph = dataNamedGraph, + resourceIri = deleteResourceV2.resourceIri, + maybeDeleteComment = deleteResourceV2.maybeDeleteComment, + currentTime = deleteResourceV2.maybeDeleteDate.getOrElse(Instant.now), + requestingUser = deleteResourceV2.requestingUser.id + ) + .toString() // Do the update. _ <- (storeManager ? SparqlUpdateRequest(sparqlUpdate)).mapTo[SparqlUpdateResponse] @@ -609,27 +636,27 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt // Verify that the resource was deleted correctly. sparqlQuery = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .checkResourceDeletion( - resourceIri = deleteResourceV2.resourceIri - ) - .toString() + .checkResourceDeletion( + resourceIri = deleteResourceV2.resourceIri + ) + .toString() sparqlSelectResponse <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] rows = sparqlSelectResponse.results.bindings _ = if ( - rows.isEmpty || !stringFormatter.optionStringToBoolean( - rows.head.rowMap.get("isDeleted"), - throw InconsistentRepositoryDataException( - s"Invalid boolean for isDeleted: ${rows.head.rowMap.get("isDeleted")}" - ) - ) - ) { - throw UpdateNotPerformedException( - s"Resource <${deleteResourceV2.resourceIri}> was not marked as deleted. Please report this as a possible bug." - ) - } + rows.isEmpty || !stringFormatter.optionStringToBoolean( + rows.head.rowMap.get("isDeleted"), + throw InconsistentRepositoryDataException( + s"Invalid boolean for isDeleted: ${rows.head.rowMap.get("isDeleted")}" + ) + ) + ) { + throw UpdateNotPerformedException( + s"Resource <${deleteResourceV2.resourceIri}> was not marked as deleted. Please report this as a possible bug." + ) + } } yield SuccessResponseV2("Resource marked as deleted") if (deleteResourceV2.erase) { @@ -639,10 +666,10 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt for { // Do the remaining pre-update checks and the update while holding an update lock on the resource. taskResult <- IriLocker.runWithIriLock( - deleteResourceV2.apiRequestID, - deleteResourceV2.resourceIri, - () => makeTaskFuture - ) + deleteResourceV2.apiRequestID, + deleteResourceV2.resourceIri, + () => makeTaskFuture + ) } yield taskResult } @@ -656,35 +683,37 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt for { // Get the metadata of the resource to be updated. resourcesSeq: ReadResourcesSequenceV2 <- getResourcePreviewV2( - resourceIris = Seq(eraseResourceV2.resourceIri), - targetSchema = ApiV2Complex, - featureFactoryConfig = eraseResourceV2.featureFactoryConfig, - requestingUser = eraseResourceV2.requestingUser - ) + resourceIris = Seq(eraseResourceV2.resourceIri), + targetSchema = ApiV2Complex, + featureFactoryConfig = eraseResourceV2.featureFactoryConfig, + requestingUser = eraseResourceV2.requestingUser + ) resource: ReadResourceV2 = resourcesSeq.toResource(eraseResourceV2.resourceIri) // Ensure that the requesting user is a system admin, or an admin of this project. _ = if ( - !(eraseResourceV2.requestingUser.permissions.isProjectAdmin(resource.projectADM.id) || - eraseResourceV2.requestingUser.permissions.isSystemAdmin) - ) { - throw ForbiddenException(s"Only a system admin or project admin can erase a resource") - } + !(eraseResourceV2.requestingUser.permissions.isProjectAdmin(resource.projectADM.id) || + eraseResourceV2.requestingUser.permissions.isSystemAdmin) + ) { + throw ForbiddenException(s"Only a system admin or project admin can erase a resource") + } internalResourceClassIri = eraseResourceV2.resourceClassIri.toOntologySchema(InternalSchema) // Make sure that the resource's class is what the client thinks it is. _ = if (resource.resourceClassIri != internalResourceClassIri) { - throw BadRequestException( - s"Resource <${resource.resourceIri}> is not a member of class <${eraseResourceV2.resourceClassIri}>" - ) - } + throw BadRequestException( + s"Resource <${resource.resourceIri}> is not a member of class <${eraseResourceV2.resourceClassIri}>" + ) + } // Make sure that the resource hasn't been updated since the client got its last modification date. _ = if (resource.lastModificationDate != eraseResourceV2.maybeLastModificationDate) { - throw EditConflictException(s"Resource <${resource.resourceIri}> has been modified since you last read it") - } + throw EditConflictException( + s"Resource <${resource.resourceIri}> has been modified since you last read it" + ) + } // Check that the resource is not referred to by any other resources. We ignore rdf:subject (so we // can erase the resource's own links) and rdf:object (in case there is a deleted link value that @@ -695,23 +724,23 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt resourceSmartIri = eraseResourceV2.resourceIri.toSmartIri _ <- throwIfEntityIsUsed( - entityIri = resourceSmartIri, - errorFun = throw BadRequestException( - s"Resource ${eraseResourceV2.resourceIri} cannot be erased, because it is referred to by another resource" - ), - ignoreRdfSubjectAndObject = true - ) + entityIri = resourceSmartIri, + errorFun = throw BadRequestException( + s"Resource ${eraseResourceV2.resourceIri} cannot be erased, because it is referred to by another resource" + ), + ignoreRdfSubjectAndObject = true + ) // Get the IRI of the named graph from which the resource will be erased. dataNamedGraph: IRI = stringFormatter.projectDataNamedGraphV2(resource.projectADM) // Generate SPARQL for erasing the resource. sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .eraseResource( - dataNamedGraph = dataNamedGraph, - resourceIri = eraseResourceV2.resourceIri - ) - .toString() + .eraseResource( + dataNamedGraph = dataNamedGraph, + resourceIri = eraseResourceV2.resourceIri + ) + .toString() // _ = println(sparqlUpdate) @@ -723,10 +752,10 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt resourceStillExists: Boolean <- stringFormatter.checkIriExists(resourceSmartIri.toString, storeManager) _ = if (resourceStillExists) { - throw UpdateNotPerformedException( - s"Resource <${eraseResourceV2.resourceIri}> was not erased. Please report this as a possible bug." - ) - } + throw UpdateNotPerformedException( + s"Resource <${eraseResourceV2.resourceIri}> was not erased. Please report this as a possible bug." + ) + } } yield SuccessResponseV2("Resource erased") if (!eraseResourceV2.erase) { @@ -736,10 +765,10 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt for { // Do the pre-update checks and the update while holding an update lock on the resource. taskResult <- IriLocker.runWithIriLock( - eraseResourceV2.apiRequestID, - eraseResourceV2.resourceIri, - () => makeTaskFuture - ) + eraseResourceV2.apiRequestID, + eraseResourceV2.resourceIri, + () => makeTaskFuture + ) } yield taskResult } @@ -787,102 +816,106 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt .toMap _ = internalCreateResource.values.foreach { - case (propertyIri: SmartIri, valuesForProperty: Seq[CreateValueInNewResourceV2]) => - val internalPropertyIri = propertyIri.toOntologySchema(InternalSchema) - - val cardinalityInfo = knoraPropertyCardinalities.getOrElse( - internalPropertyIri, - throw OntologyConstraintException( - s"${resourceIDForErrorMsg}Resource class <${internalCreateResource.resourceClassIri - .toOntologySchema(ApiV2Complex)}> has no cardinality for property <$propertyIri>" - ) - ) + case (propertyIri: SmartIri, valuesForProperty: Seq[CreateValueInNewResourceV2]) => + val internalPropertyIri = propertyIri.toOntologySchema(InternalSchema) + + val cardinalityInfo = knoraPropertyCardinalities.getOrElse( + internalPropertyIri, + throw OntologyConstraintException( + s"${resourceIDForErrorMsg}Resource class <${internalCreateResource.resourceClassIri + .toOntologySchema(ApiV2Complex)}> has no cardinality for property <$propertyIri>" + ) + ) - if ( - (cardinalityInfo.cardinality == Cardinality.MayHaveOne || cardinalityInfo.cardinality == Cardinality.MustHaveOne) && valuesForProperty.size > 1 - ) { - throw OntologyConstraintException( - s"${resourceIDForErrorMsg}Resource class <${internalCreateResource.resourceClassIri - .toOntologySchema(ApiV2Complex)}> does not allow more than one value for property <$propertyIri>" - ) + if ( + (cardinalityInfo.cardinality == Cardinality.MayHaveOne || cardinalityInfo.cardinality == Cardinality.MustHaveOne) && valuesForProperty.size > 1 + ) { + throw OntologyConstraintException( + s"${resourceIDForErrorMsg}Resource class <${internalCreateResource.resourceClassIri + .toOntologySchema(ApiV2Complex)}> does not allow more than one value for property <$propertyIri>" + ) + } } - } // Check that no required values are missing. requiredProps: Set[SmartIri] = knoraPropertyCardinalities.filter { case (_, cardinalityInfo) => - cardinalityInfo.cardinality == Cardinality.MustHaveOne || cardinalityInfo.cardinality == Cardinality.MustHaveSome - }.keySet -- resourceClassInfo.linkProperties + cardinalityInfo.cardinality == Cardinality.MustHaveOne || cardinalityInfo.cardinality == Cardinality.MustHaveSome + }.keySet -- resourceClassInfo.linkProperties internalPropertyIris: Set[SmartIri] = internalCreateResource.values.keySet _ = if (!requiredProps.subsetOf(internalPropertyIris)) { - val missingProps = - (requiredProps -- internalPropertyIris).map(iri => s"<${iri.toOntologySchema(ApiV2Complex)}>").mkString(", ") - throw OntologyConstraintException( - s"${resourceIDForErrorMsg}Values were not submitted for the following property or properties, which are required by resource class <${internalCreateResource.resourceClassIri - .toOntologySchema(ApiV2Complex)}>: $missingProps" - ) - } + val missingProps = + (requiredProps -- internalPropertyIris) + .map(iri => s"<${iri.toOntologySchema(ApiV2Complex)}>") + .mkString(", ") + throw OntologyConstraintException( + s"${resourceIDForErrorMsg}Values were not submitted for the following property or properties, which are required by resource class <${internalCreateResource.resourceClassIri + .toOntologySchema(ApiV2Complex)}>: $missingProps" + ) + } // Check that each submitted value is consistent with the knora-base:objectClassConstraint of the property that is supposed to // point to it. _ = checkObjectClassConstraints( - values = internalCreateResource.values, - linkTargetClasses = linkTargetClasses, - entityInfo = entityInfo, - clientResourceIDs = clientResourceIDs, - resourceIDForErrorMsg = resourceIDForErrorMsg - ) + values = internalCreateResource.values, + linkTargetClasses = linkTargetClasses, + entityInfo = entityInfo, + clientResourceIDs = clientResourceIDs, + resourceIDForErrorMsg = resourceIDForErrorMsg + ) // Check that the submitted values do not contain duplicates. _ = checkForDuplicateValues( - values = internalCreateResource.values, - clientResourceIDs = clientResourceIDs, - resourceIDForErrorMsg = resourceIDForErrorMsg - ) + values = internalCreateResource.values, + clientResourceIDs = clientResourceIDs, + resourceIDForErrorMsg = resourceIDForErrorMsg + ) // Validate and reformat any custom permissions in the request, and set all permissions to defaults if custom // permissions are not provided. resourcePermissions: String <- internalCreateResource.permissions match { - case Some(permissionStr) => - for { - validatedCustomPermissions: String <- PermissionUtilADM.validatePermissions( - permissionLiteral = permissionStr, - featureFactoryConfig = featureFactoryConfig, - responderManager = responderManager - ) - - // Is the requesting user a system admin, or an admin of this project? - _ = if ( - !(requestingUser.permissions.isProjectAdmin( - internalCreateResource.projectADM.id - ) || requestingUser.permissions.isSystemAdmin) - ) { - - // No. Make sure they don't give themselves higher permissions than they would get from the default permissions. - - val permissionComparisonResult: PermissionComparisonResult = PermissionUtilADM.comparePermissionsADM( - entityCreator = requestingUser.id, - entityProject = internalCreateResource.projectADM.id, - permissionLiteralA = validatedCustomPermissions, - permissionLiteralB = defaultResourcePermissions, - requestingUser = requestingUser - ) - - if (permissionComparisonResult == AGreaterThanB) { - throw ForbiddenException( - s"${resourceIDForErrorMsg}The specified permissions would give the resource's creator a higher permission on the resource than the default permissions" - ) - } - } - } yield validatedCustomPermissions - - case None => FastFuture.successful(defaultResourcePermissions) - } + case Some(permissionStr) => + for { + validatedCustomPermissions: String <- PermissionUtilADM.validatePermissions( + permissionLiteral = permissionStr, + featureFactoryConfig = + featureFactoryConfig, + responderManager = responderManager + ) + + // Is the requesting user a system admin, or an admin of this project? + _ = if ( + !(requestingUser.permissions.isProjectAdmin( + internalCreateResource.projectADM.id + ) || requestingUser.permissions.isSystemAdmin) + ) { + + // No. Make sure they don't give themselves higher permissions than they would get from the default permissions. + + val permissionComparisonResult: PermissionComparisonResult = + PermissionUtilADM.comparePermissionsADM( + entityCreator = requestingUser.id, + entityProject = internalCreateResource.projectADM.id, + permissionLiteralA = validatedCustomPermissions, + permissionLiteralB = defaultResourcePermissions, + requestingUser = requestingUser + ) + + if (permissionComparisonResult == AGreaterThanB) { + throw ForbiddenException( + s"${resourceIDForErrorMsg}The specified permissions would give the resource's creator a higher permission on the resource than the default permissions" + ) + } + } + } yield validatedCustomPermissions + + case None => FastFuture.successful(defaultResourcePermissions) + } valuesWithValidatedPermissions: Map[SmartIri, Seq[GenerateSparqlForValueInNewResourceV2]] <- validateAndFormatValuePermissions( @@ -895,13 +928,14 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt ) // Ask the values responder for SPARQL for generating the values. - sparqlForValuesResponse: GenerateSparqlToCreateMultipleValuesResponseV2 <- (responderManager ? - GenerateSparqlToCreateMultipleValuesRequestV2( - resourceIri = resourceIri, - values = valuesWithValidatedPermissions, - creationDate = creationDate, - requestingUser = requestingUser - )).mapTo[GenerateSparqlToCreateMultipleValuesResponseV2] + sparqlForValuesResponse: GenerateSparqlToCreateMultipleValuesResponseV2 <- + (responderManager ? + GenerateSparqlToCreateMultipleValuesRequestV2( + resourceIri = resourceIri, + values = valuesWithValidatedPermissions, + creationDate = creationDate, + requestingUser = requestingUser + )).mapTo[GenerateSparqlToCreateMultipleValuesResponseV2] } yield ResourceReadyToCreate( sparqlTemplateResourceToCreate = SparqlTemplateResourceToCreate( resourceIri = resourceIri, @@ -958,16 +992,17 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt for { // Get information about the existing resources that are targets of links. existingTargets: ReadResourcesSequenceV2 <- getResourcePreviewV2( - resourceIris = existingTargetIris.toSeq, - targetSchema = ApiV2Complex, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + resourceIris = existingTargetIris.toSeq, + targetSchema = ApiV2Complex, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) // Make a map of the IRIs of existing target resources to their class IRIs. - classesOfExistingTargets: Map[IRI, SmartIri] = existingTargets.resources - .map(resource => resource.resourceIri -> resource.resourceClassIri) - .toMap + classesOfExistingTargets: Map[IRI, SmartIri] = + existingTargets.resources + .map(resource => resource.resourceIri -> resource.resourceClassIri) + .toMap } yield classesOfNewTargets ++ classesOfExistingTargets } @@ -990,7 +1025,7 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt for (valueCombination: Seq[CreateValueInNewResourceV2] <- valueCombinations) { // valueCombination must have two elements. - val firstValue: ValueContentV2 = valueCombination.head.valueContent + val firstValue: ValueContentV2 = valueCombination.head.valueContent val secondValue: ValueContentV2 = valueCombination(1).valueContent if (firstValue.wouldDuplicateOtherValue(secondValue)) { @@ -1064,7 +1099,7 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt // Does the resource that's the target of the link belongs to a subclass of the // link property's object class constraint? - val linkTargetClass = linkTargetClasses(linkValueContentV2.referredResourceIri) + val linkTargetClass = linkTargetClasses(linkValueContentV2.referredResourceIri) val linkTargetClassInfo = entityInfo.classInfoMap(linkTargetClass) if (!linkTargetClassInfo.allBaseClasses.contains(objectClassConstraint)) { @@ -1185,33 +1220,35 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt // Yes. Validate and reformat them. for { validatedCustomPermissions <- PermissionUtilADM.validatePermissions( - permissionLiteral = permissionStr, - featureFactoryConfig = featureFactoryConfig, - responderManager = responderManager - ) + permissionLiteral = permissionStr, + featureFactoryConfig = featureFactoryConfig, + responderManager = responderManager + ) // Is the requesting user a system admin, or an admin of this project? - _ = if ( - !(requestingUser.permissions.isProjectAdmin(project.id) || requestingUser.permissions.isSystemAdmin) - ) { - - // No. Make sure they don't give themselves higher permissions than they would get from the default permissions. - - val permissionComparisonResult: PermissionComparisonResult = - PermissionUtilADM.comparePermissionsADM( - entityCreator = requestingUser.id, - entityProject = project.id, - permissionLiteralA = validatedCustomPermissions, - permissionLiteralB = defaultPropertyPermissions(propertyIri), - requestingUser = requestingUser - ) + _ = + if ( + !(requestingUser.permissions + .isProjectAdmin(project.id) || requestingUser.permissions.isSystemAdmin) + ) { + + // No. Make sure they don't give themselves higher permissions than they would get from the default permissions. + + val permissionComparisonResult: PermissionComparisonResult = + PermissionUtilADM.comparePermissionsADM( + entityCreator = requestingUser.id, + entityProject = project.id, + permissionLiteralA = validatedCustomPermissions, + permissionLiteralB = defaultPropertyPermissions(propertyIri), + requestingUser = requestingUser + ) - if (permissionComparisonResult == AGreaterThanB) { - throw ForbiddenException( - s"${resourceIDForErrorMsg}The specified value permissions would give a value's creator a higher permission on the value than the default permissions" - ) + if (permissionComparisonResult == AGreaterThanB) { + throw ForbiddenException( + s"${resourceIDForErrorMsg}The specified value permissions would give a value's creator a higher permission on the value than the default permissions" + ) + } } - } } yield GenerateSparqlForValueInNewResourceV2( valueContent = valueToCreate.valueContent, customValueIri = valueToCreate.customValueIri, @@ -1319,85 +1356,84 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt val resourceFuture: Future[ReadResourcesSequenceV2] = for { resourcesResponse: ReadResourcesSequenceV2 <- getResourcesV2( - resourceIris = Seq(resourceIri), - requestingUser = requestingUser, - targetSchema = ApiV2Complex, - featureFactoryConfig = featureFactoryConfig, - schemaOptions = SchemaOptions.ForStandoffWithTextValues - ) + resourceIris = Seq(resourceIri), + requestingUser = requestingUser, + targetSchema = ApiV2Complex, + featureFactoryConfig = featureFactoryConfig, + schemaOptions = SchemaOptions.ForStandoffWithTextValues + ) resource: ReadResourceV2 = resourcesResponse.toResource(requestedResourceIri = resourceIri) _ = if ( - resource.resourceClassIri.toString != resourceReadyToCreate.sparqlTemplateResourceToCreate.resourceClassIri - ) { - throw AssertionException(s"Resource <$resourceIri> was saved, but it has the wrong resource class") - } + resource.resourceClassIri.toString != resourceReadyToCreate.sparqlTemplateResourceToCreate.resourceClassIri + ) { + throw AssertionException(s"Resource <$resourceIri> was saved, but it has the wrong resource class") + } _ = if (resource.attachedToUser != requestingUser.id) { - throw AssertionException(s"Resource <$resourceIri> was saved, but it is attached to the wrong user") - } + throw AssertionException(s"Resource <$resourceIri> was saved, but it is attached to the wrong user") + } _ = if (resource.projectADM.id != projectIri) { - throw AssertionException(s"Resource <$resourceIri> was saved, but it is attached to the wrong user") - } + throw AssertionException(s"Resource <$resourceIri> was saved, but it is attached to the wrong user") + } _ = if (resource.permissions != resourceReadyToCreate.sparqlTemplateResourceToCreate.permissions) { - throw AssertionException(s"Resource <$resourceIri> was saved, but it has the wrong permissions") - } + throw AssertionException(s"Resource <$resourceIri> was saved, but it has the wrong permissions") + } // Undo any escapes in the submitted rdfs:label to compare it with the saved one. unescapedLabel: String = stringFormatter.fromSparqlEncodedString( - resourceReadyToCreate.sparqlTemplateResourceToCreate.resourceLabel - ) + resourceReadyToCreate.sparqlTemplateResourceToCreate.resourceLabel + ) _ = if (resource.label != unescapedLabel) { - throw AssertionException(s"Resource <$resourceIri> was saved, but it has the wrong label") - } + throw AssertionException(s"Resource <$resourceIri> was saved, but it has the wrong label") + } savedPropertyIris: Set[SmartIri] = resource.values.keySet // Check that the property knora-base:hasStandoffLinkToValue was automatically added if necessary. - expectedPropertyIris: Set[SmartIri] = resourceReadyToCreate.values.keySet ++ (if ( - resourceReadyToCreate.hasStandoffLink - ) { - Some( - OntologyConstants.KnoraBase.HasStandoffLinkToValue.toSmartIri - ) - } else { - None - }) + expectedPropertyIris: Set[SmartIri] = + resourceReadyToCreate.values.keySet ++ (if (resourceReadyToCreate.hasStandoffLink) { + Some( + OntologyConstants.KnoraBase.HasStandoffLinkToValue.toSmartIri + ) + } else { + None + }) _ = if (savedPropertyIris != expectedPropertyIris) { - throw AssertionException( - s"Resource <$resourceIri> was saved, but it has the wrong properties: expected (${expectedPropertyIris - .map(_.toSparql) - .mkString(", ")}), but saved (${savedPropertyIris.map(_.toSparql).mkString(", ")})" - ) - } + throw AssertionException( + s"Resource <$resourceIri> was saved, but it has the wrong properties: expected (${expectedPropertyIris + .map(_.toSparql) + .mkString(", ")}), but saved (${savedPropertyIris.map(_.toSparql).mkString(", ")})" + ) + } // Ignore knora-base:hasStandoffLinkToValue when checking the expected values. _ = (resource.values - OntologyConstants.KnoraBase.HasStandoffLinkToValue.toSmartIri).foreach { - case (propertyIri: SmartIri, savedValues: Seq[ReadValueV2]) => - val expectedValues: Seq[UnverifiedValueV2] = resourceReadyToCreate.values(propertyIri) + case (propertyIri: SmartIri, savedValues: Seq[ReadValueV2]) => + val expectedValues: Seq[UnverifiedValueV2] = resourceReadyToCreate.values(propertyIri) - if (expectedValues.size != savedValues.size) { - throw AssertionException(s"Resource <$resourceIri> was saved, but it has the wrong values") - } + if (expectedValues.size != savedValues.size) { + throw AssertionException(s"Resource <$resourceIri> was saved, but it has the wrong values") + } - savedValues.zip(expectedValues).foreach { case (savedValue, expectedValue) => - if ( - !(expectedValue.valueContent.wouldDuplicateCurrentVersion(savedValue.valueContent) && - savedValue.permissions == expectedValue.permissions && - savedValue.attachedToUser == requestingUser.id) - ) { - // println(s"========== Expected ==========\n${MessageUtil.toSource(expectedValue.valueContent)}\n========== Saved ==========\n${MessageUtil.toSource(savedValue.valueContent)}") - throw AssertionException( - s"Resource <$resourceIri> was saved, but one or more of its values are not correct" - ) - } + savedValues.zip(expectedValues).foreach { case (savedValue, expectedValue) => + if ( + !(expectedValue.valueContent.wouldDuplicateCurrentVersion(savedValue.valueContent) && + savedValue.permissions == expectedValue.permissions && + savedValue.attachedToUser == requestingUser.id) + ) { + // println(s"========== Expected ==========\n${MessageUtil.toSource(expectedValue.valueContent)}\n========== Saved ==========\n${MessageUtil.toSource(savedValue.valueContent)}") + throw AssertionException( + s"Resource <$resourceIri> was saved, but one or more of its values are not correct" + ) + } + } } - } } yield ReadResourcesSequenceV2( resources = Seq(resource.copy(values = Map.empty)) ) @@ -1480,33 +1516,34 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt for { resourceRequestSparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .getResourcePropertiesAndValues( - resourceIris = resourceIrisDistinct, - preview = preview, - withDeleted = withDeleted, - maybePropertyIri = propertyIri, - maybeValueUuid = valueUuid, - maybeVersionDate = versionDate, - queryAllNonStandoff = true, - maybeStandoffMinStartIndex = maybeStandoffMinStartIndex, - maybeStandoffMaxStartIndex = maybeStandoffMaxStartIndex, - stringFormatter = stringFormatter - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v2.txt + .getResourcePropertiesAndValues( + resourceIris = resourceIrisDistinct, + preview = preview, + withDeleted = withDeleted, + maybePropertyIri = propertyIri, + maybeValueUuid = valueUuid, + maybeVersionDate = versionDate, + queryAllNonStandoff = true, + maybeStandoffMinStartIndex = maybeStandoffMinStartIndex, + maybeStandoffMaxStartIndex = maybeStandoffMaxStartIndex, + stringFormatter = stringFormatter + ) + .toString() + ) resourceRequestResponse: SparqlExtendedConstructResponse <- (storeManager ? SparqlExtendedConstructRequest( - sparql = resourceRequestSparql, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + sparql = resourceRequestSparql, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse] // separate resources and values - mainResourcesAndValueRdfData: ConstructResponseUtilV2.MainResourcesAndValueRdfData = ConstructResponseUtilV2 - .splitMainResourcesAndValueRdfData( - constructQueryResults = resourceRequestResponse, - requestingUser = requestingUser - ) + mainResourcesAndValueRdfData: ConstructResponseUtilV2.MainResourcesAndValueRdfData = + ConstructResponseUtilV2 + .splitMainResourcesAndValueRdfData( + constructQueryResults = resourceRequestResponse, + requestingUser = requestingUser + ) } yield mainResourcesAndValueRdfData } @@ -1548,16 +1585,20 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt for { mainResourcesAndValueRdfData: ConstructResponseUtilV2.MainResourcesAndValueRdfData <- getResourcesFromTriplestore( - resourceIris = resourceIris, - preview = false, - withDeleted = withDeleted, - propertyIri = propertyIri, - valueUuid = valueUuid, - versionDate = versionDate, - queryStandoff = queryStandoff, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + resourceIris = + resourceIris, + preview = false, + withDeleted = withDeleted, + propertyIri = propertyIri, + valueUuid = valueUuid, + versionDate = versionDate, + queryStandoff = + queryStandoff, + featureFactoryConfig = + featureFactoryConfig, + requestingUser = + requestingUser + ) // If we're querying standoff, get XML-to standoff mappings. mappingsAsMap: Map[IRI, MappingAndXSLTransformation] <- @@ -1572,57 +1613,61 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt } apiResponse: ReadResourcesSequenceV2 <- ConstructResponseUtilV2.createApiResponse( - mainResourcesAndValueRdfData = mainResourcesAndValueRdfData, - orderByResourceIri = resourceIrisDistinct, - pageSizeBeforeFiltering = resourceIris.size, // doesn't matter because we're not doing paging - mappings = mappingsAsMap, - queryStandoff = queryStandoff, - versionDate = versionDate, - calculateMayHaveMoreResults = false, - responderManager = responderManager, - targetSchema = targetSchema, - settings = settings, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + mainResourcesAndValueRdfData = mainResourcesAndValueRdfData, + orderByResourceIri = resourceIrisDistinct, + pageSizeBeforeFiltering = + resourceIris.size, // doesn't matter because we're not doing paging + mappings = mappingsAsMap, + queryStandoff = queryStandoff, + versionDate = versionDate, + calculateMayHaveMoreResults = false, + responderManager = responderManager, + targetSchema = targetSchema, + settings = settings, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) _ = apiResponse.checkResourceIris( - targetResourceIris = resourceIris.toSet, - resourcesSequence = apiResponse - ) + targetResourceIris = resourceIris.toSet, + resourcesSequence = apiResponse + ) _ = valueUuid match { - case Some(definedValueUuid) => - if (!apiResponse.resources.exists(_.values.values.exists(_.exists(_.valueHasUUID == definedValueUuid)))) { - throw NotFoundException( - s"Value with UUID ${stringFormatter.base64EncodeUuid(definedValueUuid)} not found (maybe you do not have permission to see it)" - ) - } + case Some(definedValueUuid) => + if (!apiResponse.resources.exists(_.values.values.exists(_.exists(_.valueHasUUID == definedValueUuid)))) { + throw NotFoundException( + s"Value with UUID ${stringFormatter.base64EncodeUuid(definedValueUuid)} not found (maybe you do not have permission to see it)" + ) + } - case None => () - } + case None => () + } // Check if resources are deleted, if so, replace them with DeletedResource responseWithDeletedResourcesReplaced = apiResponse.resources match { - case resourceList => - if (resourceList.nonEmpty) { - val resourceListWithDeletedResourcesReplaced = resourceList.map { resource => - resource.deletionInfo match { - // Resource deleted -> return DeletedResource instead - case Some(_) => resource.asDeletedResource() - // Resource not deleted -> return resource - case None => - // deleted values should be shown -> resource can be returned - if (showDeletedValues) resource - // deleted Values should not be shown -> replace them with generic DeletedValue - else resource.withDeletedValues() - } - } - apiResponse.copy(resources = resourceListWithDeletedResourcesReplaced) - } else { - apiResponse - } - } + case resourceList => + if (resourceList.nonEmpty) { + val resourceListWithDeletedResourcesReplaced = resourceList.map { + resource => + resource.deletionInfo match { + // Resource deleted -> return DeletedResource instead + case Some(_) => resource.asDeletedResource() + // Resource not deleted -> return resource + case None => + // deleted values should be shown -> resource can be returned + if (showDeletedValues) resource + // deleted Values should not be shown -> replace them with generic DeletedValue + else resource.withDeletedValues() + } + } + apiResponse.copy(resources = + resourceListWithDeletedResourcesReplaced + ) + } else { + apiResponse + } + } } yield responseWithDeletedResourcesReplaced @@ -1650,49 +1695,57 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt for { mainResourcesAndValueRdfData: ConstructResponseUtilV2.MainResourcesAndValueRdfData <- getResourcesFromTriplestore( - resourceIris = resourceIris, - preview = true, - withDeleted = withDeleted, - queryStandoff = false, // This has no effect, because we are not querying values. - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + resourceIris = + resourceIris, + preview = true, + withDeleted = withDeleted, + queryStandoff = + false, // This has no effect, because we are not querying values. + featureFactoryConfig = + featureFactoryConfig, + requestingUser = + requestingUser + ) apiResponse: ReadResourcesSequenceV2 <- ConstructResponseUtilV2.createApiResponse( - mainResourcesAndValueRdfData = mainResourcesAndValueRdfData, - orderByResourceIri = resourceIrisDistinct, - pageSizeBeforeFiltering = resourceIris.size, // doesn't matter because we're not doing paging - mappings = Map.empty[IRI, MappingAndXSLTransformation], - queryStandoff = false, - versionDate = None, - calculateMayHaveMoreResults = false, - responderManager = responderManager, - targetSchema = targetSchema, - settings = settings, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + mainResourcesAndValueRdfData = mainResourcesAndValueRdfData, + orderByResourceIri = resourceIrisDistinct, + pageSizeBeforeFiltering = + resourceIris.size, // doesn't matter because we're not doing paging + mappings = Map.empty[IRI, MappingAndXSLTransformation], + queryStandoff = false, + versionDate = None, + calculateMayHaveMoreResults = false, + responderManager = responderManager, + targetSchema = targetSchema, + settings = settings, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) _ = apiResponse.checkResourceIris( - targetResourceIris = resourceIris.toSet, - resourcesSequence = apiResponse - ) + targetResourceIris = resourceIris.toSet, + resourcesSequence = apiResponse + ) // Check if resources are deleted, if so, replace them with DeletedResource responseWithDeletedResourcesReplaced = apiResponse.resources match { - case resourceList => - if (resourceList.nonEmpty) { - val resourceListWithDeletedResourcesReplaced = resourceList.map { resource => - resource.deletionInfo match { - case Some(_) => resource.asDeletedResource() - case None => resource.withDeletedValues() - } - } - apiResponse.copy(resources = resourceListWithDeletedResourcesReplaced) - } else { - apiResponse - } - } + case resourceList => + if (resourceList.nonEmpty) { + val resourceListWithDeletedResourcesReplaced = resourceList.map { + resource => + resource.deletionInfo match { + case Some(_) => resource.asDeletedResource() + case None => resource.withDeletedValues() + } + } + apiResponse.copy(resources = + resourceListWithDeletedResourcesReplaced + ) + } else { + apiResponse + } + } } yield responseWithDeletedResourcesReplaced } @@ -1713,46 +1766,49 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt val gravsearchUrlFuture = for { resources: ReadResourcesSequenceV2 <- getResourcesV2( - resourceIris = Vector(gravsearchTemplateIri), - targetSchema = ApiV2Complex, - schemaOptions = Set(MarkupAsStandoff), - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + resourceIris = Vector(gravsearchTemplateIri), + targetSchema = ApiV2Complex, + schemaOptions = Set(MarkupAsStandoff), + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) resource: ReadResourceV2 = resources.toResource(gravsearchTemplateIri) _ = if (resource.resourceClassIri.toString != OntologyConstants.KnoraBase.TextRepresentation) { - throw BadRequestException(s"Resource $gravsearchTemplateIri is not a Gravsearch template (text file expected)") - } - - (fileValueIri: IRI, gravsearchFileValueContent: TextFileValueContentV2) = resource.values.get( - OntologyConstants.KnoraBase.HasTextFileValue.toSmartIri - ) match { - case Some(values: Seq[ReadValueV2]) if values.size == 1 => - values.head match { - case value: ReadValueV2 => - value.valueContent match { - case textRepr: TextFileValueContentV2 => (value.valueIri, textRepr) - case _ => - throw InconsistentRepositoryDataException( - s"Resource $gravsearchTemplateIri is supposed to have exactly one value of type ${OntologyConstants.KnoraBase.TextFileValue}" - ) - } + throw BadRequestException( + s"Resource $gravsearchTemplateIri is not a Gravsearch template (text file expected)" + ) } - case _ => - throw InconsistentRepositoryDataException( - s"Resource $gravsearchTemplateIri has no property ${OntologyConstants.KnoraBase.HasTextFileValue}" - ) - } + (fileValueIri: IRI, gravsearchFileValueContent: TextFileValueContentV2) = + resource.values.get( + OntologyConstants.KnoraBase.HasTextFileValue.toSmartIri + ) match { + case Some(values: Seq[ReadValueV2]) if values.size == 1 => + values.head match { + case value: ReadValueV2 => + value.valueContent match { + case textRepr: TextFileValueContentV2 => (value.valueIri, textRepr) + case _ => + throw InconsistentRepositoryDataException( + s"Resource $gravsearchTemplateIri is supposed to have exactly one value of type ${OntologyConstants.KnoraBase.TextFileValue}" + ) + } + } + + case _ => + throw InconsistentRepositoryDataException( + s"Resource $gravsearchTemplateIri has no property ${OntologyConstants.KnoraBase.HasTextFileValue}" + ) + } // check if gravsearchFileValueContent represents a text file _ = if (gravsearchFileValueContent.fileValue.internalMimeType != "text/plain") { - throw BadRequestException( - s"Expected $fileValueIri to be a text file referring to a Gravsearch template, but it has MIME type ${gravsearchFileValueContent.fileValue.internalMimeType}" - ) - } + throw BadRequestException( + s"Expected $fileValueIri to be a text file referring to a Gravsearch template, but it has MIME type ${gravsearchFileValueContent.fileValue.internalMimeType}" + ) + } gravsearchUrl: String = s"${settings.internalSipiBaseUrl}/${resource.projectADM.shortcode}/${gravsearchFileValueContent.fileValue.internalFilename}/file" @@ -1765,10 +1821,10 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt for { gravsearchTemplateUrl <- recoveredGravsearchUrlFuture response: SipiGetTextFileResponse <- (storeManager ? SipiGetTextFileRequest( - fileUrl = gravsearchTemplateUrl, - requestingUser = KnoraSystemInstances.Users.SystemUser, - senderName = this.getClass.getName - )).mapTo[SipiGetTextFileResponse] + fileUrl = gravsearchTemplateUrl, + requestingUser = KnoraSystemInstances.Users.SystemUser, + senderName = this.getClass.getName + )).mapTo[SipiGetTextFileResponse] gravsearchTemplate: String = response.content } yield gravsearchTemplate @@ -1884,10 +1940,10 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt for { // get the template template <- getGravsearchTemplate( - gravsearchTemplateIri = gravsearchTemplateIri.get, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + gravsearchTemplateIri = gravsearchTemplateIri.get, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) // insert actual resource Iri, replacing the placeholder gravsearchQuery = template.replace("$resourceIri", resourceIri) @@ -1897,12 +1953,12 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt // do a request to the SearchResponder gravSearchResponse: ReadResourcesSequenceV2 <- (responderManager ? GravsearchRequestV2( - constructQuery = constructQuery, - targetSchema = ApiV2Complex, - schemaOptions = SchemaOptions.ForStandoffWithTextValues, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - )).mapTo[ReadResourcesSequenceV2] + constructQuery = constructQuery, + targetSchema = ApiV2Complex, + schemaOptions = SchemaOptions.ForStandoffWithTextValues, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + )).mapTo[ReadResourcesSequenceV2] } yield gravSearchResponse.toResource(resourceIri) } else { @@ -1917,12 +1973,12 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt for { // get requested resource resource <- getResourcesV2( - resourceIris = Vector(resourceIri), - targetSchema = ApiV2Complex, - schemaOptions = SchemaOptions.ForStandoffWithTextValues, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ).map(_.toResource(resourceIri)) + resourceIris = Vector(resourceIri), + targetSchema = ApiV2Complex, + schemaOptions = SchemaOptions.ForStandoffWithTextValues, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ).map(_.toResource(resourceIri)) } yield resource } @@ -1931,108 +1987,115 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt // the ext value is expected to have standoff markup _ = if (bodyTextValue.standoff.isEmpty) - throw BadRequestException(s"Property $textProperty of $resourceIri is expected to have standoff markup") + throw BadRequestException(s"Property $textProperty of $resourceIri is expected to have standoff markup") // get all the metadata but the text property for the TEI header headerResource = resource.copy( - values = convertDateToGregorian(resource.values - textProperty) - ) + values = convertDateToGregorian(resource.values - textProperty) + ) // get the XSL transformation for the TEI header headerXSLT: Option[String] <- headerXSLTIri match { - case Some(headerIri) => - val teiHeaderXsltRequest = GetXSLTransformationRequestV2( - xsltTextRepresentationIri = headerIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + case Some(headerIri) => + val teiHeaderXsltRequest = GetXSLTransformationRequestV2( + xsltTextRepresentationIri = headerIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) - val xslTransformationFuture = for { - xslTransformation: GetXSLTransformationResponseV2 <- (responderManager ? teiHeaderXsltRequest) - .mapTo[GetXSLTransformationResponseV2] - } yield Some(xslTransformation.xslt) + val xslTransformationFuture = for { + xslTransformation: GetXSLTransformationResponseV2 <- + (responderManager ? teiHeaderXsltRequest) + .mapTo[GetXSLTransformationResponseV2] + } yield Some(xslTransformation.xslt) - xslTransformationFuture.recover { - case notFound: NotFoundException => - throw SipiException(s"TEI header XSL transformation <$headerIri> not found: ${notFound.message}") + xslTransformationFuture.recover { + case notFound: NotFoundException => + throw SipiException( + s"TEI header XSL transformation <$headerIri> not found: ${notFound.message}" + ) - case other => throw other - } + case other => throw other + } - case None => Future(None) - } + case None => Future(None) + } // get the Iri of the mapping to convert standoff markup to TEI/XML mappingToBeApplied = mappingIri match { - case Some(mapping: IRI) => - // a custom mapping is provided - mapping + case Some(mapping: IRI) => + // a custom mapping is provided + mapping - case None => - // no mapping is provided, assume the standard case (standard standoff entites only) - OntologyConstants.KnoraBase.TEIMapping - } + case None => + // no mapping is provided, assume the standard case (standard standoff entites only) + OntologyConstants.KnoraBase.TEIMapping + } // get mapping to convert standoff markup to TEI/XML teiMapping: GetMappingResponseV2 <- (responderManager ? GetMappingRequestV2( - mappingIri = mappingToBeApplied, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - )).mapTo[GetMappingResponseV2] + mappingIri = mappingToBeApplied, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + )).mapTo[GetMappingResponseV2] // get XSLT from mapping for the TEI body bodyXslt: String <- teiMapping.mappingIri match { - case OntologyConstants.KnoraBase.TEIMapping => - // standard standoff to TEI conversion + case OntologyConstants.KnoraBase.TEIMapping => + // standard standoff to TEI conversion - // use standard XSLT (built-in) - val teiXSLTFile: String = FileUtil.readTextResource("standoffToTEI.xsl") + // use standard XSLT (built-in) + val teiXSLTFile: String = FileUtil.readTextResource("standoffToTEI.xsl") - // return the file's content - Future(teiXSLTFile) + // return the file's content + Future(teiXSLTFile) - case otherMapping => - teiMapping.mapping.defaultXSLTransformation match { - // custom standoff to TEI conversion + case otherMapping => + teiMapping.mapping.defaultXSLTransformation match { + // custom standoff to TEI conversion - case Some(xslTransformationIri) => - // get XSLT for the TEI body. - val teiBodyXsltRequest = GetXSLTransformationRequestV2( - xsltTextRepresentationIri = xslTransformationIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + case Some(xslTransformationIri) => + // get XSLT for the TEI body. + val teiBodyXsltRequest = GetXSLTransformationRequestV2( + xsltTextRepresentationIri = xslTransformationIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) - val xslTransformationFuture = for { - xslTransformation: GetXSLTransformationResponseV2 <- (responderManager ? teiBodyXsltRequest) - .mapTo[GetXSLTransformationResponseV2] - } yield xslTransformation.xslt + val xslTransformationFuture = for { + xslTransformation: GetXSLTransformationResponseV2 <- + (responderManager ? teiBodyXsltRequest) + .mapTo[GetXSLTransformationResponseV2] + } yield xslTransformation.xslt - xslTransformationFuture.recover { - case notFound: NotFoundException => - throw SipiException( - s"Default XSL transformation <${teiMapping.mapping.defaultXSLTransformation.get}> not found for mapping <${teiMapping.mappingIri}>: ${notFound.message}" - ) + xslTransformationFuture.recover { + case notFound: NotFoundException => + throw SipiException( + s"Default XSL transformation <${teiMapping.mapping.defaultXSLTransformation.get}> not found for mapping <${teiMapping.mappingIri}>: ${notFound.message}" + ) - case other => throw other - } - case None => throw BadRequestException(s"Default XSL Transformation expected for mapping $otherMapping") - } - } + case other => throw other + } + case None => + throw BadRequestException( + s"Default XSL Transformation expected for mapping $otherMapping" + ) + } + } tei = ResourceTEIGetResponseV2( - header = TEIHeader( - headerInfo = headerResource, - headerXSLT = headerXSLT, - featureFactoryConfig = featureFactoryConfig, - settings = settings - ), - body = TEIBody( - bodyInfo = bodyTextValue, - bodyXSLT = bodyXslt, - teiMapping = teiMapping.mapping - ) - ) + header = TEIHeader( + headerInfo = headerResource, + headerXSLT = headerXSLT, + featureFactoryConfig = featureFactoryConfig, + settings = settings + ), + body = TEIBody( + bodyInfo = bodyTextValue, + bodyXSLT = bodyXslt, + teiMapping = teiMapping.mapping + ) + ) } yield tei } @@ -2118,16 +2181,16 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt for { // Get the direct links from/to the start node. sparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .getGraphData( - startNodeIri = startNode.nodeIri, - startNodeOnly = false, - maybeExcludeLinkProperty = excludePropertyInternal, - outbound = outbound, // true to query outbound edges, false to query inbound edges - limit = settings.maxGraphBreadth - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v2.txt + .getGraphData( + startNodeIri = startNode.nodeIri, + startNodeOnly = false, + maybeExcludeLinkProperty = excludePropertyInternal, + outbound = outbound, // true to query outbound edges, false to query inbound edges + limit = settings.maxGraphBreadth + ) + .toString() + ) // _ = println(sparql) @@ -2170,7 +2233,7 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt // Get the edges from the query results. val edges: Set[QueryResultEdge] = rows.map { row: VariableResultsRow => val rowMap: Map[String, String] = row.rowMap - val nodeIri: IRI = rowMap("node") + val nodeIri: IRI = rowMap("node") // The SPARQL query takes a start node and returns the other node in the edge. // @@ -2259,16 +2322,16 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt for { // Get the start node. sparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .getGraphData( - startNodeIri = graphDataGetRequest.resourceIri, - maybeExcludeLinkProperty = excludePropertyInternal, - startNodeOnly = true, - outbound = true, - limit = settings.maxGraphBreadth - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v2.txt + .getGraphData( + startNodeIri = graphDataGetRequest.resourceIri, + maybeExcludeLinkProperty = excludePropertyInternal, + startNodeOnly = true, + outbound = true, + limit = settings.maxGraphBreadth + ) + .toString() + ) // _ = println(sparql) @@ -2276,35 +2339,37 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt rows: Seq[VariableResultsRow] = response.results.bindings _ = if (rows.isEmpty) { - throw NotFoundException(s"Resource <${graphDataGetRequest.resourceIri}> not found (it may have been deleted)") - } + throw NotFoundException( + s"Resource <${graphDataGetRequest.resourceIri}> not found (it may have been deleted)" + ) + } firstRowMap: Map[String, String] = rows.head.rowMap startNode: QueryResultNode = QueryResultNode( - nodeIri = firstRowMap("node"), - nodeClass = firstRowMap("nodeClass").toSmartIri, - nodeLabel = firstRowMap("nodeLabel"), - nodeCreator = firstRowMap("nodeCreator"), - nodeProject = firstRowMap("nodeProject"), - nodePermissions = firstRowMap("nodePermissions") - ) + nodeIri = firstRowMap("node"), + nodeClass = firstRowMap("nodeClass").toSmartIri, + 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 - .getUserPermissionADM( - entityCreator = startNode.nodeCreator, - entityProject = startNode.nodeProject, - entityPermissionLiteral = startNode.nodePermissions, - requestingUser = graphDataGetRequest.requestingUser - ) - .isEmpty - ) { - throw ForbiddenException( - s"User ${graphDataGetRequest.requestingUser.email} does not have permission to view resource <${graphDataGetRequest.resourceIri}>" - ) - } + PermissionUtilADM + .getUserPermissionADM( + entityCreator = startNode.nodeCreator, + entityProject = startNode.nodeProject, + entityPermissionLiteral = startNode.nodePermissions, + requestingUser = graphDataGetRequest.requestingUser + ) + .isEmpty + ) { + throw ForbiddenException( + s"User ${graphDataGetRequest.requestingUser.email} does not have permission to view resource <${graphDataGetRequest.resourceIri}>" + ) + } // Recursively get the graph containing outbound links. outboundQueryResults: GraphQueryResults <- @@ -2336,21 +2401,21 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt // Convert each node to a GraphNodeV2 for the API response message. resultNodes: Vector[GraphNodeV2] = nodes.map { node: QueryResultNode => - GraphNodeV2( - resourceIri = node.nodeIri, - resourceClassIri = node.nodeClass, - resourceLabel = node.nodeLabel - ) - }.toVector + GraphNodeV2( + resourceIri = node.nodeIri, + resourceClassIri = node.nodeClass, + resourceLabel = node.nodeLabel + ) + }.toVector // Convert each edge to a GraphEdgeV2 for the API response message. resultEdges: Vector[GraphEdgeV2] = edges.map { edge: QueryResultEdge => - GraphEdgeV2( - source = edge.sourceNodeIri, - propertyIri = edge.linkProp, - target = edge.targetNodeIri - ) - }.toVector + GraphEdgeV2( + source = edge.sourceNodeIri, + propertyIri = edge.linkProp, + target = edge.targetNodeIri + ) + }.toVector } yield GraphDataGetResponseV2( nodes = resultNodes, @@ -2372,33 +2437,34 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt // Get the resource preview, to make sure the user has permission to see the resource, and to get // its creation date. resourcePreviewResponse: ReadResourcesSequenceV2 <- getResourcePreviewV2( - resourceIris = Seq(resourceHistoryRequest.resourceIri), - withDeleted = resourceHistoryRequest.withDeletedResource, - targetSchema = ApiV2Complex, - featureFactoryConfig = resourceHistoryRequest.featureFactoryConfig, - requestingUser = resourceHistoryRequest.requestingUser - ) + resourceIris = Seq(resourceHistoryRequest.resourceIri), + withDeleted = resourceHistoryRequest.withDeletedResource, + targetSchema = ApiV2Complex, + featureFactoryConfig = + resourceHistoryRequest.featureFactoryConfig, + requestingUser = resourceHistoryRequest.requestingUser + ) resourcePreview: ReadResourceV2 = resourcePreviewResponse.toResource(resourceHistoryRequest.resourceIri) // Get the version history of the resource's values. historyRequestSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .getResourceValueVersionHistory( - withDeletedResource = resourceHistoryRequest.withDeletedResource, - resourceIri = resourceHistoryRequest.resourceIri, - maybeStartDate = resourceHistoryRequest.startDate, - maybeEndDate = resourceHistoryRequest.endDate - ) - .toString() + .getResourceValueVersionHistory( + withDeletedResource = resourceHistoryRequest.withDeletedResource, + resourceIri = resourceHistoryRequest.resourceIri, + maybeStartDate = resourceHistoryRequest.startDate, + maybeEndDate = resourceHistoryRequest.endDate + ) + .toString() valueHistoryResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(historyRequestSparql)) - .mapTo[SparqlSelectResult] + .mapTo[SparqlSelectResult] - valueHistoryEntries: Seq[ResourceHistoryEntry] = valueHistoryResponse.results.bindings.map { - row: VariableResultsRow => + valueHistoryEntries: Seq[ResourceHistoryEntry] = + valueHistoryResponse.results.bindings.map { row: VariableResultsRow => val versionDateStr: String = row.rowMap("versionDate") - val author: IRI = row.rowMap("author") + val author: IRI = row.rowMap("author") ResourceHistoryEntry( versionDate = stringFormatter.xsdDateTimeStampToInstant( @@ -2407,7 +2473,7 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt ), author = author ) - } + } // Figure out whether to add the resource's creation to the history. @@ -2444,39 +2510,40 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt for { // Make a Gravsearch query from a template. gravsearchQueryForIncomingLinks: String <- Future( - org.knora.webapi.messages.twirl.queries.gravsearch.txt - .getIncomingImageLinks( - resourceIri = request.resourceIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.gravsearch.txt + .getIncomingImageLinks( + resourceIri = request.resourceIri + ) + .toString() + ) // Run the query. parsedGravsearchQuery <- FastFuture.successful(GravsearchParser.parseQuery(gravsearchQueryForIncomingLinks)) searchResponse <- (responderManager ? GravsearchRequestV2( - constructQuery = parsedGravsearchQuery, - targetSchema = ApiV2Complex, - schemaOptions = SchemaOptions.ForStandoffSeparateFromTextValues, - featureFactoryConfig = request.featureFactoryConfig, - requestingUser = request.requestingUser - )).mapTo[ReadResourcesSequenceV2] + constructQuery = parsedGravsearchQuery, + targetSchema = ApiV2Complex, + schemaOptions = SchemaOptions.ForStandoffSeparateFromTextValues, + featureFactoryConfig = request.featureFactoryConfig, + requestingUser = request.requestingUser + )).mapTo[ReadResourcesSequenceV2] resource: ReadResourceV2 = searchResponse.toResource(request.resourceIri) - incomingLinks: Seq[ReadValueV2] = resource.values - .getOrElse(OntologyConstants.KnoraBase.HasIncomingLinkValue.toSmartIri, Seq.empty) + incomingLinks: Seq[ReadValueV2] = + resource.values + .getOrElse(OntologyConstants.KnoraBase.HasIncomingLinkValue.toSmartIri, Seq.empty) representations: Seq[ReadResourceV2] = incomingLinks.collect { case readLinkValueV2: ReadLinkValueV2 => - readLinkValueV2.valueContent.nestedResource - }.flatten + readLinkValueV2.valueContent.nestedResource + }.flatten } yield ResourceIIIFManifestGetResponseV2( JsonLDDocument( body = JsonLDObject( Map( JsonLDKeywords.CONTEXT -> JsonLDString("http://iiif.io/api/presentation/3/context.json"), - "id" -> JsonLDString(s"${request.resourceIri}/manifest"), // Is this IRI OK? - "type" -> JsonLDString("Manifest"), + "id" -> JsonLDString(s"${request.resourceIri}/manifest"), // Is this IRI OK? + "type" -> JsonLDString("Manifest"), "label" -> JsonLDObject( Map( "en" -> JsonLDArray( @@ -2512,7 +2579,7 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt JsonLDObject( Map( - "id" -> JsonLDString(s"${representation.resourceIri}/canvas"), // Is this IRI OK? + "id" -> JsonLDString(s"${representation.resourceIri}/canvas"), // Is this IRI OK? "type" -> JsonLDString("Canvas"), "label" -> JsonLDObject( Map( @@ -2524,33 +2591,33 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt ) ), "height" -> JsonLDInt(imageValueContent.dimY), - "width" -> JsonLDInt(imageValueContent.dimX), + "width" -> JsonLDInt(imageValueContent.dimX), "items" -> JsonLDArray( Seq( JsonLDObject( Map( - "id" -> JsonLDString(s"${imageValue.valueIri}/image"), // Is this IRI OK? + "id" -> JsonLDString(s"${imageValue.valueIri}/image"), // Is this IRI OK? "type" -> JsonLDString("AnnotationPage"), "items" -> JsonLDArray( Seq( JsonLDObject( Map( - "id" -> JsonLDString(imageValue.valueIri), - "type" -> JsonLDString("Annotation"), + "id" -> JsonLDString(imageValue.valueIri), + "type" -> JsonLDString("Annotation"), "motivation" -> JsonLDString("painting"), "body" -> JsonLDObject( Map( - "id" -> JsonLDString(fileUrl), - "type" -> JsonLDString("Image"), + "id" -> JsonLDString(fileUrl), + "type" -> JsonLDString("Image"), "format" -> JsonLDString("image/jpeg"), "height" -> JsonLDInt(imageValueContent.dimY), - "width" -> JsonLDInt(imageValueContent.dimX), + "width" -> JsonLDInt(imageValueContent.dimX), "service" -> JsonLDArray( Seq( JsonLDObject( Map( - "id" -> JsonLDString(settings.externalSipiIIIFGetUrl), - "type" -> JsonLDString("ImageService3"), + "id" -> JsonLDString(settings.externalSipiIIIFGetUrl), + "type" -> JsonLDString("ImageService3"), "profile" -> JsonLDString("level1") ) ) @@ -2588,19 +2655,25 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt ): Future[ResourceAndValueVersionHistoryResponseV2] = for { resourceHistory: ResourceVersionHistoryResponseV2 <- getResourceHistoryV2( - ResourceVersionHistoryGetRequestV2( - resourceIri = resourceHistoryEventsGetRequest.resourceIri, - withDeletedResource = true, - featureFactoryConfig = resourceHistoryEventsGetRequest.featureFactoryConfig, - requestingUser = resourceHistoryEventsGetRequest.requestingUser - ) - ) + ResourceVersionHistoryGetRequestV2( + resourceIri = + resourceHistoryEventsGetRequest.resourceIri, + withDeletedResource = true, + featureFactoryConfig = + resourceHistoryEventsGetRequest.featureFactoryConfig, + requestingUser = + resourceHistoryEventsGetRequest.requestingUser + ) + ) resourceFullHist: Seq[ResourceAndValueHistoryEvent] <- extractEventsFromHistory( - resourceIri = resourceHistoryEventsGetRequest.resourceIri, - resourceHistory = resourceHistory.history, - featureFactoryConfig = resourceHistoryEventsGetRequest.featureFactoryConfig, - requestingUser = resourceHistoryEventsGetRequest.requestingUser - ) + resourceIri = + resourceHistoryEventsGetRequest.resourceIri, + resourceHistory = resourceHistory.history, + featureFactoryConfig = + resourceHistoryEventsGetRequest.featureFactoryConfig, + requestingUser = + resourceHistoryEventsGetRequest.requestingUser + ) sortedResourceHistory = resourceFullHist.sortBy(_.versionDate) } yield ResourceAndValueVersionHistoryResponseV2(historyEvents = sortedResourceHistory) @@ -2616,40 +2689,48 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt for { // Get the project; checks if a project with given IRI exists. projectInfoResponse: ProjectGetResponseADM <- (responderManager ? ProjectGetRequestADM( - identifier = ProjectIdentifierADM(maybeIri = Some(projectResourceHistoryEventsGetRequest.projectIri)), - featureFactoryConfig = projectResourceHistoryEventsGetRequest.featureFactoryConfig, - requestingUser = projectResourceHistoryEventsGetRequest.requestingUser - )).mapTo[ProjectGetResponseADM] + identifier = ProjectIdentifierADM(maybeIri = + Some(projectResourceHistoryEventsGetRequest.projectIri) + ), + featureFactoryConfig = + projectResourceHistoryEventsGetRequest.featureFactoryConfig, + requestingUser = + projectResourceHistoryEventsGetRequest.requestingUser + )).mapTo[ProjectGetResponseADM] // Do a SELECT prequery to get the IRIs of the resources that belong to the project. prequery = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .getAllResourcesInProjectPrequery( - projectIri = projectInfoResponse.project.id - ) - .toString + .getAllResourcesInProjectPrequery( + projectIri = projectInfoResponse.project.id + ) + .toString - sparqlSelectResponse <- (storeManager ? SparqlSelectRequest(prequery)).mapTo[SparqlSelectResult] + sparqlSelectResponse <- (storeManager ? SparqlSelectRequest(prequery)).mapTo[SparqlSelectResult] mainResourceIris: Seq[IRI] = sparqlSelectResponse.results.bindings.map(_.rowMap("resource")) // For each resource IRI return history events - historyOfResourcesAsSeqOfFutures: Seq[Future[Seq[ResourceAndValueHistoryEvent]]] = mainResourceIris.map { - resourceIri => + historyOfResourcesAsSeqOfFutures: Seq[Future[Seq[ResourceAndValueHistoryEvent]]] = + mainResourceIris.map { resourceIri => for { resourceHistory: ResourceVersionHistoryResponseV2 <- getResourceHistoryV2( - ResourceVersionHistoryGetRequestV2( - resourceIri = resourceIri, - withDeletedResource = true, - featureFactoryConfig = projectResourceHistoryEventsGetRequest.featureFactoryConfig, - requestingUser = projectResourceHistoryEventsGetRequest.requestingUser - ) - ) + ResourceVersionHistoryGetRequestV2( + resourceIri = resourceIri, + withDeletedResource = true, + featureFactoryConfig = + projectResourceHistoryEventsGetRequest.featureFactoryConfig, + requestingUser = + projectResourceHistoryEventsGetRequest.requestingUser + ) + ) resourceFullHist: Seq[ResourceAndValueHistoryEvent] <- extractEventsFromHistory( - resourceIri = resourceIri, - resourceHistory = resourceHistory.history, - featureFactoryConfig = projectResourceHistoryEventsGetRequest.featureFactoryConfig, - requestingUser = projectResourceHistoryEventsGetRequest.requestingUser - ) + resourceIri = resourceIri, + resourceHistory = resourceHistory.history, + featureFactoryConfig = + projectResourceHistoryEventsGetRequest.featureFactoryConfig, + requestingUser = + projectResourceHistoryEventsGetRequest.requestingUser + ) } yield resourceFullHist - } + } projectHistory: Seq[Seq[ResourceAndValueHistoryEvent]] <- Future.sequence(historyOfResourcesAsSeqOfFutures) sortedProjectHistory: Seq[ResourceAndValueHistoryEvent] = projectHistory.flatten.sortBy(_.versionDate) @@ -2675,43 +2756,46 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt resourceHist: Seq[ResourceHistoryEntry] <- Future.successful(resourceHistory.reverse) // Collect the full representations of the resource for each version date histories: Seq[Future[(ResourceHistoryEntry, ReadResourceV2)]] = resourceHist.map { hist => - getResourceAtGivenTime( - resourceIri = resourceIri, - versionHist = hist, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) - } + getResourceAtGivenTime( + resourceIri = resourceIri, + versionHist = hist, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) + } fullReps: Seq[(ResourceHistoryEntry, ReadResourceV2)] <- Future.sequence(histories) // Create an event for the resource at creation time (creationTimeHist, resourceAtCreation) = fullReps.head resourceCreationEvent: Seq[ResourceAndValueHistoryEvent] = getResourceCreationEvent( - resourceAtCreation, - creationTimeHist - ) + resourceAtCreation, + creationTimeHist + ) // If there is a version history for deletion of the event, create a delete resource event for it. (deletionRep, resourceAtValueChanges) = fullReps.tail.partition { case (resHist, resource) => - resource - .asInstanceOf[ReadResourceV2] - .deletionInfo - .exists(deletionInfo => deletionInfo.deleteDate == resHist.versionDate) - } + resource + .asInstanceOf[ReadResourceV2] + .deletionInfo + .exists(deletionInfo => + deletionInfo.deleteDate == resHist.versionDate + ) + } resourceDeleteEvent = getResourceDeletionEvents(deletionRep) // For each value version, form an event - valuesEvents: Seq[ResourceAndValueHistoryEvent] = resourceAtValueChanges.flatMap { - case (versionHist, readResource) => getValueEvents(readResource, versionHist, fullReps) - } + valuesEvents: Seq[ResourceAndValueHistoryEvent] = + resourceAtValueChanges.flatMap { case (versionHist, readResource) => + getValueEvents(readResource, versionHist, fullReps) + } // Get the update resource metadata event, if there is any. resourceMetadataUpdateEvent: Seq[ResourceAndValueHistoryEvent] = getResourceMetadataUpdateEvent( - fullReps.last, - valuesEvents, - resourceDeleteEvent - ) + fullReps.last, + valuesEvents, + resourceDeleteEvent + ) } yield resourceCreationEvent ++ resourceDeleteEvent ++ valuesEvents ++ resourceMetadataUpdateEvent @@ -2732,14 +2816,14 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt ): Future[(ResourceHistoryEntry, ReadResourceV2)] = for { resourceFullRepAtCreationTime: ReadResourcesSequenceV2 <- getResourcesV2( - resourceIris = Seq(resourceIri), - versionDate = Some(versionHist.versionDate), - showDeletedValues = true, - targetSchema = ApiV2Complex, - schemaOptions = Set.empty[SchemaOption], - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + resourceIris = Seq(resourceIri), + versionDate = Some(versionHist.versionDate), + showDeletedValues = true, + targetSchema = ApiV2Complex, + schemaOptions = Set.empty[SchemaOption], + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) resourceAtCreationTime: ReadResourceV2 = resourceFullRepAtCreationTime.resources.head } yield versionHist -> resourceAtCreationTime @@ -2994,7 +3078,7 @@ class ResourcesResponderV2(responderData: ResponderData) extends ResponderWithSt resourceDeleteEvents: Seq[ResourceAndValueHistoryEvent] ): Seq[ResourceAndValueHistoryEvent] = { val readResource: ReadResourceV2 = latestVersionOfResource._2 - val author: IRI = latestVersionOfResource._1.author + val author: IRI = latestVersionOfResource._1.author // Is lastModificationDate of resource None readResource.lastModificationDate match { // Yes. Do nothing. diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v2/ResponderWithStandoffV2.scala b/webapi/src/main/scala/org/knora/webapi/responders/v2/ResponderWithStandoffV2.scala index 8a728d24a6..5d950b56c8 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/v2/ResponderWithStandoffV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v2/ResponderWithStandoffV2.scala @@ -51,10 +51,10 @@ abstract class ResponderWithStandoffV2(responderData: ResponderData) extends Res val mappingResponsesFuture: Vector[Future[GetMappingResponseV2]] = mappingIris.map { mappingIri: IRI => for { mappingResponse: GetMappingResponseV2 <- (responderManager ? GetMappingRequestV2( - mappingIri = mappingIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - )).mapTo[GetMappingResponseV2] + mappingIri = mappingIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + )).mapTo[GetMappingResponseV2] } yield mappingResponse }.toVector @@ -62,8 +62,8 @@ abstract class ResponderWithStandoffV2(responderData: ResponderData) extends Res mappingResponses: Vector[GetMappingResponseV2] <- Future.sequence(mappingResponsesFuture) // get the default XSL transformations - mappingsWithFuture: Vector[Future[(IRI, MappingAndXSLTransformation)]] = mappingResponses.map { - mapping: GetMappingResponseV2 => + mappingsWithFuture: Vector[Future[(IRI, MappingAndXSLTransformation)]] = + mappingResponses.map { mapping: GetMappingResponseV2 => for { // if given, get the default XSL transformation xsltOption: Option[String] <- @@ -94,10 +94,10 @@ abstract class ResponderWithStandoffV2(responderData: ResponderData) extends Res XSLTransformation = xsltOption ) - } + } mappings: Vector[(IRI, MappingAndXSLTransformation)] <- Future.sequence(mappingsWithFuture) - mappingsAsMap: Map[IRI, MappingAndXSLTransformation] = mappings.toMap + mappingsAsMap: Map[IRI, MappingAndXSLTransformation] = mappings.toMap } yield mappingsAsMap } diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v2/SearchResponderV2.scala b/webapi/src/main/scala/org/knora/webapi/responders/v2/SearchResponderV2.scala index c876925d2f..4d71da77ce 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/v2/SearchResponderV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v2/SearchResponderV2.scala @@ -178,20 +178,20 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand for { countSparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .searchFulltext( - searchTerms = searchTerms, - limitToProject = limitToProject, - limitToResourceClass = limitToResourceClass.map(_.toString), - limitToStandoffClass = limitToStandoffClass.map(_.toString), - returnFiles = false, // not relevant for a count query - separator = None, // no separator needed for count query - limit = 1, - offset = 0, - countQuery = true // do not get the resources themselves, but the sum of results - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v2.txt + .searchFulltext( + searchTerms = searchTerms, + limitToProject = limitToProject, + limitToResourceClass = limitToResourceClass.map(_.toString), + limitToStandoffClass = limitToStandoffClass.map(_.toString), + returnFiles = false, // not relevant for a count query + separator = None, // no separator needed for count query + limit = 1, + offset = 0, + countQuery = true // do not get the resources themselves, but the sum of results + ) + .toString() + ) // _ = println(countSparql) @@ -199,10 +199,10 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand // query response should contain one result with one row with the name "count" _ = if (countResponse.results.bindings.length != 1) { - throw GravsearchException( - s"Fulltext count query is expected to return exactly one row, but ${countResponse.results.bindings.size} given" - ) - } + throw GravsearchException( + s"Fulltext count query is expected to return exactly one row, but ${countResponse.results.bindings.size} given" + ) + } count = countResponse.results.bindings.head.rowMap("count") @@ -243,25 +243,25 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand for { searchSparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .searchFulltext( - searchTerms = searchTerms, - limitToProject = limitToProject, - limitToResourceClass = limitToResourceClass.map(_.toString), - limitToStandoffClass = limitToStandoffClass.map(_.toString), - returnFiles = returnFiles, - separator = Some(groupConcatSeparator), - limit = settings.v2ResultsPerPage, - offset = offset * settings.v2ResultsPerPage, // determine the actual offset - countQuery = false - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v2.txt + .searchFulltext( + searchTerms = searchTerms, + limitToProject = limitToProject, + limitToResourceClass = limitToResourceClass.map(_.toString), + limitToStandoffClass = limitToStandoffClass.map(_.toString), + returnFiles = returnFiles, + separator = Some(groupConcatSeparator), + limit = settings.v2ResultsPerPage, + offset = offset * settings.v2ResultsPerPage, // determine the actual offset + countQuery = false + ) + .toString() + ) // _ = println(searchSparql) prequeryResponseNotMerged: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(searchSparql)) - .mapTo[SparqlSelectResult] + .mapTo[SparqlSelectResult] // _ = println(prequeryResponseNotMerged) mainResourceVar = QueryVariable("resource") @@ -272,8 +272,8 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand // a sequence of resource IRIs that match the search criteria // attention: no permission checking has been done so far resourceIris: Seq[IRI] = prequeryResponse.results.bindings.map { resultRow: VariableResultsRow => - resultRow.rowMap(FullTextSearchConstants.resourceVar.variableName) - } + resultRow.rowMap(FullTextSearchConstants.resourceVar.variableName) + } // If the prequery returned some results, prepare a main query. mainResourcesAndValueRdfData: ConstructResponseUtilV2.MainResourcesAndValueRdfData <- @@ -321,16 +321,17 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand for { searchResponse: SparqlExtendedConstructResponse <- (storeManager ? SparqlExtendedConstructRequest( - sparql = triplestoreSpecificQuery.toSparql, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + sparql = triplestoreSpecificQuery.toSparql, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse] // separate resources and value objects - queryResultsSep: ConstructResponseUtilV2.MainResourcesAndValueRdfData = ConstructResponseUtilV2 - .splitMainResourcesAndValueRdfData( - constructQueryResults = searchResponse, - requestingUser = requestingUser - ) + queryResultsSep: ConstructResponseUtilV2.MainResourcesAndValueRdfData = + ConstructResponseUtilV2 + .splitMainResourcesAndValueRdfData( + constructQueryResults = searchResponse, + requestingUser = requestingUser + ) } yield queryResultsSep } else { @@ -343,9 +344,9 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand // Find out whether to query standoff along with text values. This boolean value will be passed to // ConstructResponseUtilV2.makeTextValueContentV2. queryStandoff: Boolean = SchemaOptions.queryStandoffWithTextValues( - targetSchema = targetSchema, - schemaOptions = schemaOptions - ) + targetSchema = targetSchema, + schemaOptions = schemaOptions + ) // If we're querying standoff, get XML-to standoff mappings. mappingsAsMap: Map[IRI, MappingAndXSLTransformation] <- @@ -362,19 +363,19 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand // _ = println(mappingsAsMap) apiResponse: ReadResourcesSequenceV2 <- ConstructResponseUtilV2.createApiResponse( - mainResourcesAndValueRdfData = mainResourcesAndValueRdfData, - orderByResourceIri = resourceIris, - pageSizeBeforeFiltering = resourceIris.size, - mappings = mappingsAsMap, - queryStandoff = queryStandoff, - calculateMayHaveMoreResults = true, - versionDate = None, - responderManager = responderManager, - settings = settings, - targetSchema = targetSchema, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + mainResourcesAndValueRdfData = mainResourcesAndValueRdfData, + orderByResourceIri = resourceIris, + pageSizeBeforeFiltering = resourceIris.size, + mappings = mappingsAsMap, + queryStandoff = queryStandoff, + calculateMayHaveMoreResults = true, + versionDate = None, + responderManager = responderManager, + settings = settings, + targetSchema = targetSchema, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) } yield apiResponse } @@ -401,19 +402,19 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand // Do type inspection and remove type annotations from the WHERE clause. typeInspectionResult: GravsearchTypeInspectionResult <- gravsearchTypeInspectionRunner.inspectTypes( - inputQuery.whereClause, - requestingUser - ) + inputQuery.whereClause, + requestingUser + ) whereClauseWithoutAnnotations: WhereClause = GravsearchTypeInspectionUtil.removeTypeAnnotations( - inputQuery.whereClause - ) + inputQuery.whereClause + ) // Validate schemas and predicates in the CONSTRUCT clause. _ = GravsearchQueryChecker.checkConstructClause( - constructClause = inputQuery.constructClause, - typeInspectionResult = typeInspectionResult - ) + constructClause = inputQuery.constructClause, + typeInspectionResult = typeInspectionResult + ) // Create a Select prequery @@ -426,12 +427,15 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand ) nonTriplestoreSpecificPrequery: SelectQuery = QueryTraverser.transformConstructToSelect( - inputQuery = inputQuery.copy( - whereClause = whereClauseWithoutAnnotations, - orderBy = Seq.empty[OrderCriterion] // count queries do not need any sorting criteria - ), - transformer = nonTriplestoreSpecificConstructToSelectTransformer - ) + inputQuery = inputQuery.copy( + whereClause = whereClauseWithoutAnnotations, + orderBy = + Seq.empty[ + OrderCriterion + ] // count queries do not need any sorting criteria + ), + transformer = nonTriplestoreSpecificConstructToSelectTransformer + ) // Convert the non-triplestore-specific query to a triplestore-specific one. @@ -441,21 +445,21 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand ) triplestoreSpecificCountQuery = QueryTraverser.transformSelectToSelect( - inputQuery = nonTriplestoreSpecificPrequery, - transformer = triplestoreSpecificQueryPatternTransformerSelect - ) + inputQuery = nonTriplestoreSpecificPrequery, + transformer = triplestoreSpecificQueryPatternTransformerSelect + ) // _ = println(triplestoreSpecificCountQuery.toSparql) countResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(triplestoreSpecificCountQuery.toSparql)) - .mapTo[SparqlSelectResult] + .mapTo[SparqlSelectResult] // query response should contain one result with one row with the name "count" _ = if (countResponse.results.bindings.length != 1) { - throw GravsearchException( - s"Count query is expected to return exactly one row, but ${countResponse.results.bindings.size} given" - ) - } + throw GravsearchException( + s"Count query is expected to return exactly one row, but ${countResponse.results.bindings.size} given" + ) + } count: String = countResponse.results.bindings.head.rowMap("count") @@ -485,18 +489,18 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand for { // Do type inspection and remove type annotations from the WHERE clause. typeInspectionResult: GravsearchTypeInspectionResult <- gravsearchTypeInspectionRunner.inspectTypes( - inputQuery.whereClause, - requestingUser - ) + inputQuery.whereClause, + requestingUser + ) whereClauseWithoutAnnotations: WhereClause = GravsearchTypeInspectionUtil.removeTypeAnnotations( - inputQuery.whereClause - ) + inputQuery.whereClause + ) // Validate schemas and predicates in the CONSTRUCT clause. _ = GravsearchQueryChecker.checkConstructClause( - constructClause = inputQuery.constructClause, - typeInspectionResult = typeInspectionResult - ) + constructClause = inputQuery.constructClause, + typeInspectionResult = typeInspectionResult + ) // Create a Select prequery @@ -513,9 +517,10 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand // TODO: the ORDER BY criterion has to be included in a GROUP BY statement, returning more than one row if property occurs more than once nonTriplestoreSpecificPrequery: SelectQuery = QueryTraverser.transformConstructToSelect( - inputQuery = inputQuery.copy(whereClause = whereClauseWithoutAnnotations), - transformer = nonTriplestoreSpecificConstructToSelectTransformer - ) + inputQuery = + inputQuery.copy(whereClause = whereClauseWithoutAnnotations), + transformer = nonTriplestoreSpecificConstructToSelectTransformer + ) // variable representing the main resources mainResourceVar: QueryVariable = nonTriplestoreSpecificConstructToSelectTransformer.mainResourceVariable @@ -529,29 +534,29 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand // Convert the preprocessed query to a non-triplestore-specific query. triplestoreSpecificPrequery = QueryTraverser.transformSelectToSelect( - inputQuery = nonTriplestoreSpecificPrequery, - transformer = triplestoreSpecificQueryPatternTransformerSelect - ) + inputQuery = nonTriplestoreSpecificPrequery, + transformer = triplestoreSpecificQueryPatternTransformerSelect + ) triplestoreSpecificPrequerySparql = triplestoreSpecificPrequery.toSparql - _ = log.debug(triplestoreSpecificPrequerySparql) + _ = log.debug(triplestoreSpecificPrequerySparql) prequeryResponseNotMerged: SparqlSelectResult <- (storeManager ? SparqlSelectRequest( - triplestoreSpecificPrequerySparql - )).mapTo[SparqlSelectResult] + triplestoreSpecificPrequerySparql + )).mapTo[SparqlSelectResult] pageSizeBeforeFiltering: Int = prequeryResponseNotMerged.results.bindings.size // Merge rows with the same main resource IRI. This could happen if there are unbound variables in a UNION. prequeryResponse = mergePrequeryResults( - prequeryResponseNotMerged = prequeryResponseNotMerged, - mainResourceVar = mainResourceVar - ) + prequeryResponseNotMerged = prequeryResponseNotMerged, + mainResourceVar = mainResourceVar + ) // a sequence of resource IRIs that match the search criteria // attention: no permission checking has been done so far mainResourceIris: Seq[IRI] = prequeryResponse.results.bindings.map { resultRow: VariableResultsRow => - resultRow.rowMap(mainResourceVar.variableName) - } + resultRow.rowMap(mainResourceVar.variableName) + } mainQueryResults: ConstructResponseUtilV2.MainResourcesAndValueRdfData <- if (mainResourceIris.nonEmpty) { @@ -625,9 +630,9 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand for { mainQueryResponse: SparqlExtendedConstructResponse <- (storeManager ? SparqlExtendedConstructRequest( - sparql = triplestoreSpecificMainQuerySparql, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + sparql = triplestoreSpecificMainQuerySparql, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse] // Filter out values that the user doesn't have permission to see. queryResultsFilteredForPermissions: ConstructResponseUtilV2.MainResourcesAndValueRdfData = @@ -642,15 +647,15 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand IRI, ConstructResponseUtilV2.ResourceWithValueRdfData ] = MainQueryResultProcessor - .getRequestedValuesFromResultsWithFullGraphPattern( - queryResultsFilteredForPermissions.resources, - valueObjectVarsAndIrisPerMainResource, - allResourceVariablesFromTypeInspection, - dependentResourceIrisFromTypeInspection, - nonTriplestoreSpecificConstructToSelectTransformer, - typeInspectionResult, - inputQuery - ) + .getRequestedValuesFromResultsWithFullGraphPattern( + queryResultsFilteredForPermissions.resources, + valueObjectVarsAndIrisPerMainResource, + allResourceVariablesFromTypeInspection, + dependentResourceIrisFromTypeInspection, + nonTriplestoreSpecificConstructToSelectTransformer, + typeInspectionResult, + inputQuery + ) } yield queryResultsFilteredForPermissions.copy( resources = queryResWithFullGraphPatternOnlyRequestedValues ) @@ -663,9 +668,9 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand // Find out whether to query standoff along with text values. This boolean value will be passed to // ConstructResponseUtilV2.makeTextValueContentV2. queryStandoff: Boolean = SchemaOptions.queryStandoffWithTextValues( - targetSchema = targetSchema, - schemaOptions = schemaOptions - ) + targetSchema = targetSchema, + schemaOptions = schemaOptions + ) // If we're querying standoff, get XML-to standoff mappings. mappingsAsMap: Map[IRI, MappingAndXSLTransformation] <- @@ -680,19 +685,19 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand } apiResponse: ReadResourcesSequenceV2 <- ConstructResponseUtilV2.createApiResponse( - mainResourcesAndValueRdfData = mainQueryResults, - orderByResourceIri = mainResourceIris, - pageSizeBeforeFiltering = pageSizeBeforeFiltering, - mappings = mappingsAsMap, - queryStandoff = queryStandoff, - versionDate = None, - calculateMayHaveMoreResults = true, - responderManager = responderManager, - settings = settings, - targetSchema = targetSchema, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + mainResourcesAndValueRdfData = mainQueryResults, + orderByResourceIri = mainResourceIris, + pageSizeBeforeFiltering = pageSizeBeforeFiltering, + mappings = mappingsAsMap, + queryStandoff = queryStandoff, + versionDate = None, + calculateMayHaveMoreResults = true, + responderManager = responderManager, + settings = settings, + targetSchema = targetSchema, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) } yield apiResponse } @@ -725,79 +730,98 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand // If an ORDER BY property was specified, determine which subproperty of knora-base:valueHas to use to get the // literal value to sort by. maybeOrderByValuePredicate: Option[SmartIri] = maybeInternalOrderByPropertyIri match { - case Some(internalOrderByPropertyIri) => - val internalOrderByPropertyDef: ReadPropertyInfoV2 = - entityInfoResponse.propertyInfoMap(internalOrderByPropertyIri) - - // Ensure that the ORDER BY property is one that we can sort by. - if ( - !internalOrderByPropertyDef.isResourceProp || internalOrderByPropertyDef.isLinkProp || internalOrderByPropertyDef.isLinkValueProp || internalOrderByPropertyDef.isFileValueProp - ) { - throw BadRequestException(s"Cannot sort by property <${resourcesInProjectGetRequestV2.orderByProperty}>") - } - - // Ensure that the resource class has a cardinality on the ORDER BY property. - if (!classDef.knoraResourceProperties.contains(internalOrderByPropertyIri)) { - throw BadRequestException( - s"Class <${resourcesInProjectGetRequestV2.resourceClass}> has no cardinality on property <${resourcesInProjectGetRequestV2.orderByProperty}>" - ) - } - - // Get the value class that's the object of the knora-base:objectClassConstraint of the ORDER BY property. - val orderByValueType: SmartIri = internalOrderByPropertyDef.entityInfoContent.requireIriObject( - OntologyConstants.KnoraBase.ObjectClassConstraint.toSmartIri, - throw InconsistentRepositoryDataException( - s"Property <$internalOrderByPropertyIri> has no knora-base:objectClassConstraint" - ) - ) - - // Determine which subproperty of knora-base:valueHas corresponds to that value class. - val orderByValuePredicate = orderByValueType.toString match { - case OntologyConstants.KnoraBase.IntValue => OntologyConstants.KnoraBase.ValueHasInteger - case OntologyConstants.KnoraBase.DecimalValue => OntologyConstants.KnoraBase.ValueHasDecimal - case OntologyConstants.KnoraBase.BooleanValue => OntologyConstants.KnoraBase.ValueHasBoolean - case OntologyConstants.KnoraBase.DateValue => OntologyConstants.KnoraBase.ValueHasStartJDN - case OntologyConstants.KnoraBase.ColorValue => OntologyConstants.KnoraBase.ValueHasColor - case OntologyConstants.KnoraBase.GeonameValue => OntologyConstants.KnoraBase.ValueHasGeonameCode - case OntologyConstants.KnoraBase.IntervalValue => OntologyConstants.KnoraBase.ValueHasIntervalStart - case OntologyConstants.KnoraBase.UriValue => OntologyConstants.KnoraBase.ValueHasUri - case _ => OntologyConstants.KnoraBase.ValueHasString - } - - Some(orderByValuePredicate.toSmartIri) - - case None => None - } + case Some(internalOrderByPropertyIri) => + val internalOrderByPropertyDef: ReadPropertyInfoV2 = + entityInfoResponse.propertyInfoMap( + internalOrderByPropertyIri + ) + + // Ensure that the ORDER BY property is one that we can sort by. + if ( + !internalOrderByPropertyDef.isResourceProp || internalOrderByPropertyDef.isLinkProp || internalOrderByPropertyDef.isLinkValueProp || internalOrderByPropertyDef.isFileValueProp + ) { + throw BadRequestException( + s"Cannot sort by property <${resourcesInProjectGetRequestV2.orderByProperty}>" + ) + } + + // Ensure that the resource class has a cardinality on the ORDER BY property. + if ( + !classDef.knoraResourceProperties.contains( + internalOrderByPropertyIri + ) + ) { + throw BadRequestException( + s"Class <${resourcesInProjectGetRequestV2.resourceClass}> has no cardinality on property <${resourcesInProjectGetRequestV2.orderByProperty}>" + ) + } + + // Get the value class that's the object of the knora-base:objectClassConstraint of the ORDER BY property. + val orderByValueType: SmartIri = + internalOrderByPropertyDef.entityInfoContent + .requireIriObject( + OntologyConstants.KnoraBase.ObjectClassConstraint.toSmartIri, + throw InconsistentRepositoryDataException( + s"Property <$internalOrderByPropertyIri> has no knora-base:objectClassConstraint" + ) + ) + + // Determine which subproperty of knora-base:valueHas corresponds to that value class. + val orderByValuePredicate = orderByValueType.toString match { + case OntologyConstants.KnoraBase.IntValue => + OntologyConstants.KnoraBase.ValueHasInteger + case OntologyConstants.KnoraBase.DecimalValue => + OntologyConstants.KnoraBase.ValueHasDecimal + case OntologyConstants.KnoraBase.BooleanValue => + OntologyConstants.KnoraBase.ValueHasBoolean + case OntologyConstants.KnoraBase.DateValue => + OntologyConstants.KnoraBase.ValueHasStartJDN + case OntologyConstants.KnoraBase.ColorValue => + OntologyConstants.KnoraBase.ValueHasColor + case OntologyConstants.KnoraBase.GeonameValue => + OntologyConstants.KnoraBase.ValueHasGeonameCode + case OntologyConstants.KnoraBase.IntervalValue => + OntologyConstants.KnoraBase.ValueHasIntervalStart + case OntologyConstants.KnoraBase.UriValue => + OntologyConstants.KnoraBase.ValueHasUri + case _ => OntologyConstants.KnoraBase.ValueHasString + } + + Some(orderByValuePredicate.toSmartIri) + + case None => None + } // Do a SELECT prequery to get the IRIs of the requested page of resources. prequery = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .getResourcesByClassInProjectPrequery( - projectIri = resourcesInProjectGetRequestV2.projectIri.toString, - resourceClassIri = internalClassIri, - maybeOrderByProperty = maybeInternalOrderByPropertyIri, - maybeOrderByValuePredicate = maybeOrderByValuePredicate, - limit = settings.v2ResultsPerPage, - offset = resourcesInProjectGetRequestV2.page * settings.v2ResultsPerPage - ) - .toString - - sparqlSelectResponse <- (storeManager ? SparqlSelectRequest(prequery)).mapTo[SparqlSelectResult] + .getResourcesByClassInProjectPrequery( + projectIri = resourcesInProjectGetRequestV2.projectIri.toString, + resourceClassIri = internalClassIri, + maybeOrderByProperty = maybeInternalOrderByPropertyIri, + maybeOrderByValuePredicate = maybeOrderByValuePredicate, + limit = settings.v2ResultsPerPage, + offset = resourcesInProjectGetRequestV2.page * settings.v2ResultsPerPage + ) + .toString + + sparqlSelectResponse <- (storeManager ? SparqlSelectRequest(prequery)).mapTo[SparqlSelectResult] mainResourceIris: Seq[IRI] = sparqlSelectResponse.results.bindings.map(_.rowMap("resource")) // Find out whether to query standoff along with text values. This boolean value will be passed to // ConstructResponseUtilV2.makeTextValueContentV2. queryStandoff: Boolean = SchemaOptions.queryStandoffWithTextValues( - targetSchema = ApiV2Complex, - schemaOptions = resourcesInProjectGetRequestV2.schemaOptions - ) + targetSchema = ApiV2Complex, + schemaOptions = resourcesInProjectGetRequestV2.schemaOptions + ) // If we're supposed to query standoff, get the indexes delimiting the first page of standoff. (Subsequent // pages, if any, will be queried separately.) - (maybeStandoffMinStartIndex: Option[Int], maybeStandoffMaxStartIndex: Option[Int]) = StandoffTagUtilV2 - .getStandoffMinAndMaxStartIndexesForTextValueQuery( - queryStandoff = queryStandoff, - settings = settings - ) + (maybeStandoffMinStartIndex: Option[Int], maybeStandoffMaxStartIndex: Option[Int]) = + StandoffTagUtilV2 + .getStandoffMinAndMaxStartIndexesForTextValueQuery( + queryStandoff = queryStandoff, + settings = settings + ) // Are there any matching resources? apiResponse: ReadResourcesSequenceV2 <- @@ -806,34 +830,36 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand // Yes. Do a CONSTRUCT query to get the contents of those resources. If we're querying standoff, get // at most one page of standoff per text value. resourceRequestSparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .getResourcePropertiesAndValues( - resourceIris = mainResourceIris, - preview = false, - withDeleted = false, - queryAllNonStandoff = true, - maybePropertyIri = None, - maybeVersionDate = None, - maybeStandoffMinStartIndex = maybeStandoffMinStartIndex, - maybeStandoffMaxStartIndex = maybeStandoffMaxStartIndex, - stringFormatter = stringFormatter - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v2.txt + .getResourcePropertiesAndValues( + resourceIris = mainResourceIris, + preview = false, + withDeleted = false, + queryAllNonStandoff = true, + maybePropertyIri = None, + maybeVersionDate = None, + maybeStandoffMinStartIndex = maybeStandoffMinStartIndex, + maybeStandoffMaxStartIndex = maybeStandoffMaxStartIndex, + stringFormatter = stringFormatter + ) + .toString() + ) // _ = println(resourceRequestSparql) - resourceRequestResponse: SparqlExtendedConstructResponse <- (storeManager ? SparqlExtendedConstructRequest( - sparql = resourceRequestSparql, - featureFactoryConfig = resourcesInProjectGetRequestV2.featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + resourceRequestResponse: SparqlExtendedConstructResponse <- + (storeManager ? SparqlExtendedConstructRequest( + sparql = resourceRequestSparql, + featureFactoryConfig = resourcesInProjectGetRequestV2.featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse] // separate resources and values - mainResourcesAndValueRdfData: ConstructResponseUtilV2.MainResourcesAndValueRdfData = ConstructResponseUtilV2 - .splitMainResourcesAndValueRdfData( - constructQueryResults = resourceRequestResponse, - requestingUser = resourcesInProjectGetRequestV2.requestingUser - ) + mainResourcesAndValueRdfData: ConstructResponseUtilV2.MainResourcesAndValueRdfData = + ConstructResponseUtilV2 + .splitMainResourcesAndValueRdfData( + constructQueryResults = resourceRequestResponse, + requestingUser = resourcesInProjectGetRequestV2.requestingUser + ) // If we're querying standoff, get XML-to standoff mappings. mappings: Map[IRI, MappingAndXSLTransformation] <- @@ -849,19 +875,23 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand // Construct a ReadResourceV2 for each resource that the user has permission to see. readResourcesSequence: ReadResourcesSequenceV2 <- ConstructResponseUtilV2.createApiResponse( - mainResourcesAndValueRdfData = mainResourcesAndValueRdfData, - orderByResourceIri = mainResourceIris, - pageSizeBeforeFiltering = mainResourceIris.size, - mappings = mappings, - queryStandoff = maybeStandoffMinStartIndex.nonEmpty, - versionDate = None, - calculateMayHaveMoreResults = true, - responderManager = responderManager, - targetSchema = resourcesInProjectGetRequestV2.targetSchema, - settings = settings, - featureFactoryConfig = resourcesInProjectGetRequestV2.featureFactoryConfig, - requestingUser = resourcesInProjectGetRequestV2.requestingUser - ) + mainResourcesAndValueRdfData = + mainResourcesAndValueRdfData, + orderByResourceIri = mainResourceIris, + pageSizeBeforeFiltering = mainResourceIris.size, + mappings = mappings, + queryStandoff = maybeStandoffMinStartIndex.nonEmpty, + versionDate = None, + calculateMayHaveMoreResults = true, + responderManager = responderManager, + targetSchema = + resourcesInProjectGetRequestV2.targetSchema, + settings = settings, + featureFactoryConfig = + resourcesInProjectGetRequestV2.featureFactoryConfig, + requestingUser = + resourcesInProjectGetRequestV2.requestingUser + ) } yield readResourcesSequence } else { FastFuture.successful(ReadResourcesSequenceV2(Vector.empty[ReadResourceV2])) @@ -890,17 +920,17 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand for { countSparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .searchResourceByLabel( - searchTerm = searchPhrase, - limitToProject = limitToProject, - limitToResourceClass = limitToResourceClass.map(_.toString), - limit = 1, - offset = 0, - countQuery = true - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v2.txt + .searchResourceByLabel( + searchTerm = searchPhrase, + limitToProject = limitToProject, + limitToResourceClass = limitToResourceClass.map(_.toString), + limit = 1, + offset = 0, + countQuery = true + ) + .toString() + ) // _ = println(countSparql) @@ -908,10 +938,10 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand // query response should contain one result with one row with the name "count" _ = if (countResponse.results.bindings.length != 1) { - throw GravsearchException( - s"Fulltext count query is expected to return exactly one row, but ${countResponse.results.bindings.size} given" - ) - } + throw GravsearchException( + s"Fulltext count query is expected to return exactly one row, but ${countResponse.results.bindings.size} given" + ) + } count = countResponse.results.bindings.head.rowMap("count") @@ -947,70 +977,71 @@ class SearchResponderV2(responderData: ResponderData) extends ResponderWithStand for { searchResourceByLabelSparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .searchResourceByLabel( - searchTerm = searchPhrase, - limitToProject = limitToProject, - limitToResourceClass = limitToResourceClass.map(_.toString), - limit = settings.v2ResultsPerPage, - offset = offset * settings.v2ResultsPerPage, - countQuery = false - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v2.txt + .searchResourceByLabel( + searchTerm = searchPhrase, + limitToProject = limitToProject, + limitToResourceClass = limitToResourceClass.map(_.toString), + limit = settings.v2ResultsPerPage, + offset = offset * settings.v2ResultsPerPage, + countQuery = false + ) + .toString() + ) // _ = println(searchResourceByLabelSparql) searchResourceByLabelResponse: SparqlExtendedConstructResponse <- (storeManager ? SparqlExtendedConstructRequest( - sparql = searchResourceByLabelSparql, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + sparql = searchResourceByLabelSparql, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse] // collect the IRIs of main resources returned - mainResourceIris: Set[IRI] = searchResourceByLabelResponse.statements.foldLeft(Set.empty[IRI]) { - case (acc: Set[IRI], (subject: SubjectV2, assertions: Map[SmartIri, Seq[LiteralV2]])) => - // check if the assertions represent a main resource and include its IRI if so - val subjectIsMainResource: Boolean = - assertions.getOrElse(OntologyConstants.KnoraBase.IsMainResource.toSmartIri, Seq.empty).headOption match { - case Some(BooleanLiteralV2(booleanVal)) => booleanVal - case _ => false - } + mainResourceIris: Set[IRI] = + searchResourceByLabelResponse.statements.foldLeft(Set.empty[IRI]) { + case (acc: Set[IRI], (subject: SubjectV2, assertions: Map[SmartIri, Seq[LiteralV2]])) => + // check if the assertions represent a main resource and include its IRI if so + val subjectIsMainResource: Boolean = + assertions.getOrElse(OntologyConstants.KnoraBase.IsMainResource.toSmartIri, Seq.empty).headOption match { + case Some(BooleanLiteralV2(booleanVal)) => booleanVal + case _ => false + } - if (subjectIsMainResource) { - val subjIri: IRI = subject match { - case IriSubjectV2(value) => value - case other => throw InconsistentRepositoryDataException(s"Unexpected subject of resource: $other") - } + if (subjectIsMainResource) { + val subjIri: IRI = subject match { + case IriSubjectV2(value) => value + case other => throw InconsistentRepositoryDataException(s"Unexpected subject of resource: $other") + } - acc + subjIri - } else { - acc - } - } + acc + subjIri + } else { + acc + } + } // _ = println(mainResourceIris.size) // separate resources and value objects mainResourcesAndValueRdfData = ConstructResponseUtilV2.splitMainResourcesAndValueRdfData( - constructQueryResults = searchResourceByLabelResponse, - requestingUser = requestingUser - ) + constructQueryResults = searchResourceByLabelResponse, + requestingUser = requestingUser + ) //_ = println(queryResultsSeparated) apiResponse: ReadResourcesSequenceV2 <- ConstructResponseUtilV2.createApiResponse( - mainResourcesAndValueRdfData = mainResourcesAndValueRdfData, - orderByResourceIri = mainResourceIris.toSeq.sorted, - pageSizeBeforeFiltering = mainResourceIris.size, - queryStandoff = false, - versionDate = None, - calculateMayHaveMoreResults = true, - responderManager = responderManager, - targetSchema = targetSchema, - settings = settings, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + mainResourcesAndValueRdfData = mainResourcesAndValueRdfData, + orderByResourceIri = mainResourceIris.toSeq.sorted, + pageSizeBeforeFiltering = mainResourceIris.size, + queryStandoff = false, + versionDate = None, + calculateMayHaveMoreResults = true, + responderManager = responderManager, + targetSchema = targetSchema, + settings = settings, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) } yield apiResponse } diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v2/StandoffResponderV2.scala b/webapi/src/main/scala/org/knora/webapi/responders/v2/StandoffResponderV2.scala index 65bbc6db0d..7c0fb5ee87 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/v2/StandoffResponderV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v2/StandoffResponderV2.scala @@ -103,86 +103,91 @@ class StandoffResponderV2(responderData: ResponderData) extends Responder(respon for { resourceRequestSparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .getResourcePropertiesAndValues( - resourceIris = Seq(getStandoffRequestV2.resourceIri), - preview = false, - withDeleted = false, - maybePropertyIri = None, - maybeVersionDate = None, - queryAllNonStandoff = false, - maybeValueIri = Some(getStandoffRequestV2.valueIri), - maybeStandoffMinStartIndex = Some(getStandoffRequestV2.offset), - maybeStandoffMaxStartIndex = Some(requestMaxStartIndex), - stringFormatter = stringFormatter - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v2.txt + .getResourcePropertiesAndValues( + resourceIris = Seq(getStandoffRequestV2.resourceIri), + preview = false, + withDeleted = false, + maybePropertyIri = None, + maybeVersionDate = None, + queryAllNonStandoff = false, + maybeValueIri = Some(getStandoffRequestV2.valueIri), + maybeStandoffMinStartIndex = Some(getStandoffRequestV2.offset), + maybeStandoffMaxStartIndex = Some(requestMaxStartIndex), + stringFormatter = stringFormatter + ) + .toString() + ) // _ = println("=================================") // _ = println(resourceRequestSparql) // standoffPageStartTime = System.currentTimeMillis() - resourceRequestResponse: SparqlExtendedConstructResponse <- (storeManager ? SparqlExtendedConstructRequest( - sparql = resourceRequestSparql, - featureFactoryConfig = getStandoffRequestV2.featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + resourceRequestResponse: SparqlExtendedConstructResponse <- + (storeManager ? SparqlExtendedConstructRequest( + sparql = resourceRequestSparql, + featureFactoryConfig = getStandoffRequestV2.featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse] // standoffPageEndTime = System.currentTimeMillis() // _ = println(s"Got a page of standoff in ${standoffPageEndTime - standoffPageStartTime} ms") // separate resources and values - mainResourcesAndValueRdfData: ConstructResponseUtilV2.MainResourcesAndValueRdfData = ConstructResponseUtilV2 - .splitMainResourcesAndValueRdfData( - constructQueryResults = resourceRequestResponse, - requestingUser = getStandoffRequestV2.requestingUser - ) + mainResourcesAndValueRdfData: ConstructResponseUtilV2.MainResourcesAndValueRdfData = + ConstructResponseUtilV2 + .splitMainResourcesAndValueRdfData( + constructQueryResults = resourceRequestResponse, + requestingUser = getStandoffRequestV2.requestingUser + ) readResourcesSequenceV2: ReadResourcesSequenceV2 <- ConstructResponseUtilV2.createApiResponse( - mainResourcesAndValueRdfData = mainResourcesAndValueRdfData, - orderByResourceIri = Seq(getStandoffRequestV2.resourceIri), - pageSizeBeforeFiltering = 1, // doesn't matter because we're not doing paging - mappings = Map.empty, - queryStandoff = false, - calculateMayHaveMoreResults = false, - versionDate = None, - responderManager = responderManager, - targetSchema = getStandoffRequestV2.targetSchema, - settings = settings, - featureFactoryConfig = getStandoffRequestV2.featureFactoryConfig, - requestingUser = getStandoffRequestV2.requestingUser - ) + mainResourcesAndValueRdfData = mainResourcesAndValueRdfData, + orderByResourceIri = Seq(getStandoffRequestV2.resourceIri), + pageSizeBeforeFiltering = + 1, // doesn't matter because we're not doing paging + mappings = Map.empty, + queryStandoff = false, + calculateMayHaveMoreResults = false, + versionDate = None, + responderManager = responderManager, + targetSchema = getStandoffRequestV2.targetSchema, + settings = settings, + featureFactoryConfig = + getStandoffRequestV2.featureFactoryConfig, + requestingUser = getStandoffRequestV2.requestingUser + ) readResourceV2 = readResourcesSequenceV2.toResource(getStandoffRequestV2.resourceIri) - valueObj: ReadValueV2 = readResourceV2.values.values.flatten - .find(_.valueIri == getStandoffRequestV2.valueIri) - .getOrElse( - throw NotFoundException( - s"Value <${getStandoffRequestV2.valueIri}> not found in resource <${getStandoffRequestV2.resourceIri}> (maybe you do not have permission to see it, or it is marked as deleted)" + valueObj: ReadValueV2 = + readResourceV2.values.values.flatten + .find(_.valueIri == getStandoffRequestV2.valueIri) + .getOrElse( + throw NotFoundException( + s"Value <${getStandoffRequestV2.valueIri}> not found in resource <${getStandoffRequestV2.resourceIri}> (maybe you do not have permission to see it, or it is marked as deleted)" + ) ) - ) textValueObj: ReadTextValueV2 = valueObj match { - case textVal: ReadTextValueV2 => textVal - case _ => - throw BadRequestException( - s"Value <${getStandoffRequestV2.valueIri}> not found in resource <${getStandoffRequestV2.resourceIri}> is not a text value" - ) - } + case textVal: ReadTextValueV2 => textVal + case _ => + throw BadRequestException( + s"Value <${getStandoffRequestV2.valueIri}> not found in resource <${getStandoffRequestV2.resourceIri}> is not a text value" + ) + } nextOffset: Option[Int] = textValueObj.valueHasMaxStandoffStartIndex match { - case Some(definedMaxIndex) => - if (requestMaxStartIndex >= definedMaxIndex) { - None - } else { - Some(requestMaxStartIndex + 1) - } - - case None => None - } + case Some(definedMaxIndex) => + if (requestMaxStartIndex >= definedMaxIndex) { + None + } else { + Some(requestMaxStartIndex + 1) + } + + case None => None + } } yield GetStandoffResponseV2( valueIri = textValueObj.valueIri, standoff = textValueObj.valueContent.standoff, @@ -207,47 +212,48 @@ class StandoffResponderV2(responderData: ResponderData) extends Responder(respon val xsltUrlFuture = for { textRepresentationResponseV2: ReadResourcesSequenceV2 <- (responderManager ? ResourcesGetRequestV2( - resourceIris = Vector(xslTransformationIri), - targetSchema = ApiV2Complex, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - )).mapTo[ReadResourcesSequenceV2] + resourceIris = Vector(xslTransformationIri), + targetSchema = ApiV2Complex, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + )).mapTo[ReadResourcesSequenceV2] resource = textRepresentationResponseV2.toResource(xslTransformationIri) _ = if (resource.resourceClassIri.toString != OntologyConstants.KnoraBase.XSLTransformation) { - throw BadRequestException( - s"Resource $xslTransformationIri is not a ${OntologyConstants.KnoraBase.XSLTransformation}" - ) - } - - (fileValueIri: IRI, xsltFileValueContent: TextFileValueContentV2) = resource.values.get( - OntologyConstants.KnoraBase.HasTextFileValue.toSmartIri - ) match { - case Some(values: Seq[ReadValueV2]) if values.size == 1 => - values.head match { - case value: ReadValueV2 => - value.valueContent match { - case textRepr: TextFileValueContentV2 => (value.valueIri, textRepr) - case _ => - throw InconsistentRepositoryDataException( - s"${OntologyConstants.KnoraBase.XSLTransformation} $xslTransformationIri is supposed to have exactly one value of type ${OntologyConstants.KnoraBase.TextFileValue}" - ) - } + throw BadRequestException( + s"Resource $xslTransformationIri is not a ${OntologyConstants.KnoraBase.XSLTransformation}" + ) } - case _ => - throw InconsistentRepositoryDataException( - s"${OntologyConstants.KnoraBase.XSLTransformation} has no or more than one property ${OntologyConstants.KnoraBase.HasTextFileValue}" - ) - } + (fileValueIri: IRI, xsltFileValueContent: TextFileValueContentV2) = + resource.values.get( + OntologyConstants.KnoraBase.HasTextFileValue.toSmartIri + ) match { + case Some(values: Seq[ReadValueV2]) if values.size == 1 => + values.head match { + case value: ReadValueV2 => + value.valueContent match { + case textRepr: TextFileValueContentV2 => (value.valueIri, textRepr) + case _ => + throw InconsistentRepositoryDataException( + s"${OntologyConstants.KnoraBase.XSLTransformation} $xslTransformationIri is supposed to have exactly one value of type ${OntologyConstants.KnoraBase.TextFileValue}" + ) + } + } + + case _ => + throw InconsistentRepositoryDataException( + s"${OntologyConstants.KnoraBase.XSLTransformation} has no or more than one property ${OntologyConstants.KnoraBase.HasTextFileValue}" + ) + } // check if xsltFileValueContent represents an XSL transformation _ = if (!xmlMimeTypes.contains(xsltFileValueContent.fileValue.internalMimeType)) { - throw BadRequestException( - s"Expected $fileValueIri to be an XML file referring to an XSL transformation, but it has MIME type ${xsltFileValueContent.fileValue.internalMimeType}" - ) - } + throw BadRequestException( + s"Expected $fileValueIri to be an XML file referring to an XSL transformation, but it has MIME type ${xsltFileValueContent.fileValue.internalMimeType}" + ) + } xsltUrl: String = s"${settings.internalSipiBaseUrl}/${resource.projectADM.shortcode}/${xsltFileValueContent.fileValue.internalFilename}/file" @@ -272,10 +278,10 @@ class StandoffResponderV2(responderData: ResponderData) extends Responder(respon } else { for { response: SipiGetTextFileResponse <- (storeManager ? SipiGetTextFileRequest( - fileUrl = xsltFileUrl, - requestingUser = KnoraSystemInstances.Users.SystemUser, - senderName = this.getClass.getName - )).mapTo[SipiGetTextFileResponse] + fileUrl = xsltFileUrl, + requestingUser = KnoraSystemInstances.Users.SystemUser, + senderName = this.getClass.getName + )).mapTo[SipiGetTextFileResponse] _ = CacheUtil.put(cacheName = xsltCacheName, key = xsltFileUrl, value = response.content) } yield response.content } @@ -321,7 +327,7 @@ class StandoffResponderV2(responderData: ResponderData) extends Responder(respon // create a schema instance schemaInstance: Schema = factory.newSchema(schemaSource) - validator: JValidator = schemaInstance.newValidator() + validator: JValidator = schemaInstance.newValidator() // validate the provided mapping _ = validator.validate(new StreamSource(new StringReader(xml))) @@ -331,159 +337,236 @@ class StandoffResponderV2(responderData: ResponderData) extends Responder(respon // get the default XSL transformation, if given (optional) defaultXSLTransformation: Option[IRI] <- mappingXML \ "defaultXSLTransformation" match { - case defaultTrans: NodeSeq if defaultTrans.length == 1 => - // check if the IRI is valid - val transIri = stringFormatter.validateAndEscapeIri( - defaultTrans.headOption - .getOrElse(throw BadRequestException("could not access ")) - .text, - throw BadRequestException(s"XSL transformation ${defaultTrans.head.text} is not a valid IRI") - ) - - // try to obtain the XSL transformation to make sure that it really exists - for { - transform: GetXSLTransformationResponseV2 <- getXSLTransformation( - xslTransformationIri = transIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) - } yield Some(transIri) - case _ => Future(None) - } + case defaultTrans: NodeSeq if defaultTrans.length == 1 => + // check if the IRI is valid + val transIri = stringFormatter.validateAndEscapeIri( + defaultTrans.headOption + .getOrElse( + throw BadRequestException( + "could not access " + ) + ) + .text, + throw BadRequestException( + s"XSL transformation ${defaultTrans.head.text} is not a valid IRI" + ) + ) + + // try to obtain the XSL transformation to make sure that it really exists + for { + transform: GetXSLTransformationResponseV2 <- + getXSLTransformation( + xslTransformationIri = transIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) + } yield Some(transIri) + case _ => Future(None) + } // create a collection of a all elements mappingElement mappingElementsXML: NodeSeq = mappingXML \ "mappingElement" mappingElements: Seq[MappingElement] = mappingElementsXML.map { curMappingEle: Node => - // get the name of the XML tag - val tagName = (curMappingEle \ "tag" \ "name").headOption - .getOrElse(throw BadRequestException(s"no '' given for node $curMappingEle")) - .text - - // get the namespace the tag is defined in - val tagNamespace = (curMappingEle \ "tag" \ "namespace").headOption - .getOrElse(throw BadRequestException(s"no '' given for node $curMappingEle")) - .text - - // get the class the tag is combined with - val className = (curMappingEle \ "tag" \ "class").headOption - .getOrElse(throw BadRequestException(s"no '' given for node $curMappingEle")) - .text - - // get the boolean indicating if the element requires a separator in the text once it is converted to standoff - val separatorBooleanAsString = (curMappingEle \ "tag" \ "separatesWords").headOption - .getOrElse(throw BadRequestException(s"no '' given for node $curMappingEle")) - .text - - val separatorRequired: Boolean = stringFormatter.validateBoolean( - separatorBooleanAsString, - throw BadRequestException(s" could not be converted to Boolean: $separatorBooleanAsString") - ) - - // get the standoff class IRI - val standoffClassIri = (curMappingEle \ "standoffClass" \ "classIri").headOption - .getOrElse(throw BadRequestException(s"no '' given for node $curMappingEle")) - .text - - // get a collection containing all the attributes - val attributeNodes: NodeSeq = curMappingEle \ "standoffClass" \ "attributes" \ "attribute" - - val attributes: Seq[MappingXMLAttribute] = attributeNodes.map { curAttributeNode => - // get the current attribute's name - val attrName = (curAttributeNode \ "attributeName").headOption - .getOrElse(throw BadRequestException(s"no '' given for attribute $curAttributeNode")) - .text - - val attributeNamespace = (curAttributeNode \ "namespace").headOption - .getOrElse(throw BadRequestException(s"no '' given for attribute $curAttributeNode")) - .text - - // get the standoff property IRI for the current attribute - val propIri = (curAttributeNode \ "propertyIri").headOption - .getOrElse(throw BadRequestException(s"no '' given for attribute $curAttributeNode")) - .text - - MappingXMLAttribute( - attributeName = stringFormatter.toSparqlEncodedString( - attrName, - throw BadRequestException(s"tagname $attrName contains invalid characters") - ), - namespace = stringFormatter.toSparqlEncodedString( - attributeNamespace, - throw BadRequestException(s"tagname $attributeNamespace contains invalid characters") - ), - standoffProperty = stringFormatter.validateAndEscapeIri( - propIri, - throw BadRequestException(s"standoff class IRI $standoffClassIri is not a valid IRI") - ), - mappingXMLAttributeElementIri = stringFormatter.makeRandomMappingElementIri(mappingIri) - ) - - } - - // get the optional element datatype - val datatypeMaybe: NodeSeq = curMappingEle \ "standoffClass" \ "datatype" - - // if "datatype" is given, get the the standoff class data type and the name of the XML data type attribute - val standoffDataTypeOption: Option[MappingStandoffDatatypeClass] = if (datatypeMaybe.nonEmpty) { - val dataTypeXML = (datatypeMaybe \ "type").headOption - .getOrElse(throw BadRequestException(s"no '' given for datatype")) - .text - - val dataType: StandoffDataTypeClasses.Value = - StandoffDataTypeClasses.lookup( - dataTypeXML, - throw BadRequestException(s"Invalid data type provided for $tagName") - ) - val dataTypeAttribute: String = (datatypeMaybe \ "attributeName").headOption - .getOrElse(throw BadRequestException(s"no '' given for datatype")) - .text - - Some( - MappingStandoffDatatypeClass( - datatype = dataType.toString, // safe because it is an enumeration - attributeName = stringFormatter.toSparqlEncodedString( - dataTypeAttribute, - throw BadRequestException(s"tagname $dataTypeAttribute contains invalid characters") - ), - mappingStandoffDataTypeClassElementIri = stringFormatter.makeRandomMappingElementIri(mappingIri) - ) - ) - } else { - None - } - - MappingElement( - tagName = stringFormatter.toSparqlEncodedString( - tagName, - throw BadRequestException(s"tagname $tagName contains invalid characters") - ), - namespace = stringFormatter.toSparqlEncodedString( - tagNamespace, - throw BadRequestException(s"namespace $tagNamespace contains invalid characters") - ), - className = stringFormatter.toSparqlEncodedString( - className, - throw BadRequestException(s"classname $className contains invalid characters") - ), - standoffClass = stringFormatter.validateAndEscapeIri( - standoffClassIri, - throw BadRequestException(s"standoff class IRI $standoffClassIri is not a valid IRI") - ), - attributes = attributes, - standoffDataTypeClass = standoffDataTypeOption, - mappingElementIri = stringFormatter.makeRandomMappingElementIri(mappingIri), - separatorRequired = separatorRequired - ) - - } + // get the name of the XML tag + val tagName = (curMappingEle \ "tag" \ "name").headOption + .getOrElse( + throw BadRequestException( + s"no '' given for node $curMappingEle" + ) + ) + .text + + // get the namespace the tag is defined in + val tagNamespace = (curMappingEle \ "tag" \ "namespace").headOption + .getOrElse( + throw BadRequestException( + s"no '' given for node $curMappingEle" + ) + ) + .text + + // get the class the tag is combined with + val className = (curMappingEle \ "tag" \ "class").headOption + .getOrElse( + throw BadRequestException( + s"no '' given for node $curMappingEle" + ) + ) + .text + + // get the boolean indicating if the element requires a separator in the text once it is converted to standoff + val separatorBooleanAsString = + (curMappingEle \ "tag" \ "separatesWords").headOption + .getOrElse( + throw BadRequestException( + s"no '' given for node $curMappingEle" + ) + ) + .text + + val separatorRequired: Boolean = stringFormatter.validateBoolean( + separatorBooleanAsString, + throw BadRequestException( + s" could not be converted to Boolean: $separatorBooleanAsString" + ) + ) + + // get the standoff class IRI + val standoffClassIri = + (curMappingEle \ "standoffClass" \ "classIri").headOption + .getOrElse( + throw BadRequestException( + s"no '' given for node $curMappingEle" + ) + ) + .text + + // get a collection containing all the attributes + val attributeNodes: NodeSeq = + curMappingEle \ "standoffClass" \ "attributes" \ "attribute" + + val attributes: Seq[MappingXMLAttribute] = attributeNodes.map { + curAttributeNode => + // get the current attribute's name + val attrName = (curAttributeNode \ "attributeName").headOption + .getOrElse( + throw BadRequestException( + s"no '' given for attribute $curAttributeNode" + ) + ) + .text + + val attributeNamespace = + (curAttributeNode \ "namespace").headOption + .getOrElse( + throw BadRequestException( + s"no '' given for attribute $curAttributeNode" + ) + ) + .text + + // get the standoff property IRI for the current attribute + val propIri = (curAttributeNode \ "propertyIri").headOption + .getOrElse( + throw BadRequestException( + s"no '' given for attribute $curAttributeNode" + ) + ) + .text + + MappingXMLAttribute( + attributeName = stringFormatter.toSparqlEncodedString( + attrName, + throw BadRequestException( + s"tagname $attrName contains invalid characters" + ) + ), + namespace = stringFormatter.toSparqlEncodedString( + attributeNamespace, + throw BadRequestException( + s"tagname $attributeNamespace contains invalid characters" + ) + ), + standoffProperty = stringFormatter.validateAndEscapeIri( + propIri, + throw BadRequestException( + s"standoff class IRI $standoffClassIri is not a valid IRI" + ) + ), + mappingXMLAttributeElementIri = + stringFormatter.makeRandomMappingElementIri(mappingIri) + ) + + } + + // get the optional element datatype + val datatypeMaybe: NodeSeq = + curMappingEle \ "standoffClass" \ "datatype" + + // if "datatype" is given, get the the standoff class data type and the name of the XML data type attribute + val standoffDataTypeOption: Option[MappingStandoffDatatypeClass] = + if (datatypeMaybe.nonEmpty) { + val dataTypeXML = (datatypeMaybe \ "type").headOption + .getOrElse( + throw BadRequestException(s"no '' given for datatype") + ) + .text + + val dataType: StandoffDataTypeClasses.Value = + StandoffDataTypeClasses.lookup( + dataTypeXML, + throw BadRequestException( + s"Invalid data type provided for $tagName" + ) + ) + val dataTypeAttribute: String = + (datatypeMaybe \ "attributeName").headOption + .getOrElse( + throw BadRequestException( + s"no '' given for datatype" + ) + ) + .text + + Some( + MappingStandoffDatatypeClass( + datatype = + dataType.toString, // safe because it is an enumeration + attributeName = stringFormatter.toSparqlEncodedString( + dataTypeAttribute, + throw BadRequestException( + s"tagname $dataTypeAttribute contains invalid characters" + ) + ), + mappingStandoffDataTypeClassElementIri = + stringFormatter.makeRandomMappingElementIri(mappingIri) + ) + ) + } else { + None + } + + MappingElement( + tagName = stringFormatter.toSparqlEncodedString( + tagName, + throw BadRequestException( + s"tagname $tagName contains invalid characters" + ) + ), + namespace = stringFormatter.toSparqlEncodedString( + tagNamespace, + throw BadRequestException( + s"namespace $tagNamespace contains invalid characters" + ) + ), + className = stringFormatter.toSparqlEncodedString( + className, + throw BadRequestException( + s"classname $className contains invalid characters" + ) + ), + standoffClass = stringFormatter.validateAndEscapeIri( + standoffClassIri, + throw BadRequestException( + s"standoff class IRI $standoffClassIri is not a valid IRI" + ) + ), + attributes = attributes, + standoffDataTypeClass = standoffDataTypeOption, + mappingElementIri = + stringFormatter.makeRandomMappingElementIri(mappingIri), + separatorRequired = separatorRequired + ) + + } // transform mappingElements to the structure that is used internally to convert to or from standoff // in order to check for duplicates (checks are done during transformation) mappingXMLToStandoff: MappingXMLtoStandoff = transformMappingElementsToMappingXMLtoStandoff( - mappingElements, - None - ) + mappingElements, + None + ) // get the standoff entities used in the mapping // checks if the standoff classes exist in the ontology @@ -493,55 +576,55 @@ class StandoffResponderV2(responderData: ResponderData) extends Responder(respon // check if the mapping IRI already exists getExistingMappingSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .getMapping( - mappingIri = mappingIri - ) - .toString() + .getMapping( + mappingIri = mappingIri + ) + .toString() existingMappingResponse: SparqlConstructResponse <- (storeManager ? SparqlConstructRequest( - sparql = getExistingMappingSparql, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlConstructResponse] + sparql = getExistingMappingSparql, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlConstructResponse] _ = if (existingMappingResponse.statements.nonEmpty) { - throw BadRequestException(s"mapping IRI $mappingIri already exists") - } + throw BadRequestException(s"mapping IRI $mappingIri already exists") + } createNewMappingSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .createNewMapping( - dataNamedGraph = namedGraph, - mappingIri = mappingIri, - label = label, - defaultXSLTransformation = defaultXSLTransformation, - mappingElements = mappingElements - ) - .toString() + .createNewMapping( + dataNamedGraph = namedGraph, + mappingIri = mappingIri, + label = label, + defaultXSLTransformation = defaultXSLTransformation, + mappingElements = mappingElements + ) + .toString() // Do the update. createResourceResponse: SparqlUpdateResponse <- (storeManager ? SparqlUpdateRequest(createNewMappingSparql)) - .mapTo[SparqlUpdateResponse] + .mapTo[SparqlUpdateResponse] // check if the mapping has been created newMappingResponse <- (storeManager ? SparqlConstructRequest( - sparql = getExistingMappingSparql, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlConstructResponse] + sparql = getExistingMappingSparql, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlConstructResponse] _ = if (newMappingResponse.statements.isEmpty) { - log.error( - s"Attempted a SPARQL update to create a new resource, but it inserted no rows:\n\n$newMappingResponse" - ) - throw UpdateNotPerformedException( - s"Resource $mappingIri was not created. Please report this as a possible bug." - ) - } + log.error( + s"Attempted a SPARQL update to create a new resource, but it inserted no rows:\n\n$newMappingResponse" + ) + throw UpdateNotPerformedException( + s"Resource $mappingIri was not created. Please report this as a possible bug." + ) + } // get the mapping from the triplestore and cache it thereby _ = getMappingFromTriplestore( - mappingIri = mappingIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + mappingIri = mappingIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) } yield { CreateMappingResponseV2( mappingIri = mappingIri, @@ -566,19 +649,19 @@ class StandoffResponderV2(responderData: ResponderData) extends Responder(respon for { // Don't allow anonymous users to create a mapping. userIri: IRI <- Future { - if (requestingUser.isAnonymousUser) { - throw ForbiddenException("Anonymous users aren't allowed to create mappings") - } else { - requestingUser.id - } - } + if (requestingUser.isAnonymousUser) { + throw ForbiddenException("Anonymous users aren't allowed to create mappings") + } else { + requestingUser.id + } + } // check if the given project IRI represents an actual project projectInfoMaybe: Option[ProjectADM] <- (responderManager ? ProjectGetADM( - identifier = ProjectIdentifierADM(maybeIri = Some(projectIri.toString)), - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - )).mapTo[Option[ProjectADM]] + identifier = ProjectIdentifierADM(maybeIri = Some(projectIri.toString)), + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + )).mapTo[Option[ProjectADM]] // TODO: make sure that has sufficient permissions to create a mapping in the given project @@ -586,26 +669,26 @@ class StandoffResponderV2(responderData: ResponderData) extends Responder(respon mappingIri = stringFormatter.makeProjectMappingIri(projectIri.toString, mappingName) _ = if (projectInfoMaybe.isEmpty) - throw BadRequestException(s"Project with Iri ${projectIri.toString} does not exist") + throw BadRequestException(s"Project with Iri ${projectIri.toString} does not exist") // put the mapping into the named graph of the project namedGraph = StringFormatter.getGeneralInstance.projectDataNamedGraphV2(projectInfoMaybe.get) result: CreateMappingResponseV2 <- IriLocker.runWithIriLock( - apiRequestID, - stringFormatter - .createMappingLockIriForProject( - projectIri.toString - ), // use a special project specific IRI to lock the creation of mappings for the given project - () => - createMappingAndCheck( - xml = xml, - label = label, - mappingIri = mappingIri, - namedGraph = namedGraph, - requestingUser = requestingUser - ) - ) + apiRequestID, + stringFormatter + .createMappingLockIriForProject( + projectIri.toString + ), // use a special project specific IRI to lock the creation of mappings for the given project + () => + createMappingAndCheck( + xml = xml, + label = label, + mappingIri = mappingIri, + namedGraph = namedGraph, + requestingUser = requestingUser + ) + ) } yield result @@ -790,10 +873,10 @@ class StandoffResponderV2(responderData: ResponderData) extends Responder(respon case None => for { mapping: MappingXMLtoStandoff <- getMappingFromTriplestore( - mappingIri = mappingIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + mappingIri = mappingIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) entities: StandoffEntityInfoGetResponseV2 <- getStandoffEntitiesFromMappingV2(mapping, requestingUser) @@ -837,14 +920,14 @@ class StandoffResponderV2(responderData: ResponderData) extends Responder(respon for { mappingResponse: SparqlConstructResponse <- (storeManager ? SparqlConstructRequest( - sparql = getMappingSparql, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlConstructResponse] + sparql = getMappingSparql, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlConstructResponse] // if the result is empty, the mapping does not exist _ = if (mappingResponse.statements.isEmpty) { - throw BadRequestException(s"mapping $mappingIri does not exist in triplestore") - } + throw BadRequestException(s"mapping $mappingIri does not exist in triplestore") + } // separate MappingElements from other statements (attributes and datatypes) (mappingElementStatements: Map[IRI, Seq[(IRI, String)]], otherStatements: Map[IRI, Seq[(IRI, String)]]) = @@ -853,64 +936,88 @@ class StandoffResponderV2(responderData: ResponderData) extends Responder(respon } mappingElements: Seq[MappingElement] = mappingElementStatements.map { - case (subjectIri: IRI, assertions: Seq[(IRI, String)]) => - // for convenience (works only for props with cardinality one) - val assertionsAsMap: Map[IRI, String] = assertions.toMap - - // check for attributes - val attributes: Seq[MappingXMLAttribute] = assertions.filter { case (propIri, obj) => - propIri == OntologyConstants.KnoraBase.MappingHasXMLAttribute - }.map { case (attrProp: IRI, attributeElementIri: String) => - val attributeStatementsAsMap: Map[IRI, String] = otherStatements(attributeElementIri).toMap - - MappingXMLAttribute( - attributeName = attributeStatementsAsMap(OntologyConstants.KnoraBase.MappingHasXMLAttributename), - namespace = attributeStatementsAsMap(OntologyConstants.KnoraBase.MappingHasXMLNamespace), - standoffProperty = attributeStatementsAsMap(OntologyConstants.KnoraBase.MappingHasStandoffProperty), - mappingXMLAttributeElementIri = attributeElementIri - ) - } - - // check for standoff data type class - val dataTypeOption: Option[IRI] = - assertionsAsMap.get(OntologyConstants.KnoraBase.MappingHasStandoffDataTypeClass) - - MappingElement( - tagName = assertionsAsMap(OntologyConstants.KnoraBase.MappingHasXMLTagname), - namespace = assertionsAsMap(OntologyConstants.KnoraBase.MappingHasXMLNamespace), - className = assertionsAsMap(OntologyConstants.KnoraBase.MappingHasXMLClass), - standoffClass = assertionsAsMap(OntologyConstants.KnoraBase.MappingHasStandoffClass), - mappingElementIri = subjectIri, - standoffDataTypeClass = dataTypeOption match { - case Some(dataTypeElementIri: IRI) => - val dataTypeAssertionsAsMap: Map[IRI, String] = otherStatements(dataTypeElementIri).toMap - - Some( - MappingStandoffDatatypeClass( - datatype = dataTypeAssertionsAsMap(OntologyConstants.KnoraBase.MappingHasStandoffClass), - attributeName = dataTypeAssertionsAsMap(OntologyConstants.KnoraBase.MappingHasXMLAttributename), - mappingStandoffDataTypeClassElementIri = dataTypeElementIri - ) - ) - case None => None - }, - attributes = attributes, - separatorRequired = assertionsAsMap(OntologyConstants.KnoraBase.MappingElementRequiresSeparator).toBoolean - ) - - }.toSeq + case (subjectIri: IRI, assertions: Seq[(IRI, String)]) => + // for convenience (works only for props with cardinality one) + val assertionsAsMap: Map[IRI, String] = assertions.toMap + + // check for attributes + val attributes: Seq[MappingXMLAttribute] = assertions.filter { + case (propIri, obj) => + propIri == OntologyConstants.KnoraBase.MappingHasXMLAttribute + }.map { case (attrProp: IRI, attributeElementIri: String) => + val attributeStatementsAsMap: Map[IRI, String] = + otherStatements(attributeElementIri).toMap + + MappingXMLAttribute( + attributeName = attributeStatementsAsMap( + OntologyConstants.KnoraBase.MappingHasXMLAttributename + ), + namespace = attributeStatementsAsMap( + OntologyConstants.KnoraBase.MappingHasXMLNamespace + ), + standoffProperty = attributeStatementsAsMap( + OntologyConstants.KnoraBase.MappingHasStandoffProperty + ), + mappingXMLAttributeElementIri = attributeElementIri + ) + } + + // check for standoff data type class + val dataTypeOption: Option[IRI] = + assertionsAsMap.get( + OntologyConstants.KnoraBase.MappingHasStandoffDataTypeClass + ) + + MappingElement( + tagName = + assertionsAsMap(OntologyConstants.KnoraBase.MappingHasXMLTagname), + namespace = assertionsAsMap( + OntologyConstants.KnoraBase.MappingHasXMLNamespace + ), + className = + assertionsAsMap(OntologyConstants.KnoraBase.MappingHasXMLClass), + standoffClass = assertionsAsMap( + OntologyConstants.KnoraBase.MappingHasStandoffClass + ), + mappingElementIri = subjectIri, + standoffDataTypeClass = dataTypeOption match { + case Some(dataTypeElementIri: IRI) => + val dataTypeAssertionsAsMap: Map[IRI, String] = + otherStatements(dataTypeElementIri).toMap + + Some( + MappingStandoffDatatypeClass( + datatype = dataTypeAssertionsAsMap( + OntologyConstants.KnoraBase.MappingHasStandoffClass + ), + attributeName = dataTypeAssertionsAsMap( + OntologyConstants.KnoraBase.MappingHasXMLAttributename + ), + mappingStandoffDataTypeClassElementIri = dataTypeElementIri + ) + ) + case None => None + }, + attributes = attributes, + separatorRequired = assertionsAsMap( + OntologyConstants.KnoraBase.MappingElementRequiresSeparator + ).toBoolean + ) + + }.toSeq // check if there is a default XSL transformation defaultXSLTransformationOption: Option[IRI] = otherStatements(mappingIri).find { case (pred: IRI, obj: String) => - pred == OntologyConstants.KnoraBase.MappingHasDefaultXSLTransformation - }.map { case (hasDefaultTransformation: IRI, xslTransformationIri: IRI) => - xslTransformationIri - } + pred == OntologyConstants.KnoraBase.MappingHasDefaultXSLTransformation + }.map { + case (hasDefaultTransformation: IRI, xslTransformationIri: IRI) => + xslTransformationIri + } mappingXMLToStandoff = transformMappingElementsToMappingXMLtoStandoff( - mappingElements, - defaultXSLTransformationOption - ) + mappingElements, + defaultXSLTransformationOption + ) // add the mapping to the cache _ = CacheUtil.put(cacheName = mappingCacheName, key = mappingIri, value = mappingXMLToStandoff) @@ -960,33 +1067,36 @@ class StandoffResponderV2(responderData: ResponderData) extends Responder(respon for { // request information about standoff classes that should be created - standoffClassEntities: StandoffEntityInfoGetResponseV2 <- (responderManager ? StandoffEntityInfoGetRequestV2( - standoffClassIris = standoffTagIrisFromMapping.map(_.toSmartIri), - requestingUser = requestingUser - )).mapTo[StandoffEntityInfoGetResponseV2] + standoffClassEntities: StandoffEntityInfoGetResponseV2 <- + (responderManager ? StandoffEntityInfoGetRequestV2( + standoffClassIris = standoffTagIrisFromMapping.map(_.toSmartIri), + requestingUser = requestingUser + )).mapTo[StandoffEntityInfoGetResponseV2] // check that the ontology responder returned the information for all the standoff classes it was asked for // if the ontology responder does not return a standoff class it was asked for, then this standoff class does not exist _ = if (standoffTagIrisFromMapping.map(_.toSmartIri) != standoffClassEntities.standoffClassInfoMap.keySet) { - throw NotFoundException( - s"the ontology responder could not find information about these standoff classes: ${(standoffTagIrisFromMapping - .map(_.toSmartIri) -- standoffClassEntities.standoffClassInfoMap.keySet).mkString(", ")}" - ) - } + throw NotFoundException( + s"the ontology responder could not find information about these standoff classes: ${(standoffTagIrisFromMapping + .map(_.toSmartIri) -- standoffClassEntities.standoffClassInfoMap.keySet).mkString(", ")}" + ) + } // get the property Iris that are defined on the standoff classes returned by the ontology responder - standoffPropertyIrisFromOntologyResponder: Set[SmartIri] = standoffClassEntities.standoffClassInfoMap.foldLeft( - Set.empty[SmartIri] - ) { case (acc, (standoffClassIri, standoffClassEntity: ReadClassInfoV2)) => - val props = standoffClassEntity.allCardinalities.keySet - acc ++ props - } + standoffPropertyIrisFromOntologyResponder: Set[SmartIri] = + standoffClassEntities.standoffClassInfoMap.foldLeft( + Set.empty[SmartIri] + ) { case (acc, (standoffClassIri, standoffClassEntity: ReadClassInfoV2)) => + val props = standoffClassEntity.allCardinalities.keySet + acc ++ props + } // request information about the standoff properties - standoffPropertyEntities: StandoffEntityInfoGetResponseV2 <- (responderManager ? StandoffEntityInfoGetRequestV2( - standoffPropertyIris = standoffPropertyIrisFromOntologyResponder, - requestingUser = requestingUser - )).mapTo[StandoffEntityInfoGetResponseV2] + standoffPropertyEntities: StandoffEntityInfoGetResponseV2 <- + (responderManager ? StandoffEntityInfoGetRequestV2( + standoffPropertyIris = standoffPropertyIrisFromOntologyResponder, + requestingUser = requestingUser + )).mapTo[StandoffEntityInfoGetResponseV2] // check that the ontology responder returned the information for all the standoff properties it was asked for // if the ontology responder does not return a standoff property it was asked for, then this standoff property does not exist @@ -995,71 +1105,71 @@ class StandoffResponderV2(responderData: ResponderData) extends Responder(respon .intersect(standoffPropertyIrisFromMapping.map(_.toSmartIri)) _ = if (standoffPropertyIrisFromMapping.map(_.toSmartIri) != propertyDefinitionsFromMappingFoundInOntology) { - throw NotFoundException( - s"the ontology responder could not find information about these standoff properties: " + - s"${(standoffPropertyIrisFromMapping.map(_.toSmartIri) -- propertyDefinitionsFromMappingFoundInOntology) - .mkString(", ")}" - ) - } + throw NotFoundException( + s"the ontology responder could not find information about these standoff properties: " + + s"${(standoffPropertyIrisFromMapping.map(_.toSmartIri) -- propertyDefinitionsFromMappingFoundInOntology) + .mkString(", ")}" + ) + } // check that for each standoff property defined in the mapping element for a standoff class, a corresponding cardinality exists in the ontology _ = mappingStandoffToXML.foreach { case (standoffClass: IRI, xmlTag: XMLTagItem) => - // collect all the standoff properties defined for this standoff class - val standoffPropertiesForStandoffClass: Set[SmartIri] = xmlTag.attributes.keySet.map(_.toSmartIri) - - // check that the current standoff class has cardinalities for all the properties defined - val cardinalitiesFound = standoffClassEntities - .standoffClassInfoMap(standoffClass.toSmartIri) - .allCardinalities - .keySet - .intersect(standoffPropertiesForStandoffClass) - - if (standoffPropertiesForStandoffClass != cardinalitiesFound) { - throw NotFoundException( - s"the following standoff properties have no cardinality for $standoffClass: ${(standoffPropertiesForStandoffClass -- cardinalitiesFound) - .mkString(", ")}" - ) - } - - // collect the required standoff properties for the standoff class - val requiredPropsForClass: Set[SmartIri] = standoffClassEntities - .standoffClassInfoMap(standoffClass.toSmartIri) - .allCardinalities - .filter { case (property: SmartIri, card: KnoraCardinalityInfo) => - card.cardinality == Cardinality.MustHaveOne || card.cardinality == Cardinality.MustHaveSome - } - .keySet -- StandoffProperties.systemProperties.map(_.toSmartIri) -- StandoffProperties.dataTypeProperties - .map(_.toSmartIri) - - // check that all the required standoff properties exist in the mapping - if (standoffPropertiesForStandoffClass.intersect(requiredPropsForClass) != requiredPropsForClass) { - throw NotFoundException( - s"the following required standoff properties are not defined for the standoff class $standoffClass: ${(requiredPropsForClass -- standoffPropertiesForStandoffClass) - .mkString(", ")}" - ) - } - - // check if the standoff class's data type is correct in the mapping - standoffClassEntities.standoffClassInfoMap(standoffClass.toSmartIri).standoffDataType match { - case Some(dataType: StandoffDataTypeClasses.Value) => - // check if this corresponds to the datatype in the mapping - val dataTypeFromMapping: XMLStandoffDataTypeClass = xmlTag.tagItem.mapping.dataType.getOrElse( - throw InvalidStandoffException(s"no data type provided for $standoffClass, but $dataType required") - ) - if (dataTypeFromMapping.standoffDataTypeClass != dataType) { - throw InvalidStandoffException( - s"wrong data type ${dataTypeFromMapping.standoffDataTypeClass} provided for $standoffClass, but $dataType required" + // collect all the standoff properties defined for this standoff class + val standoffPropertiesForStandoffClass: Set[SmartIri] = xmlTag.attributes.keySet.map(_.toSmartIri) + + // check that the current standoff class has cardinalities for all the properties defined + val cardinalitiesFound = standoffClassEntities + .standoffClassInfoMap(standoffClass.toSmartIri) + .allCardinalities + .keySet + .intersect(standoffPropertiesForStandoffClass) + + if (standoffPropertiesForStandoffClass != cardinalitiesFound) { + throw NotFoundException( + s"the following standoff properties have no cardinality for $standoffClass: ${(standoffPropertiesForStandoffClass -- cardinalitiesFound) + .mkString(", ")}" ) } - case None => - if (xmlTag.tagItem.mapping.dataType.nonEmpty) { - throw InvalidStandoffException( - s"no data type expected for $standoffClass, but ${xmlTag.tagItem.mapping.dataType.get.standoffDataTypeClass} given" + + // collect the required standoff properties for the standoff class + val requiredPropsForClass: Set[SmartIri] = standoffClassEntities + .standoffClassInfoMap(standoffClass.toSmartIri) + .allCardinalities + .filter { case (property: SmartIri, card: KnoraCardinalityInfo) => + card.cardinality == Cardinality.MustHaveOne || card.cardinality == Cardinality.MustHaveSome + } + .keySet -- StandoffProperties.systemProperties.map(_.toSmartIri) -- StandoffProperties.dataTypeProperties + .map(_.toSmartIri) + + // check that all the required standoff properties exist in the mapping + if (standoffPropertiesForStandoffClass.intersect(requiredPropsForClass) != requiredPropsForClass) { + throw NotFoundException( + s"the following required standoff properties are not defined for the standoff class $standoffClass: ${(requiredPropsForClass -- standoffPropertiesForStandoffClass) + .mkString(", ")}" ) } - } - } + // check if the standoff class's data type is correct in the mapping + standoffClassEntities.standoffClassInfoMap(standoffClass.toSmartIri).standoffDataType match { + case Some(dataType: StandoffDataTypeClasses.Value) => + // check if this corresponds to the datatype in the mapping + val dataTypeFromMapping: XMLStandoffDataTypeClass = xmlTag.tagItem.mapping.dataType.getOrElse( + throw InvalidStandoffException(s"no data type provided for $standoffClass, but $dataType required") + ) + if (dataTypeFromMapping.standoffDataTypeClass != dataType) { + throw InvalidStandoffException( + s"wrong data type ${dataTypeFromMapping.standoffDataTypeClass} provided for $standoffClass, but $dataType required" + ) + } + case None => + if (xmlTag.tagItem.mapping.dataType.nonEmpty) { + throw InvalidStandoffException( + s"no data type expected for $standoffClass, but ${xmlTag.tagItem.mapping.dataType.get.standoffDataTypeClass} given" + ) + } + } + + } } yield StandoffEntityInfoGetResponseV2( standoffClassInfoMap = standoffClassEntities.standoffClassInfoMap, @@ -1106,22 +1216,22 @@ class StandoffResponderV2(responderData: ResponderData) extends Responder(respon for { // Get a page of standoff. standoffResponse <- getStandoffV2( - GetStandoffPageRequestV2( - resourceIri = resourceIri, - valueIri = valueIri, - offset = offset, - targetSchema = ApiV2Complex, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) - ) + GetStandoffPageRequestV2( + resourceIri = resourceIri, + valueIri = valueIri, + offset = offset, + targetSchema = ApiV2Complex, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) + ) // Add it to the standoff that has already been collected. collectedStandoff = previousResult match { - case Some(definedPreviousResult) => - definedPreviousResult.underlyingResult.standoff ++ standoffResponse.standoff - case None => standoffResponse.standoff.toVector - } + case Some(definedPreviousResult) => + definedPreviousResult.underlyingResult.standoff ++ standoffResponse.standoff + case None => standoffResponse.standoff.toVector + } } yield standoffResponse.nextOffset match { case Some(definedNextOffset) => // There is more standoff to query. Return the collected standoff and the next task. diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v2/ValuesResponderV2.scala b/webapi/src/main/scala/org/knora/webapi/responders/v2/ValuesResponderV2.scala index 21a4f444fd..4bc26fdbfb 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/v2/ValuesResponderV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v2/ValuesResponderV2.scala @@ -74,53 +74,59 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde def makeTaskFuture: Future[CreateValueResponseV2] = { for { // Convert the submitted value to the internal schema. - submittedInternalPropertyIri: SmartIri <- Future( - createValueRequest.createValue.propertyIri.toOntologySchema(InternalSchema) - ) + submittedInternalPropertyIri: SmartIri <- + Future( + createValueRequest.createValue.propertyIri.toOntologySchema(InternalSchema) + ) submittedInternalValueContent: ValueContentV2 = createValueRequest.createValue.valueContent - .toOntologySchema(InternalSchema) + .toOntologySchema(InternalSchema) // Get ontology information about the submitted property. propertyInfoRequestForSubmittedProperty = PropertiesGetRequestV2( - propertyIris = Set(submittedInternalPropertyIri), - allLanguages = false, - requestingUser = createValueRequest.requestingUser - ) + propertyIris = Set(submittedInternalPropertyIri), + allLanguages = false, + requestingUser = createValueRequest.requestingUser + ) propertyInfoResponseForSubmittedProperty: ReadOntologyV2 <- (responderManager ? propertyInfoRequestForSubmittedProperty) .mapTo[ReadOntologyV2] propertyInfoForSubmittedProperty: ReadPropertyInfoV2 = propertyInfoResponseForSubmittedProperty.properties( - submittedInternalPropertyIri - ) + submittedInternalPropertyIri + ) // Don't accept link properties. _ = if (propertyInfoForSubmittedProperty.isLinkProp) { - throw BadRequestException( - s"Invalid property <${createValueRequest.createValue.propertyIri}>. Use a link value property to submit a link." - ) - } + throw BadRequestException( + s"Invalid property <${createValueRequest.createValue.propertyIri}>. Use a link value property to submit a link." + ) + } // Don't accept knora-api:hasStandoffLinkToValue. - _ = if ( - createValueRequest.createValue.propertyIri.toString == OntologyConstants.KnoraApiV2Complex.HasStandoffLinkToValue - ) { - throw BadRequestException( - s"Values of <${createValueRequest.createValue.propertyIri}> cannot be created directly" - ) - } + _ = + if ( + createValueRequest.createValue.propertyIri.toString == OntologyConstants.KnoraApiV2Complex.HasStandoffLinkToValue + ) { + throw BadRequestException( + s"Values of <${createValueRequest.createValue.propertyIri}> cannot be created directly" + ) + } // Make an adjusted version of the submitted property: if it's a link value property, substitute the // corresponding link property, whose objects we will need to query. Get ontology information about the // adjusted property. adjustedInternalPropertyInfo: ReadPropertyInfoV2 <- getAdjustedInternalPropertyInfo( - submittedPropertyIri = createValueRequest.createValue.propertyIri, - maybeSubmittedValueType = Some(createValueRequest.createValue.valueContent.valueType), - propertyInfoForSubmittedProperty = propertyInfoForSubmittedProperty, - requestingUser = createValueRequest.requestingUser - ) + submittedPropertyIri = + createValueRequest.createValue.propertyIri, + maybeSubmittedValueType = Some( + createValueRequest.createValue.valueContent.valueType + ), + propertyInfoForSubmittedProperty = + propertyInfoForSubmittedProperty, + requestingUser = createValueRequest.requestingUser + ) adjustedInternalPropertyIri = adjustedInternalPropertyInfo.entityInfoContent.propertyIri @@ -128,39 +134,39 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde // so we can see objects that the user doesn't have permission to see. resourceInfo: ReadResourceV2 <- getResourceWithPropertyValues( - resourceIri = createValueRequest.createValue.resourceIri, - propertyInfo = adjustedInternalPropertyInfo, - featureFactoryConfig = createValueRequest.featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + resourceIri = createValueRequest.createValue.resourceIri, + propertyInfo = adjustedInternalPropertyInfo, + featureFactoryConfig = createValueRequest.featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) // Check that the user has permission to modify the resource. _ = ResourceUtilV2.checkResourcePermission( - resourceInfo = resourceInfo, - permissionNeeded = ModifyPermission, - requestingUser = createValueRequest.requestingUser - ) + resourceInfo = resourceInfo, + permissionNeeded = ModifyPermission, + requestingUser = createValueRequest.requestingUser + ) // Check that the resource has the rdf:type that the client thinks it has. _ = if ( - resourceInfo.resourceClassIri != createValueRequest.createValue.resourceClassIri.toOntologySchema( - InternalSchema - ) - ) { - throw BadRequestException( - s"The rdf:type of resource <${createValueRequest.createValue.resourceIri}> is not <${createValueRequest.createValue.resourceClassIri}>" - ) - } + resourceInfo.resourceClassIri != createValueRequest.createValue.resourceClassIri.toOntologySchema( + InternalSchema + ) + ) { + throw BadRequestException( + s"The rdf:type of resource <${createValueRequest.createValue.resourceIri}> is not <${createValueRequest.createValue.resourceClassIri}>" + ) + } // Get the definition of the resource class. classInfoRequest = ClassesGetRequestV2( - classIris = Set(resourceInfo.resourceClassIri), - allLanguages = false, - requestingUser = createValueRequest.requestingUser - ) + classIris = Set(resourceInfo.resourceClassIri), + allLanguages = false, + requestingUser = createValueRequest.requestingUser + ) classInfoResponse: ReadOntologyV2 <- (responderManager ? classInfoRequest).mapTo[ReadOntologyV2] @@ -168,158 +174,162 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde classInfo: ReadClassInfoV2 = classInfoResponse.classes(resourceInfo.resourceClassIri) cardinalityInfo: Cardinality.KnoraCardinalityInfo = classInfo.allCardinalities.getOrElse( - submittedInternalPropertyIri, - throw BadRequestException( - s"Resource <${createValueRequest.createValue.resourceIri}> belongs to class <${resourceInfo.resourceClassIri - .toOntologySchema(ApiV2Complex)}>, which has no cardinality for property <${createValueRequest.createValue.propertyIri}>" - ) - ) + submittedInternalPropertyIri, + throw BadRequestException( + s"Resource <${createValueRequest.createValue.resourceIri}> belongs to class <${resourceInfo.resourceClassIri + .toOntologySchema(ApiV2Complex)}>, which has no cardinality for property <${createValueRequest.createValue.propertyIri}>" + ) + ) // Check that the object of the adjusted property (the value to be created, or the target of the link to be created) will have // the correct type for the adjusted property's knora-base:objectClassConstraint. _ <- checkPropertyObjectClassConstraint( - propertyInfo = adjustedInternalPropertyInfo, - valueContent = submittedInternalValueContent, - featureFactoryConfig = createValueRequest.featureFactoryConfig, - requestingUser = createValueRequest.requestingUser - ) + propertyInfo = adjustedInternalPropertyInfo, + valueContent = submittedInternalValueContent, + featureFactoryConfig = createValueRequest.featureFactoryConfig, + requestingUser = createValueRequest.requestingUser + ) // If this is a list value, check that it points to a real list node. _ <- submittedInternalValueContent match { - case listValue: HierarchicalListValueContentV2 => - ResourceUtilV2.checkListNodeExists(listValue.valueHasListNode, storeManager) - case _ => FastFuture.successful(()) - } + case listValue: HierarchicalListValueContentV2 => + ResourceUtilV2.checkListNodeExists(listValue.valueHasListNode, storeManager) + case _ => FastFuture.successful(()) + } // Check that the resource class's cardinality for the submitted property allows another value to be added // for that property. currentValuesForProp: Seq[ReadValueV2] = resourceInfo.values - .getOrElse(submittedInternalPropertyIri, Seq.empty[ReadValueV2]) + .getOrElse(submittedInternalPropertyIri, Seq.empty[ReadValueV2]) - _ = if ( - (cardinalityInfo.cardinality == Cardinality.MustHaveOne || cardinalityInfo.cardinality == Cardinality.MustHaveSome) && currentValuesForProp.isEmpty - ) { - throw InconsistentRepositoryDataException( - s"Resource class <${resourceInfo.resourceClassIri - .toOntologySchema(ApiV2Complex)}> has a cardinality of ${cardinalityInfo.cardinality} on property <${createValueRequest.createValue.propertyIri}>, but resource <${createValueRequest.createValue.resourceIri}> has no value for that property" - ) - } + _ = + if ( + (cardinalityInfo.cardinality == Cardinality.MustHaveOne || cardinalityInfo.cardinality == Cardinality.MustHaveSome) && currentValuesForProp.isEmpty + ) { + throw InconsistentRepositoryDataException( + s"Resource class <${resourceInfo.resourceClassIri + .toOntologySchema(ApiV2Complex)}> has a cardinality of ${cardinalityInfo.cardinality} on property <${createValueRequest.createValue.propertyIri}>, but resource <${createValueRequest.createValue.resourceIri}> has no value for that property" + ) + } - _ = if ( - cardinalityInfo.cardinality == Cardinality.MustHaveOne || (cardinalityInfo.cardinality == Cardinality.MayHaveOne && currentValuesForProp.nonEmpty) - ) { - throw OntologyConstraintException( - s"Resource class <${resourceInfo.resourceClassIri - .toOntologySchema(ApiV2Complex)}> has a cardinality of ${cardinalityInfo.cardinality} on property <${createValueRequest.createValue.propertyIri}>, and this does not allow a value to be added for that property to resource <${createValueRequest.createValue.resourceIri}>" - ) - } + _ = + if ( + cardinalityInfo.cardinality == Cardinality.MustHaveOne || (cardinalityInfo.cardinality == Cardinality.MayHaveOne && currentValuesForProp.nonEmpty) + ) { + throw OntologyConstraintException( + s"Resource class <${resourceInfo.resourceClassIri + .toOntologySchema(ApiV2Complex)}> has a cardinality of ${cardinalityInfo.cardinality} on property <${createValueRequest.createValue.propertyIri}>, and this does not allow a value to be added for that property to resource <${createValueRequest.createValue.resourceIri}>" + ) + } // Check that the new value would not duplicate an existing value. unescapedSubmittedInternalValueContent = submittedInternalValueContent.unescape _ = if ( - currentValuesForProp.exists(currentVal => - unescapedSubmittedInternalValueContent.wouldDuplicateOtherValue(currentVal.valueContent) - ) - ) { - throw DuplicateValueException() - } + currentValuesForProp.exists(currentVal => + unescapedSubmittedInternalValueContent.wouldDuplicateOtherValue(currentVal.valueContent) + ) + ) { + throw DuplicateValueException() + } // If this is a text value, check that the resources pointed to by any standoff link tags exist // and that the user has permission to see them. _ <- submittedInternalValueContent match { - case textValueContent: TextValueContentV2 => - checkResourceIris( - targetResourceIris = textValueContent.standoffLinkTagTargetResourceIris, - featureFactoryConfig = createValueRequest.featureFactoryConfig, - requestingUser = createValueRequest.requestingUser - ) + case textValueContent: TextValueContentV2 => + checkResourceIris( + targetResourceIris = textValueContent.standoffLinkTagTargetResourceIris, + featureFactoryConfig = createValueRequest.featureFactoryConfig, + requestingUser = createValueRequest.requestingUser + ) - case _ => FastFuture.successful(()) - } + case _ => FastFuture.successful(()) + } // Get the default permissions for the new value. defaultValuePermissions: String <- ResourceUtilV2.getDefaultValuePermissions( - projectIri = resourceInfo.projectADM.id, - resourceClassIri = resourceInfo.resourceClassIri, - propertyIri = submittedInternalPropertyIri, - requestingUser = createValueRequest.requestingUser, - responderManager = responderManager - ) + projectIri = resourceInfo.projectADM.id, + resourceClassIri = resourceInfo.resourceClassIri, + propertyIri = submittedInternalPropertyIri, + requestingUser = createValueRequest.requestingUser, + responderManager = responderManager + ) // Did the user submit permissions for the new value? newValuePermissionLiteral <- createValueRequest.createValue.permissions match { - case Some(permissions: String) => - // Yes. Validate them. - for { - validatedCustomPermissions <- PermissionUtilADM.validatePermissions( - permissionLiteral = permissions, - featureFactoryConfig = createValueRequest.featureFactoryConfig, - responderManager = responderManager - ) - - // Is the requesting user a system admin, or an admin of this project? - _ = if ( - !(createValueRequest.requestingUser.permissions.isProjectAdmin( - createValueRequest.requestingUser.id - ) || createValueRequest.requestingUser.permissions.isSystemAdmin) - ) { - - // No. Make sure they don't give themselves higher permissions than they would get from the default permissions. - - val permissionComparisonResult: PermissionComparisonResult = PermissionUtilADM.comparePermissionsADM( - entityCreator = createValueRequest.requestingUser.id, - entityProject = resourceInfo.projectADM.id, - permissionLiteralA = validatedCustomPermissions, - permissionLiteralB = defaultValuePermissions, - requestingUser = createValueRequest.requestingUser - ) - - if (permissionComparisonResult == AGreaterThanB) { - throw ForbiddenException( - s"The specified value permissions would give a value's creator a higher permission on the value than the default permissions" - ) - } - } - } yield validatedCustomPermissions - - case None => - // No. Use the default permissions. - FastFuture.successful(defaultValuePermissions) - } + case Some(permissions: String) => + // Yes. Validate them. + for { + validatedCustomPermissions <- PermissionUtilADM.validatePermissions( + permissionLiteral = permissions, + featureFactoryConfig = + createValueRequest.featureFactoryConfig, + responderManager = responderManager + ) + + // Is the requesting user a system admin, or an admin of this project? + _ = if ( + !(createValueRequest.requestingUser.permissions.isProjectAdmin( + createValueRequest.requestingUser.id + ) || createValueRequest.requestingUser.permissions.isSystemAdmin) + ) { + + // No. Make sure they don't give themselves higher permissions than they would get from the default permissions. + + val permissionComparisonResult: PermissionComparisonResult = + PermissionUtilADM.comparePermissionsADM( + entityCreator = createValueRequest.requestingUser.id, + entityProject = resourceInfo.projectADM.id, + permissionLiteralA = validatedCustomPermissions, + permissionLiteralB = defaultValuePermissions, + requestingUser = createValueRequest.requestingUser + ) + + if (permissionComparisonResult == AGreaterThanB) { + throw ForbiddenException( + s"The specified value permissions would give a value's creator a higher permission on the value than the default permissions" + ) + } + } + } yield validatedCustomPermissions + + case None => + // No. Use the default permissions. + FastFuture.successful(defaultValuePermissions) + } dataNamedGraph: IRI = stringFormatter.projectDataNamedGraphV2(resourceInfo.projectADM) // Create the new value. unverifiedValue <- createValueV2AfterChecks( - dataNamedGraph = dataNamedGraph, - projectIri = resourceInfo.projectADM.id, - resourceInfo = resourceInfo, - propertyIri = adjustedInternalPropertyIri, - value = submittedInternalValueContent, - valueIri = createValueRequest.createValue.valueIri, - valueUUID = createValueRequest.createValue.valueUUID, - valueCreationDate = createValueRequest.createValue.valueCreationDate, - valueCreator = createValueRequest.requestingUser.id, - valuePermissions = newValuePermissionLiteral, - requestingUser = createValueRequest.requestingUser - ) + dataNamedGraph = dataNamedGraph, + projectIri = resourceInfo.projectADM.id, + resourceInfo = resourceInfo, + propertyIri = adjustedInternalPropertyIri, + value = submittedInternalValueContent, + valueIri = createValueRequest.createValue.valueIri, + valueUUID = createValueRequest.createValue.valueUUID, + valueCreationDate = createValueRequest.createValue.valueCreationDate, + valueCreator = createValueRequest.requestingUser.id, + valuePermissions = newValuePermissionLiteral, + requestingUser = createValueRequest.requestingUser + ) // Check that the value was written correctly to the triplestore. verifiedValue: VerifiedValueV2 <- verifyValue( - resourceIri = createValueRequest.createValue.resourceIri, - propertyIri = submittedInternalPropertyIri, - unverifiedValue = unverifiedValue, - featureFactoryConfig = createValueRequest.featureFactoryConfig, - requestingUser = createValueRequest.requestingUser - ) + resourceIri = createValueRequest.createValue.resourceIri, + propertyIri = submittedInternalPropertyIri, + unverifiedValue = unverifiedValue, + featureFactoryConfig = createValueRequest.featureFactoryConfig, + requestingUser = createValueRequest.requestingUser + ) } yield CreateValueResponseV2( valueIri = verifiedValue.newValueIri, valueType = verifiedValue.value.valueType, @@ -333,19 +343,19 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde // Don't allow anonymous users to create values. _ <- Future { - if (createValueRequest.requestingUser.isAnonymousUser) { - throw ForbiddenException("Anonymous users aren't allowed to create values") - } else { - createValueRequest.requestingUser.id - } - } + if (createValueRequest.requestingUser.isAnonymousUser) { + throw ForbiddenException("Anonymous users aren't allowed to create values") + } else { + createValueRequest.requestingUser.id + } + } // Do the remaining pre-update checks and the update while holding an update lock on the resource. taskResult <- IriLocker.runWithIriLock( - createValueRequest.apiRequestID, - createValueRequest.createValue.resourceIri, - () => makeTaskFuture - ) + createValueRequest.apiRequestID, + createValueRequest.createValue.resourceIri, + () => makeTaskFuture + ) } yield taskResult // Since PR #1230, the cardinalities in knora-base don't allow you to create a file value @@ -459,53 +469,53 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde // Make an IRI for the new value. newValueIri: IRI <- checkOrCreateEntityIri( - maybeValueIri, - stringFormatter.makeRandomValueIri(resourceInfo.resourceIri, Some(newValueUUID)) - ) + maybeValueIri, + stringFormatter.makeRandomValueIri(resourceInfo.resourceIri, Some(newValueUUID)) + ) // Make a creation date for the new value creationDate: Instant = maybeValueCreationDate match { - case Some(customCreationDate) => customCreationDate - case None => Instant.now - } + case Some(customCreationDate) => customCreationDate + case None => Instant.now + } // If we're creating a text value, update direct links and LinkValues for any resource references in standoff. standoffLinkUpdates <- value match { - case textValueContent: TextValueContentV2 => - // Construct a SparqlTemplateLinkUpdate for each reference that was added. - val linkUpdateFutures: Seq[Future[SparqlTemplateLinkUpdate]] = - textValueContent.standoffLinkTagTargetResourceIris.map { targetResourceIri: IRI => - incrementLinkValue( - sourceResourceInfo = resourceInfo, - linkPropertyIri = OntologyConstants.KnoraBase.HasStandoffLinkTo.toSmartIri, - targetResourceIri = targetResourceIri, - valueCreator = OntologyConstants.KnoraAdmin.SystemUser, - valuePermissions = standoffLinkValuePermissions, - requestingUser = requestingUser - ) - }.toVector - - Future.sequence(linkUpdateFutures) - - case _ => FastFuture.successful(Vector.empty[SparqlTemplateLinkUpdate]) - } + case textValueContent: TextValueContentV2 => + // Construct a SparqlTemplateLinkUpdate for each reference that was added. + val linkUpdateFutures: Seq[Future[SparqlTemplateLinkUpdate]] = + textValueContent.standoffLinkTagTargetResourceIris.map { targetResourceIri: IRI => + incrementLinkValue( + sourceResourceInfo = resourceInfo, + linkPropertyIri = OntologyConstants.KnoraBase.HasStandoffLinkTo.toSmartIri, + targetResourceIri = targetResourceIri, + valueCreator = OntologyConstants.KnoraAdmin.SystemUser, + valuePermissions = standoffLinkValuePermissions, + requestingUser = requestingUser + ) + }.toVector + + Future.sequence(linkUpdateFutures) + + case _ => FastFuture.successful(Vector.empty[SparqlTemplateLinkUpdate]) + } // Generate a SPARQL update string. sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .createValue( - dataNamedGraph = dataNamedGraph, - resourceIri = resourceInfo.resourceIri, - propertyIri = propertyIri, - newValueIri = newValueIri, - newValueUUID = newValueUUID, - value = value, - linkUpdates = standoffLinkUpdates, - valueCreator = valueCreator, - valuePermissions = valuePermissions, - creationDate = creationDate, - stringFormatter = stringFormatter - ) - .toString() + .createValue( + dataNamedGraph = dataNamedGraph, + resourceIri = resourceInfo.resourceIri, + propertyIri = propertyIri, + newValueIri = newValueIri, + newValueUUID = newValueUUID, + value = value, + linkUpdates = standoffLinkUpdates, + valueCreator = valueCreator, + valuePermissions = valuePermissions, + creationDate = creationDate, + stringFormatter = stringFormatter + ) + .toString() /* _ = println("================ Create value ================") @@ -554,32 +564,32 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde for { sparqlTemplateLinkUpdate <- incrementLinkValue( - sourceResourceInfo = resourceInfo, - linkPropertyIri = linkPropertyIri, - targetResourceIri = linkValueContent.referredResourceIri, - customNewLinkValueIri = maybeValueIri, - valueCreator = valueCreator, - valuePermissions = valuePermissions, - requestingUser = requestingUser - ) + sourceResourceInfo = resourceInfo, + linkPropertyIri = linkPropertyIri, + targetResourceIri = linkValueContent.referredResourceIri, + customNewLinkValueIri = maybeValueIri, + valueCreator = valueCreator, + valuePermissions = valuePermissions, + requestingUser = requestingUser + ) creationDate: Instant = maybeCreationDate match { - case Some(customValueCreationDate) => customValueCreationDate - case None => Instant.now - } + case Some(customValueCreationDate) => customValueCreationDate + case None => Instant.now + } // Generate a SPARQL update string. sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .createLink( - dataNamedGraph = dataNamedGraph, - resourceIri = resourceInfo.resourceIri, - linkUpdate = sparqlTemplateLinkUpdate, - newValueUUID = newValueUUID, - creationDate = creationDate, - maybeComment = linkValueContent.comment, - stringFormatter = stringFormatter - ) - .toString() + .createLink( + dataNamedGraph = dataNamedGraph, + resourceIri = resourceInfo.resourceIri, + linkUpdate = sparqlTemplateLinkUpdate, + newValueUUID = newValueUUID, + creationDate = creationDate, + maybeComment = linkValueContent.comment, + stringFormatter = stringFormatter + ) + .toString() /* _ = println("================ Create link ===============") @@ -619,8 +629,8 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde for { // Generate SPARQL to create links and LinkValues for standoff links in text values. sparqlForStandoffLinks: Option[String] <- generateInsertSparqlForStandoffLinksInMultipleValues( - createMultipleValuesRequest - ) + createMultipleValuesRequest + ) // Generate SPARQL for each value. sparqlForPropertyValueFutures: Map[SmartIri, Seq[Future[InsertSparqlWithUnverifiedValue]]] = @@ -640,19 +650,21 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde } sparqlForPropertyValues: Map[SmartIri, Seq[InsertSparqlWithUnverifiedValue]] <- ActorUtil.sequenceSeqFuturesInMap( - sparqlForPropertyValueFutures - ) + sparqlForPropertyValueFutures + ) // Concatenate all the generated SPARQL. allInsertSparql: String = sparqlForPropertyValues.values.flatten - .map(_.insertSparql) - .mkString("\n\n") + "\n\n" + sparqlForStandoffLinks.getOrElse("") + .map(_.insertSparql) + .mkString("\n\n") + "\n\n" + sparqlForStandoffLinks.getOrElse("") // Collect all the unverified values. unverifiedValues: Map[SmartIri, Seq[UnverifiedValueV2]] = sparqlForPropertyValues.map { - case (propertyIri, unverifiedValuesWithSparql) => - propertyIri -> unverifiedValuesWithSparql.map(_.unverifiedValue) - } + case (propertyIri, unverifiedValuesWithSparql) => + propertyIri -> unverifiedValuesWithSparql.map( + _.unverifiedValue + ) + } } yield GenerateSparqlToCreateMultipleValuesResponseV2( insertSparql = allInsertSparql, unverifiedValues = unverifiedValues, @@ -681,76 +693,76 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde for { // Make new value UUID. newValueUUID: UUID <- Future.successful( - makeNewValueUUID(valueToCreate.customValueIri, valueToCreate.customValueUUID) - ) + makeNewValueUUID(valueToCreate.customValueIri, valueToCreate.customValueUUID) + ) newValueIri: IRI <- checkOrCreateEntityIri( - valueToCreate.customValueIri, - stringFormatter.makeRandomValueIri(resourceIri, Some(newValueUUID)) - ) + valueToCreate.customValueIri, + stringFormatter.makeRandomValueIri(resourceIri, Some(newValueUUID)) + ) // Make a creation date for the value. If a custom creation date is given for a value, consider that otherwise // use resource creation date for the value. valueCreationDate: Instant = valueToCreate.customValueCreationDate match { - case Some(customValueCreationDate) => customValueCreationDate - case None => resourceCreationDate - } + case Some(customValueCreationDate) => customValueCreationDate + case None => resourceCreationDate + } // Generate the SPARQL. insertSparql: String = valueToCreate.valueContent match { - case linkValueContentV2: LinkValueContentV2 => - // We're creating a link. - - // Construct a SparqlTemplateLinkUpdate to tell the SPARQL template how to create - // the link and its LinkValue. - val sparqlTemplateLinkUpdate = SparqlTemplateLinkUpdate( - linkPropertyIri = propertyIri.fromLinkValuePropToLinkProp, - directLinkExists = false, - insertDirectLink = true, - deleteDirectLink = false, - linkValueExists = false, - linkTargetExists = linkValueContentV2.referredResourceExists, - newLinkValueIri = newValueIri, - linkTargetIri = linkValueContentV2.referredResourceIri, - currentReferenceCount = 0, - newReferenceCount = 1, - newLinkValueCreator = requestingUser.id, - newLinkValuePermissions = valueToCreate.permissions - ) - - // Generate SPARQL for the link. - org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .generateInsertStatementsForCreateLink( - resourceIri = resourceIri, - linkUpdate = sparqlTemplateLinkUpdate, - creationDate = valueCreationDate, - newValueUUID = newValueUUID, - maybeComment = valueToCreate.valueContent.comment, - maybeValueHasOrder = Some(valueHasOrder), - stringFormatter = stringFormatter - ) - .toString() - - case otherValueContentV2 => - // We're creating an ordinary value. Generate SPARQL for it. - org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .generateInsertStatementsForCreateValue( - resourceIri = resourceIri, - propertyIri = propertyIri, - value = otherValueContentV2, - newValueIri = newValueIri, - newValueUUID = newValueUUID, - linkUpdates = Seq.empty[ - SparqlTemplateLinkUpdate - ], // This is empty because we have to generate SPARQL for standoff links separately. - valueCreator = requestingUser.id, - valuePermissions = valueToCreate.permissions, - creationDate = valueCreationDate, - maybeValueHasOrder = Some(valueHasOrder), - stringFormatter = stringFormatter - ) - .toString() - } + case linkValueContentV2: LinkValueContentV2 => + // We're creating a link. + + // Construct a SparqlTemplateLinkUpdate to tell the SPARQL template how to create + // the link and its LinkValue. + val sparqlTemplateLinkUpdate = SparqlTemplateLinkUpdate( + linkPropertyIri = propertyIri.fromLinkValuePropToLinkProp, + directLinkExists = false, + insertDirectLink = true, + deleteDirectLink = false, + linkValueExists = false, + linkTargetExists = linkValueContentV2.referredResourceExists, + newLinkValueIri = newValueIri, + linkTargetIri = linkValueContentV2.referredResourceIri, + currentReferenceCount = 0, + newReferenceCount = 1, + newLinkValueCreator = requestingUser.id, + newLinkValuePermissions = valueToCreate.permissions + ) + + // Generate SPARQL for the link. + org.knora.webapi.messages.twirl.queries.sparql.v2.txt + .generateInsertStatementsForCreateLink( + resourceIri = resourceIri, + linkUpdate = sparqlTemplateLinkUpdate, + creationDate = valueCreationDate, + newValueUUID = newValueUUID, + maybeComment = valueToCreate.valueContent.comment, + maybeValueHasOrder = Some(valueHasOrder), + stringFormatter = stringFormatter + ) + .toString() + + case otherValueContentV2 => + // We're creating an ordinary value. Generate SPARQL for it. + org.knora.webapi.messages.twirl.queries.sparql.v2.txt + .generateInsertStatementsForCreateValue( + resourceIri = resourceIri, + propertyIri = propertyIri, + value = otherValueContentV2, + newValueIri = newValueIri, + newValueUUID = newValueUUID, + linkUpdates = Seq.empty[ + SparqlTemplateLinkUpdate + ], // This is empty because we have to generate SPARQL for standoff links separately. + valueCreator = requestingUser.id, + valuePermissions = valueToCreate.permissions, + creationDate = valueCreationDate, + maybeValueHasOrder = Some(valueHasOrder), + stringFormatter = stringFormatter + ) + .toString() + } } yield InsertSparqlWithUnverifiedValue( insertSparql = insertSparql, unverifiedValue = UnverifiedValueV2( @@ -830,13 +842,13 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde standoffLinkUpdates: Seq[SparqlTemplateLinkUpdate] <- Future.sequence(standoffLinkUpdatesFutures) // Generate SPARQL INSERT statements based on those SparqlTemplateLinkUpdates. sparqlInsert = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .generateInsertStatementsForStandoffLinks( - resourceIri = createMultipleValuesRequest.resourceIri, - linkUpdates = standoffLinkUpdates, - creationDate = createMultipleValuesRequest.creationDate, - stringFormatter = stringFormatter - ) - .toString() + .generateInsertStatementsForStandoffLinks( + resourceIri = createMultipleValuesRequest.resourceIri, + linkUpdates = standoffLinkUpdates, + creationDate = createMultipleValuesRequest.creationDate, + stringFormatter = stringFormatter + ) + .toString() } yield Some(sparqlInsert) } else { FastFuture.successful(None) @@ -893,78 +905,82 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde // Get ontology information about the submitted property. propertyInfoRequestForSubmittedProperty = PropertiesGetRequestV2( - propertyIris = Set(submittedInternalPropertyIri), - allLanguages = false, - requestingUser = updateValueRequest.requestingUser - ) + propertyIris = Set(submittedInternalPropertyIri), + allLanguages = false, + requestingUser = updateValueRequest.requestingUser + ) propertyInfoResponseForSubmittedProperty: ReadOntologyV2 <- (responderManager ? propertyInfoRequestForSubmittedProperty) .mapTo[ReadOntologyV2] propertyInfoForSubmittedProperty: ReadPropertyInfoV2 = propertyInfoResponseForSubmittedProperty.properties( - submittedInternalPropertyIri - ) + submittedInternalPropertyIri + ) // Don't accept link properties. _ = if (propertyInfoForSubmittedProperty.isLinkProp) { - throw BadRequestException( - s"Invalid property <${propertyInfoForSubmittedProperty.entityInfoContent.propertyIri.toOntologySchema(ApiV2Complex)}>. Use a link value property to submit a link." - ) - } + throw BadRequestException( + s"Invalid property <${propertyInfoForSubmittedProperty.entityInfoContent.propertyIri.toOntologySchema(ApiV2Complex)}>. Use a link value property to submit a link." + ) + } // Don't accept knora-api:hasStandoffLinkToValue. _ = if (submittedExternalPropertyIri.toString == OntologyConstants.KnoraApiV2Complex.HasStandoffLinkToValue) { - throw BadRequestException(s"Values of <$submittedExternalPropertyIri> cannot be updated directly") - } + throw BadRequestException(s"Values of <$submittedExternalPropertyIri> cannot be updated directly") + } // Make an adjusted version of the submitted property: if it's a link value property, substitute the // corresponding link property, whose objects we will need to query. Get ontology information about the // adjusted property. adjustedInternalPropertyInfo: ReadPropertyInfoV2 <- getAdjustedInternalPropertyInfo( - submittedPropertyIri = submittedExternalPropertyIri, - maybeSubmittedValueType = Some(submittedExternalValueType), - propertyInfoForSubmittedProperty = propertyInfoForSubmittedProperty, - requestingUser = updateValueRequest.requestingUser - ) + submittedPropertyIri = submittedExternalPropertyIri, + maybeSubmittedValueType = + Some(submittedExternalValueType), + propertyInfoForSubmittedProperty = + propertyInfoForSubmittedProperty, + requestingUser = updateValueRequest.requestingUser + ) // Get the resource's metadata and relevant property objects, using the adjusted property. Do this as the system user, // so we can see objects that the user doesn't have permission to see. resourceInfo: ReadResourceV2 <- getResourceWithPropertyValues( - resourceIri = resourceIri, - propertyInfo = adjustedInternalPropertyInfo, - featureFactoryConfig = updateValueRequest.featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + resourceIri = resourceIri, + propertyInfo = adjustedInternalPropertyInfo, + featureFactoryConfig = updateValueRequest.featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) _ = if (resourceInfo.resourceClassIri != submittedExternalResourceClassIri.toOntologySchema(InternalSchema)) { - throw BadRequestException( - s"The rdf:type of resource <$resourceIri> is not <$submittedExternalResourceClassIri>" - ) - } + throw BadRequestException( + s"The rdf:type of resource <$resourceIri> is not <$submittedExternalResourceClassIri>" + ) + } // Check that the resource has the value that the user wants to update, as an object of the submitted property. currentValue: ReadValueV2 = resourceInfo.values - .get(submittedInternalPropertyIri) - .flatMap(_.find(_.valueIri == valueIri)) - .getOrElse { - throw NotFoundException( - s"Resource <$resourceIri> does not have value <$valueIri> as an object of property <$submittedExternalPropertyIri>" - ) - } + .get(submittedInternalPropertyIri) + .flatMap(_.find(_.valueIri == valueIri)) + .getOrElse { + throw NotFoundException( + s"Resource <$resourceIri> does not have value <$valueIri> as an object of property <$submittedExternalPropertyIri>" + ) + } // Check that the current value has the submitted value type. _ = if (currentValue.valueContent.valueType != submittedExternalValueType.toOntologySchema(InternalSchema)) { - throw BadRequestException( - s"Value <$valueIri> has type <${currentValue.valueContent.valueType.toOntologySchema(ApiV2Complex)}>, but the submitted type was <$submittedExternalValueType>" - ) - } + throw BadRequestException( + s"Value <$valueIri> has type <${currentValue.valueContent.valueType.toOntologySchema(ApiV2Complex)}>, but the submitted type was <$submittedExternalValueType>" + ) + } // If a custom value creation date was submitted, make sure it's later than the date of the current version. _ = if (updateValueRequest.updateValue.valueCreationDate.exists(!_.isAfter(currentValue.valueCreationDate))) { - throw BadRequestException("A custom value creation date must be later than the date of the current version") - } + throw BadRequestException( + "A custom value creation date must be later than the date of the current version" + ) + } } yield ResourcePropertyValue( resource = resourceInfo, submittedInternalPropertyIri = submittedInternalPropertyIri, @@ -984,91 +1000,95 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde for { // Do the initial checks, and get information about the resource, the property, and the value. resourcePropertyValue: ResourcePropertyValue <- getResourcePropertyValue( - resourceIri = updateValuePermissionsV2.resourceIri, - submittedExternalResourceClassIri = updateValuePermissionsV2.resourceClassIri, - submittedExternalPropertyIri = updateValuePermissionsV2.propertyIri, - valueIri = updateValuePermissionsV2.valueIri, - submittedExternalValueType = updateValuePermissionsV2.valueType - ) - - resourceInfo: ReadResourceV2 = resourcePropertyValue.resource + resourceIri = updateValuePermissionsV2.resourceIri, + submittedExternalResourceClassIri = + updateValuePermissionsV2.resourceClassIri, + submittedExternalPropertyIri = + updateValuePermissionsV2.propertyIri, + valueIri = updateValuePermissionsV2.valueIri, + submittedExternalValueType = + updateValuePermissionsV2.valueType + ) + + resourceInfo: ReadResourceV2 = resourcePropertyValue.resource submittedInternalPropertyIri: SmartIri = resourcePropertyValue.submittedInternalPropertyIri - currentValue: ReadValueV2 = resourcePropertyValue.value + currentValue: ReadValueV2 = resourcePropertyValue.value // Validate and reformat the submitted permissions. newValuePermissionLiteral: String <- PermissionUtilADM.validatePermissions( - permissionLiteral = updateValuePermissionsV2.permissions, - featureFactoryConfig = updateValueRequest.featureFactoryConfig, - responderManager = responderManager - ) + permissionLiteral = updateValuePermissionsV2.permissions, + featureFactoryConfig = updateValueRequest.featureFactoryConfig, + responderManager = responderManager + ) // Check that the user has ChangeRightsPermission on the value, and that the new permissions are // different from the current ones. currentPermissionsParsed: Map[EntityPermission, Set[IRI]] = PermissionUtilADM.parsePermissions( - currentValue.permissions - ) - newPermissionsParsed: Map[EntityPermission, Set[IRI]] = PermissionUtilADM.parsePermissions( - updateValuePermissionsV2.permissions, - { permissionLiteral: String => - throw AssertionException(s"Invalid permission literal: $permissionLiteral") - } - ) + currentValue.permissions + ) + newPermissionsParsed: Map[EntityPermission, Set[IRI]] = + PermissionUtilADM.parsePermissions( + updateValuePermissionsV2.permissions, + { permissionLiteral: String => + throw AssertionException(s"Invalid permission literal: $permissionLiteral") + } + ) _ = if (newPermissionsParsed == currentPermissionsParsed) { - throw BadRequestException(s"The submitted permissions are the same as the current ones") - } + throw BadRequestException(s"The submitted permissions are the same as the current ones") + } _ = ResourceUtilV2.checkValuePermission( - resourceInfo = resourceInfo, - valueInfo = currentValue, - permissionNeeded = ChangeRightsPermission, - requestingUser = updateValueRequest.requestingUser - ) + resourceInfo = resourceInfo, + valueInfo = currentValue, + permissionNeeded = ChangeRightsPermission, + requestingUser = updateValueRequest.requestingUser + ) // Do the update. dataNamedGraph: IRI = stringFormatter.projectDataNamedGraphV2(resourceInfo.projectADM) newValueIri: IRI <- checkOrCreateEntityIri( - updateValuePermissionsV2.newValueVersionIri, - stringFormatter.makeRandomValueIri(resourceInfo.resourceIri) - ) + updateValuePermissionsV2.newValueVersionIri, + stringFormatter.makeRandomValueIri(resourceInfo.resourceIri) + ) currentTime: Instant = updateValuePermissionsV2.valueCreationDate.getOrElse(Instant.now) sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .changeValuePermissions( - dataNamedGraph = dataNamedGraph, - resourceIri = resourceInfo.resourceIri, - propertyIri = submittedInternalPropertyIri, - currentValueIri = currentValue.valueIri, - valueTypeIri = currentValue.valueContent.valueType, - newValueIri = newValueIri, - newPermissions = newValuePermissionLiteral, - currentTime = currentTime - ) - .toString() + .changeValuePermissions( + dataNamedGraph = dataNamedGraph, + resourceIri = resourceInfo.resourceIri, + propertyIri = submittedInternalPropertyIri, + currentValueIri = currentValue.valueIri, + valueTypeIri = currentValue.valueContent.valueType, + newValueIri = newValueIri, + newPermissions = newValuePermissionLiteral, + currentTime = currentTime + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(sparqlUpdate)).mapTo[SparqlUpdateResponse] // Check that the value was written correctly to the triplestore. unverifiedValue = UnverifiedValueV2( - newValueIri = newValueIri, - newValueUUID = currentValue.valueHasUUID, - valueContent = currentValue.valueContent, - permissions = newValuePermissionLiteral, - creationDate = currentTime - ) + newValueIri = newValueIri, + newValueUUID = currentValue.valueHasUUID, + valueContent = currentValue.valueContent, + permissions = newValuePermissionLiteral, + creationDate = currentTime + ) verifiedValue: VerifiedValueV2 <- verifyValue( - resourceIri = resourceInfo.resourceIri, - propertyIri = submittedInternalPropertyIri, - unverifiedValue = unverifiedValue, - featureFactoryConfig = updateValueRequest.featureFactoryConfig, - requestingUser = updateValueRequest.requestingUser - ) + resourceIri = resourceInfo.resourceIri, + propertyIri = submittedInternalPropertyIri, + unverifiedValue = unverifiedValue, + featureFactoryConfig = updateValueRequest.featureFactoryConfig, + requestingUser = updateValueRequest.requestingUser + ) } yield UpdateValueResponseV2( valueIri = verifiedValue.newValueIri, valueType = unverifiedValue.valueContent.valueType, @@ -1088,45 +1108,49 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde for { // Do the initial checks, and get information about the resource, the property, and the value. resourcePropertyValue: ResourcePropertyValue <- getResourcePropertyValue( - resourceIri = updateValueContentV2.resourceIri, - submittedExternalResourceClassIri = updateValueContentV2.resourceClassIri, - submittedExternalPropertyIri = updateValueContentV2.propertyIri, - valueIri = updateValueContentV2.valueIri, - submittedExternalValueType = updateValueContentV2.valueContent.valueType - ) - - resourceInfo: ReadResourceV2 = resourcePropertyValue.resource - submittedInternalPropertyIri: SmartIri = resourcePropertyValue.submittedInternalPropertyIri + resourceIri = updateValueContentV2.resourceIri, + submittedExternalResourceClassIri = + updateValueContentV2.resourceClassIri, + submittedExternalPropertyIri = + updateValueContentV2.propertyIri, + valueIri = updateValueContentV2.valueIri, + submittedExternalValueType = + updateValueContentV2.valueContent.valueType + ) + + resourceInfo: ReadResourceV2 = resourcePropertyValue.resource + submittedInternalPropertyIri: SmartIri = resourcePropertyValue.submittedInternalPropertyIri adjustedInternalPropertyInfo: ReadPropertyInfoV2 = resourcePropertyValue.adjustedInternalPropertyInfo - currentValue: ReadValueV2 = resourcePropertyValue.value + currentValue: ReadValueV2 = resourcePropertyValue.value // Did the user submit permissions for the new value? newValueVersionPermissionLiteral <- updateValueContentV2.permissions match { - case Some(permissions) => - // Yes. Validate them. - PermissionUtilADM.validatePermissions( - permissionLiteral = permissions, - featureFactoryConfig = updateValueRequest.featureFactoryConfig, - responderManager = responderManager - ) - - case None => - // No. Use the permissions on the current version of the value. - FastFuture.successful(currentValue.permissions) - } + case Some(permissions) => + // Yes. Validate them. + PermissionUtilADM.validatePermissions( + permissionLiteral = permissions, + featureFactoryConfig = updateValueRequest.featureFactoryConfig, + responderManager = responderManager + ) + + case None => + // No. Use the permissions on the current version of the value. + FastFuture.successful(currentValue.permissions) + } // Check that the user has permission to do the update. If they want to change the permissions // on the value, they need ChangeRightsPermission, otherwise they need ModifyPermission. currentPermissionsParsed: Map[EntityPermission, Set[IRI]] = PermissionUtilADM.parsePermissions( - currentValue.permissions - ) - newPermissionsParsed: Map[EntityPermission, Set[IRI]] = PermissionUtilADM.parsePermissions( - newValueVersionPermissionLiteral, - { permissionLiteral: String => - throw AssertionException(s"Invalid permission literal: $permissionLiteral") - } - ) + currentValue.permissions + ) + newPermissionsParsed: Map[EntityPermission, Set[IRI]] = + PermissionUtilADM.parsePermissions( + newValueVersionPermissionLiteral, + { permissionLiteral: String => + throw AssertionException(s"Invalid permission literal: $permissionLiteral") + } + ) permissionNeeded = if (newPermissionsParsed != currentPermissionsParsed) { @@ -1136,124 +1160,129 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde } _ = ResourceUtilV2.checkValuePermission( - resourceInfo = resourceInfo, - valueInfo = currentValue, - permissionNeeded = permissionNeeded, - requestingUser = updateValueRequest.requestingUser - ) + resourceInfo = resourceInfo, + valueInfo = currentValue, + permissionNeeded = permissionNeeded, + requestingUser = updateValueRequest.requestingUser + ) // Convert the submitted value content to the internal schema. submittedInternalValueContent: ValueContentV2 = updateValueContentV2.valueContent.toOntologySchema( - InternalSchema - ) + InternalSchema + ) // Check that the object of the adjusted property (the value to be created, or the target of the link to be created) will have // the correct type for the adjusted property's knora-base:objectClassConstraint. _ <- checkPropertyObjectClassConstraint( - propertyInfo = adjustedInternalPropertyInfo, - valueContent = submittedInternalValueContent, - featureFactoryConfig = updateValueRequest.featureFactoryConfig, - requestingUser = updateValueRequest.requestingUser - ) + propertyInfo = adjustedInternalPropertyInfo, + valueContent = submittedInternalValueContent, + featureFactoryConfig = updateValueRequest.featureFactoryConfig, + requestingUser = updateValueRequest.requestingUser + ) // If this is a list value, check that it points to a real list node. _ <- submittedInternalValueContent match { - case listValue: HierarchicalListValueContentV2 => - ResourceUtilV2.checkListNodeExists(listValue.valueHasListNode, storeManager) - case _ => FastFuture.successful(()) - } + case listValue: HierarchicalListValueContentV2 => + ResourceUtilV2.checkListNodeExists(listValue.valueHasListNode, storeManager) + case _ => FastFuture.successful(()) + } // Check that the updated value would not duplicate the current value version. unescapedSubmittedInternalValueContent = submittedInternalValueContent.unescape _ = if (unescapedSubmittedInternalValueContent.wouldDuplicateCurrentVersion(currentValue.valueContent)) { - throw DuplicateValueException("The submitted value is the same as the current version") - } + throw DuplicateValueException("The submitted value is the same as the current version") + } // Check that the updated value would not duplicate another existing value of the resource. currentValuesForProp: Seq[ReadValueV2] = resourceInfo.values - .getOrElse(submittedInternalPropertyIri, Seq.empty[ReadValueV2]) - .filter(_.valueIri != updateValueContentV2.valueIri) + .getOrElse(submittedInternalPropertyIri, Seq.empty[ReadValueV2]) + .filter(_.valueIri != updateValueContentV2.valueIri) _ = if ( - currentValuesForProp.exists(currentVal => - unescapedSubmittedInternalValueContent.wouldDuplicateOtherValue(currentVal.valueContent) - ) - ) { - throw DuplicateValueException() - } - - _ <- submittedInternalValueContent match { - case textValueContent: TextValueContentV2 => - // This is a text value. Check that the resources pointed to by any standoff link tags exist - // and that the user has permission to see them. - checkResourceIris( - textValueContent.standoffLinkTagTargetResourceIris, - featureFactoryConfig = updateValueRequest.featureFactoryConfig, - updateValueRequest.requestingUser - ) - - case _: LinkValueContentV2 => - // We're updating a link. This means deleting an existing link and creating a new one, so - // check that the user has permission to modify the resource. - Future { - ResourceUtilV2.checkResourcePermission( - resourceInfo = resourceInfo, - permissionNeeded = ModifyPermission, - requestingUser = updateValueRequest.requestingUser + currentValuesForProp.exists(currentVal => + unescapedSubmittedInternalValueContent.wouldDuplicateOtherValue(currentVal.valueContent) ) + ) { + throw DuplicateValueException() } - case _ => FastFuture.successful(()) - } + _ <- submittedInternalValueContent match { + case textValueContent: TextValueContentV2 => + // This is a text value. Check that the resources pointed to by any standoff link tags exist + // and that the user has permission to see them. + checkResourceIris( + textValueContent.standoffLinkTagTargetResourceIris, + featureFactoryConfig = updateValueRequest.featureFactoryConfig, + updateValueRequest.requestingUser + ) + + case _: LinkValueContentV2 => + // We're updating a link. This means deleting an existing link and creating a new one, so + // check that the user has permission to modify the resource. + Future { + ResourceUtilV2.checkResourcePermission( + resourceInfo = resourceInfo, + permissionNeeded = ModifyPermission, + requestingUser = updateValueRequest.requestingUser + ) + } + + case _ => FastFuture.successful(()) + } dataNamedGraph: IRI = stringFormatter.projectDataNamedGraphV2(resourceInfo.projectADM) // Create the new value version. unverifiedValue: UnverifiedValueV2 <- (currentValue, submittedInternalValueContent) match { - case (currentLinkValue: ReadLinkValueV2, newLinkValue: LinkValueContentV2) => - updateLinkValueV2AfterChecks( - dataNamedGraph = dataNamedGraph, - resourceInfo = resourceInfo, - linkPropertyIri = adjustedInternalPropertyInfo.entityInfoContent.propertyIri, - currentLinkValue = currentLinkValue, - newLinkValue = newLinkValue, - valueCreator = updateValueRequest.requestingUser.id, - valuePermissions = newValueVersionPermissionLiteral, - valueCreationDate = updateValueContentV2.valueCreationDate, - newValueVersionIri = updateValueContentV2.newValueVersionIri, - requestingUser = updateValueRequest.requestingUser - ) - - case _ => - updateOrdinaryValueV2AfterChecks( - dataNamedGraph = dataNamedGraph, - resourceInfo = resourceInfo, - propertyIri = adjustedInternalPropertyInfo.entityInfoContent.propertyIri, - currentValue = currentValue, - newValueVersion = submittedInternalValueContent, - valueCreator = updateValueRequest.requestingUser.id, - valuePermissions = newValueVersionPermissionLiteral, - valueCreationDate = updateValueContentV2.valueCreationDate, - newValueVersionIri = updateValueContentV2.newValueVersionIri, - requestingUser = updateValueRequest.requestingUser - ) - } + case ( + currentLinkValue: ReadLinkValueV2, + newLinkValue: LinkValueContentV2 + ) => + updateLinkValueV2AfterChecks( + dataNamedGraph = dataNamedGraph, + resourceInfo = resourceInfo, + linkPropertyIri = + adjustedInternalPropertyInfo.entityInfoContent.propertyIri, + currentLinkValue = currentLinkValue, + newLinkValue = newLinkValue, + valueCreator = updateValueRequest.requestingUser.id, + valuePermissions = newValueVersionPermissionLiteral, + valueCreationDate = updateValueContentV2.valueCreationDate, + newValueVersionIri = updateValueContentV2.newValueVersionIri, + requestingUser = updateValueRequest.requestingUser + ) + + case _ => + updateOrdinaryValueV2AfterChecks( + dataNamedGraph = dataNamedGraph, + resourceInfo = resourceInfo, + propertyIri = + adjustedInternalPropertyInfo.entityInfoContent.propertyIri, + currentValue = currentValue, + newValueVersion = submittedInternalValueContent, + valueCreator = updateValueRequest.requestingUser.id, + valuePermissions = newValueVersionPermissionLiteral, + valueCreationDate = updateValueContentV2.valueCreationDate, + newValueVersionIri = updateValueContentV2.newValueVersionIri, + requestingUser = updateValueRequest.requestingUser + ) + } // Check that the value was written correctly to the triplestore. verifiedValue: VerifiedValueV2 <- verifyValue( - resourceIri = updateValueContentV2.resourceIri, - propertyIri = submittedInternalPropertyIri, - unverifiedValue = unverifiedValue, - featureFactoryConfig = updateValueRequest.featureFactoryConfig, - requestingUser = updateValueRequest.requestingUser - ) + resourceIri = updateValueContentV2.resourceIri, + propertyIri = submittedInternalPropertyIri, + unverifiedValue = unverifiedValue, + featureFactoryConfig = updateValueRequest.featureFactoryConfig, + requestingUser = updateValueRequest.requestingUser + ) } yield UpdateValueResponseV2( valueIri = verifiedValue.newValueIri, valueType = unverifiedValue.valueContent.valueType, @@ -1323,59 +1352,79 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde ): Future[UnverifiedValueV2] = for { newValueIri: IRI <- checkOrCreateEntityIri( - newValueVersionIri, - stringFormatter.makeRandomValueIri(resourceInfo.resourceIri) - ) + newValueVersionIri, + stringFormatter.makeRandomValueIri(resourceInfo.resourceIri) + ) // If we're updating a text value, update direct links and LinkValues for any resource references in Standoff. standoffLinkUpdates: Seq[SparqlTemplateLinkUpdate] <- (currentValue.valueContent, newValueVersion) match { - case (currentTextValue: TextValueContentV2, newTextValue: TextValueContentV2) => - // Identify the resource references that have been added or removed in the new version of - // the value. - val addedResourceRefs = - newTextValue.standoffLinkTagTargetResourceIris -- currentTextValue.standoffLinkTagTargetResourceIris - val removedResourceRefs = - currentTextValue.standoffLinkTagTargetResourceIris -- newTextValue.standoffLinkTagTargetResourceIris - - // Construct a SparqlTemplateLinkUpdate for each reference that was added. - val standoffLinkUpdatesForAddedResourceRefFutures: Seq[Future[SparqlTemplateLinkUpdate]] = - addedResourceRefs.toVector.map { targetResourceIri => - incrementLinkValue( - sourceResourceInfo = resourceInfo, - linkPropertyIri = OntologyConstants.KnoraBase.HasStandoffLinkTo.toSmartIri, - targetResourceIri = targetResourceIri, - valueCreator = OntologyConstants.KnoraAdmin.SystemUser, - valuePermissions = standoffLinkValuePermissions, - requestingUser = requestingUser - ) - } - - val standoffLinkUpdatesForAddedResourceRefsFuture: Future[Seq[SparqlTemplateLinkUpdate]] = - Future.sequence(standoffLinkUpdatesForAddedResourceRefFutures) - - // Construct a SparqlTemplateLinkUpdate for each reference that was removed. - val standoffLinkUpdatesForRemovedResourceRefFutures: Seq[Future[SparqlTemplateLinkUpdate]] = - removedResourceRefs.toVector.map { removedTargetResource => - decrementLinkValue( - sourceResourceInfo = resourceInfo, - linkPropertyIri = OntologyConstants.KnoraBase.HasStandoffLinkTo.toSmartIri, - targetResourceIri = removedTargetResource, - valueCreator = OntologyConstants.KnoraAdmin.SystemUser, - valuePermissions = standoffLinkValuePermissions, - requestingUser = requestingUser - ) - } - - val standoffLinkUpdatesForRemovedResourceRefFuture = - Future.sequence(standoffLinkUpdatesForRemovedResourceRefFutures) - - for { - standoffLinkUpdatesForAddedResourceRefs <- standoffLinkUpdatesForAddedResourceRefsFuture - standoffLinkUpdatesForRemovedResourceRefs <- standoffLinkUpdatesForRemovedResourceRefFuture - } yield standoffLinkUpdatesForAddedResourceRefs ++ standoffLinkUpdatesForRemovedResourceRefs - - case _ => FastFuture.successful(Vector.empty[SparqlTemplateLinkUpdate]) - } + case ( + currentTextValue: TextValueContentV2, + newTextValue: TextValueContentV2 + ) => + // Identify the resource references that have been added or removed in the new version of + // the value. + val addedResourceRefs = + newTextValue.standoffLinkTagTargetResourceIris -- currentTextValue.standoffLinkTagTargetResourceIris + val removedResourceRefs = + currentTextValue.standoffLinkTagTargetResourceIris -- newTextValue.standoffLinkTagTargetResourceIris + + // Construct a SparqlTemplateLinkUpdate for each reference that was added. + val standoffLinkUpdatesForAddedResourceRefFutures + : Seq[Future[SparqlTemplateLinkUpdate]] = + addedResourceRefs.toVector.map { targetResourceIri => + incrementLinkValue( + sourceResourceInfo = resourceInfo, + linkPropertyIri = + OntologyConstants.KnoraBase.HasStandoffLinkTo.toSmartIri, + targetResourceIri = targetResourceIri, + valueCreator = + OntologyConstants.KnoraAdmin.SystemUser, + valuePermissions = standoffLinkValuePermissions, + requestingUser = requestingUser + ) + } + + val standoffLinkUpdatesForAddedResourceRefsFuture + : Future[Seq[SparqlTemplateLinkUpdate]] = + Future.sequence( + standoffLinkUpdatesForAddedResourceRefFutures + ) + + // Construct a SparqlTemplateLinkUpdate for each reference that was removed. + val standoffLinkUpdatesForRemovedResourceRefFutures + : Seq[Future[SparqlTemplateLinkUpdate]] = + removedResourceRefs.toVector.map { + removedTargetResource => + decrementLinkValue( + sourceResourceInfo = resourceInfo, + linkPropertyIri = + OntologyConstants.KnoraBase.HasStandoffLinkTo.toSmartIri, + targetResourceIri = removedTargetResource, + valueCreator = + OntologyConstants.KnoraAdmin.SystemUser, + valuePermissions = standoffLinkValuePermissions, + requestingUser = requestingUser + ) + } + + val standoffLinkUpdatesForRemovedResourceRefFuture = + Future.sequence( + standoffLinkUpdatesForRemovedResourceRefFutures + ) + + for { + standoffLinkUpdatesForAddedResourceRefs <- + standoffLinkUpdatesForAddedResourceRefsFuture + standoffLinkUpdatesForRemovedResourceRefs <- + standoffLinkUpdatesForRemovedResourceRefFuture + } yield standoffLinkUpdatesForAddedResourceRefs ++ standoffLinkUpdatesForRemovedResourceRefs + + case _ => + FastFuture.successful( + Vector.empty[SparqlTemplateLinkUpdate] + ) + } // If no custom value creation date was provided, make a timestamp to indicate when the value // was updated. @@ -1383,23 +1432,23 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde // Generate a SPARQL update. sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .addValueVersion( - dataNamedGraph = dataNamedGraph, - resourceIri = resourceInfo.resourceIri, - propertyIri = propertyIri, - currentValueIri = currentValue.valueIri, - newValueIri = newValueIri, - valueTypeIri = newValueVersion.valueType, - value = newValueVersion, - valueCreator = valueCreator, - valuePermissions = valuePermissions, - maybeComment = newValueVersion.comment, - linkUpdates = standoffLinkUpdates, - currentTime = currentTime, - requestingUser = requestingUser.id, - stringFormatter = stringFormatter - ) - .toString() + .addValueVersion( + dataNamedGraph = dataNamedGraph, + resourceIri = resourceInfo.resourceIri, + propertyIri = propertyIri, + currentValueIri = currentValue.valueIri, + newValueIri = newValueIri, + valueTypeIri = newValueVersion.valueType, + value = newValueVersion, + valueCreator = valueCreator, + valuePermissions = valuePermissions, + maybeComment = newValueVersion.comment, + linkUpdates = standoffLinkUpdates, + currentTime = currentTime, + requestingUser = requestingUser.id, + stringFormatter = stringFormatter + ) + .toString() /* _ = println("================ Update value ================") @@ -1450,24 +1499,26 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde for { // Yes. Delete the existing link and decrement its LinkValue's reference count. sparqlTemplateLinkUpdateForCurrentLink: SparqlTemplateLinkUpdate <- decrementLinkValue( - sourceResourceInfo = resourceInfo, - linkPropertyIri = linkPropertyIri, - targetResourceIri = currentLinkValue.valueContent.referredResourceIri, - valueCreator = valueCreator, - valuePermissions = valuePermissions, - requestingUser = requestingUser - ) + sourceResourceInfo = resourceInfo, + linkPropertyIri = linkPropertyIri, + targetResourceIri = + currentLinkValue.valueContent.referredResourceIri, + valueCreator = valueCreator, + valuePermissions = valuePermissions, + requestingUser = requestingUser + ) // Create a new link, and create a new LinkValue for it. sparqlTemplateLinkUpdateForNewLink: SparqlTemplateLinkUpdate <- incrementLinkValue( - sourceResourceInfo = resourceInfo, - linkPropertyIri = linkPropertyIri, - targetResourceIri = newLinkValue.referredResourceIri, - customNewLinkValueIri = newValueVersionIri, - valueCreator = valueCreator, - valuePermissions = valuePermissions, - requestingUser = requestingUser - ) + sourceResourceInfo = resourceInfo, + linkPropertyIri = linkPropertyIri, + targetResourceIri = + newLinkValue.referredResourceIri, + customNewLinkValueIri = newValueVersionIri, + valueCreator = valueCreator, + valuePermissions = valuePermissions, + requestingUser = requestingUser + ) // If no custom value creation date was provided, make a timestamp to indicate when the link value // was updated. @@ -1478,20 +1529,20 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde // Generate a SPARQL update string. sparqlUpdate <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .changeLinkTarget( - dataNamedGraph = dataNamedGraph, - linkSourceIri = resourceInfo.resourceIri, - linkUpdateForCurrentLink = sparqlTemplateLinkUpdateForCurrentLink, - linkUpdateForNewLink = sparqlTemplateLinkUpdateForNewLink, - newLinkValueUUID = newLinkValueUUID, - maybeComment = newLinkValue.comment, - currentTime = currentTime, - requestingUser = requestingUser.id, - stringFormatter = stringFormatter - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v2.txt + .changeLinkTarget( + dataNamedGraph = dataNamedGraph, + linkSourceIri = resourceInfo.resourceIri, + linkUpdateForCurrentLink = sparqlTemplateLinkUpdateForCurrentLink, + linkUpdateForNewLink = sparqlTemplateLinkUpdateForNewLink, + newLinkValueUUID = newLinkValueUUID, + maybeComment = newLinkValue.comment, + currentTime = currentTime, + requestingUser = requestingUser.id, + stringFormatter = stringFormatter + ) + .toString() + ) /* _ = println("================ Update link ================") @@ -1511,28 +1562,29 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde for { // We're not changing the link target, just the metadata on the LinkValue. sparqlTemplateLinkUpdate: SparqlTemplateLinkUpdate <- changeLinkValueMetadata( - sourceResourceInfo = resourceInfo, - linkPropertyIri = linkPropertyIri, - targetResourceIri = currentLinkValue.valueContent.referredResourceIri, - customNewLinkValueIri = newValueVersionIri, - valueCreator = valueCreator, - valuePermissions = valuePermissions, - requestingUser = requestingUser - ) + sourceResourceInfo = resourceInfo, + linkPropertyIri = linkPropertyIri, + targetResourceIri = + currentLinkValue.valueContent.referredResourceIri, + customNewLinkValueIri = newValueVersionIri, + valueCreator = valueCreator, + valuePermissions = valuePermissions, + requestingUser = requestingUser + ) // Make a timestamp to indicate when the link value was updated. currentTime: Instant = Instant.now sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .changeLinkMetadata( - dataNamedGraph = dataNamedGraph, - linkSourceIri = resourceInfo.resourceIri, - linkUpdate = sparqlTemplateLinkUpdate, - maybeComment = newLinkValue.comment, - currentTime = currentTime, - requestingUser = requestingUser.id - ) - .toString() + .changeLinkMetadata( + dataNamedGraph = dataNamedGraph, + linkSourceIri = resourceInfo.resourceIri, + linkUpdate = sparqlTemplateLinkUpdate, + maybeComment = newLinkValue.comment, + currentTime = currentTime, + requestingUser = requestingUser.id + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(sparqlUpdate)).mapTo[SparqlUpdateResponse] } yield UnverifiedValueV2( @@ -1554,46 +1606,47 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde for { // Convert the submitted property IRI to the internal schema. submittedInternalPropertyIri: SmartIri <- Future( - deleteValueRequest.propertyIri.toOntologySchema(InternalSchema) - ) + deleteValueRequest.propertyIri.toOntologySchema(InternalSchema) + ) // Get ontology information about the submitted property. propertyInfoRequestForSubmittedProperty = PropertiesGetRequestV2( - propertyIris = Set(submittedInternalPropertyIri), - allLanguages = false, - requestingUser = deleteValueRequest.requestingUser - ) + propertyIris = Set(submittedInternalPropertyIri), + allLanguages = false, + requestingUser = deleteValueRequest.requestingUser + ) propertyInfoResponseForSubmittedProperty: ReadOntologyV2 <- (responderManager ? propertyInfoRequestForSubmittedProperty) .mapTo[ReadOntologyV2] propertyInfoForSubmittedProperty: ReadPropertyInfoV2 = propertyInfoResponseForSubmittedProperty.properties( - submittedInternalPropertyIri - ) + submittedInternalPropertyIri + ) // Don't accept link properties. _ = if (propertyInfoForSubmittedProperty.isLinkProp) { - throw BadRequestException( - s"Invalid property <${propertyInfoForSubmittedProperty.entityInfoContent.propertyIri.toOntologySchema(ApiV2Complex)}>. Use a link value property to submit a link." - ) - } + throw BadRequestException( + s"Invalid property <${propertyInfoForSubmittedProperty.entityInfoContent.propertyIri.toOntologySchema(ApiV2Complex)}>. Use a link value property to submit a link." + ) + } // Don't accept knora-api:hasStandoffLinkToValue. _ = if (deleteValueRequest.propertyIri.toString == OntologyConstants.KnoraApiV2Complex.HasStandoffLinkToValue) { - throw BadRequestException(s"Values of <${deleteValueRequest.propertyIri}> cannot be deleted directly") - } + throw BadRequestException(s"Values of <${deleteValueRequest.propertyIri}> cannot be deleted directly") + } // Make an adjusted version of the submitted property: if it's a link value property, substitute the // corresponding link property, whose objects we will need to query. Get ontology information about the // adjusted property. adjustedInternalPropertyInfo: ReadPropertyInfoV2 <- getAdjustedInternalPropertyInfo( - submittedPropertyIri = deleteValueRequest.propertyIri, - maybeSubmittedValueType = None, - propertyInfoForSubmittedProperty = propertyInfoForSubmittedProperty, - requestingUser = deleteValueRequest.requestingUser - ) + submittedPropertyIri = deleteValueRequest.propertyIri, + maybeSubmittedValueType = None, + propertyInfoForSubmittedProperty = + propertyInfoForSubmittedProperty, + requestingUser = deleteValueRequest.requestingUser + ) adjustedInternalPropertyIri = adjustedInternalPropertyInfo.entityInfoContent.propertyIri @@ -1601,90 +1654,90 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde // so we can see objects that the user doesn't have permission to see. resourceInfo: ReadResourceV2 <- getResourceWithPropertyValues( - resourceIri = deleteValueRequest.resourceIri, - propertyInfo = adjustedInternalPropertyInfo, - featureFactoryConfig = deleteValueRequest.featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - ) + resourceIri = deleteValueRequest.resourceIri, + propertyInfo = adjustedInternalPropertyInfo, + featureFactoryConfig = deleteValueRequest.featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + ) // Check that the resource belongs to the class that the client submitted. _ = if (resourceInfo.resourceClassIri != deleteValueRequest.resourceClassIri.toOntologySchema(InternalSchema)) { - throw BadRequestException( - s"Resource <${deleteValueRequest.resourceIri}> does not belong to class <${deleteValueRequest.resourceClassIri}>" - ) - } + throw BadRequestException( + s"Resource <${deleteValueRequest.resourceIri}> does not belong to class <${deleteValueRequest.resourceClassIri}>" + ) + } // Check that the resource has the value that the user wants to delete, as an object of the submitted property. maybeCurrentValue: Option[ReadValueV2] = resourceInfo.values - .get(submittedInternalPropertyIri) - .flatMap(_.find(_.valueIri == deleteValueRequest.valueIri)) + .get(submittedInternalPropertyIri) + .flatMap(_.find(_.valueIri == deleteValueRequest.valueIri)) // Check that the user has permission to delete the value. currentValue: ReadValueV2 = maybeCurrentValue match { - case Some(value) => value - case None => - throw NotFoundException( - s"Resource <${deleteValueRequest.resourceIri}> does not have value <${deleteValueRequest.valueIri}> as an object of property <${deleteValueRequest.propertyIri}>" - ) - } + case Some(value) => value + case None => + throw NotFoundException( + s"Resource <${deleteValueRequest.resourceIri}> does not have value <${deleteValueRequest.valueIri}> as an object of property <${deleteValueRequest.propertyIri}>" + ) + } // Check that the value is of the type that the client submitted. - _ = if ( - currentValue.valueContent.valueType != deleteValueRequest.valueTypeIri.toOntologySchema(InternalSchema) - ) { - throw BadRequestException( - s"Value <${deleteValueRequest.valueIri}> in resource <${deleteValueRequest.resourceIri}> is not of type <${deleteValueRequest.valueTypeIri}>" - ) - } + _ = + if (currentValue.valueContent.valueType != deleteValueRequest.valueTypeIri.toOntologySchema(InternalSchema)) { + throw BadRequestException( + s"Value <${deleteValueRequest.valueIri}> in resource <${deleteValueRequest.resourceIri}> is not of type <${deleteValueRequest.valueTypeIri}>" + ) + } // Check the user's permissions on the value. _ = ResourceUtilV2.checkValuePermission( - resourceInfo = resourceInfo, - valueInfo = currentValue, - permissionNeeded = DeletePermission, - requestingUser = deleteValueRequest.requestingUser - ) + resourceInfo = resourceInfo, + valueInfo = currentValue, + permissionNeeded = DeletePermission, + requestingUser = deleteValueRequest.requestingUser + ) // Get the definition of the resource class. classInfoRequest = ClassesGetRequestV2( - classIris = Set(resourceInfo.resourceClassIri), - allLanguages = false, - requestingUser = deleteValueRequest.requestingUser - ) + classIris = Set(resourceInfo.resourceClassIri), + allLanguages = false, + requestingUser = deleteValueRequest.requestingUser + ) classInfoResponse: ReadOntologyV2 <- (responderManager ? classInfoRequest).mapTo[ReadOntologyV2] - classInfo: ReadClassInfoV2 = classInfoResponse.classes(resourceInfo.resourceClassIri) + classInfo: ReadClassInfoV2 = classInfoResponse.classes(resourceInfo.resourceClassIri) cardinalityInfo: Cardinality.KnoraCardinalityInfo = classInfo.allCardinalities.getOrElse( - submittedInternalPropertyIri, - throw InconsistentRepositoryDataException( - s"Resource <${deleteValueRequest.resourceIri}> belongs to class <${resourceInfo.resourceClassIri - .toOntologySchema(ApiV2Complex)}>, which has no cardinality for property <${deleteValueRequest.propertyIri}>" - ) - ) + submittedInternalPropertyIri, + throw InconsistentRepositoryDataException( + s"Resource <${deleteValueRequest.resourceIri}> belongs to class <${resourceInfo.resourceClassIri + .toOntologySchema(ApiV2Complex)}>, which has no cardinality for property <${deleteValueRequest.propertyIri}>" + ) + ) // Check that the resource class's cardinality for the submitted property allows this value to be deleted. currentValuesForProp: Seq[ReadValueV2] = resourceInfo.values - .getOrElse(submittedInternalPropertyIri, Seq.empty[ReadValueV2]) - - _ = if ( - (cardinalityInfo.cardinality == Cardinality.MustHaveOne || cardinalityInfo.cardinality == Cardinality.MustHaveSome) && currentValuesForProp.size == 1 - ) { - throw OntologyConstraintException( - s"Resource class <${resourceInfo.resourceClassIri.toOntologySchema(ApiV2Complex)}> has a cardinality of ${cardinalityInfo.cardinality} on property <${deleteValueRequest.propertyIri}>, and this does not allow a value to be deleted for that property from resource <${deleteValueRequest.resourceIri}>" - ) - } + .getOrElse(submittedInternalPropertyIri, Seq.empty[ReadValueV2]) + + _ = + if ( + (cardinalityInfo.cardinality == Cardinality.MustHaveOne || cardinalityInfo.cardinality == Cardinality.MustHaveSome) && currentValuesForProp.size == 1 + ) { + throw OntologyConstraintException( + s"Resource class <${resourceInfo.resourceClassIri.toOntologySchema(ApiV2Complex)}> has a cardinality of ${cardinalityInfo.cardinality} on property <${deleteValueRequest.propertyIri}>, and this does not allow a value to be deleted for that property from resource <${deleteValueRequest.resourceIri}>" + ) + } // If a custom delete date was submitted, make sure it's later than the date of the current version. _ = if (deleteValueRequest.deleteDate.exists(!_.isAfter(currentValue.valueCreationDate))) { - throw BadRequestException("A custom delete date must be later than the value's creation date") - } + throw BadRequestException("A custom delete date must be later than the value's creation date") + } // Get information about the project that the resource is in, so we know which named graph to do the update in. @@ -1692,56 +1745,56 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde // Do the update. deletedValueIri: IRI <- deleteValueV2AfterChecks( - dataNamedGraph = dataNamedGraph, - resourceInfo = resourceInfo, - propertyIri = adjustedInternalPropertyIri, - deleteComment = deleteValueRequest.deleteComment, - deleteDate = deleteValueRequest.deleteDate, - currentValue = currentValue, - requestingUser = deleteValueRequest.requestingUser - ) + dataNamedGraph = dataNamedGraph, + resourceInfo = resourceInfo, + propertyIri = adjustedInternalPropertyIri, + deleteComment = deleteValueRequest.deleteComment, + deleteDate = deleteValueRequest.deleteDate, + currentValue = currentValue, + requestingUser = deleteValueRequest.requestingUser + ) // Check whether the update succeeded. sparqlQuery = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .checkValueDeletion( - valueIri = deletedValueIri - ) - .toString() + .checkValueDeletion( + valueIri = deletedValueIri + ) + .toString() sparqlSelectResponse <- (storeManager ? SparqlSelectRequest(sparqlQuery)).mapTo[SparqlSelectResult] - rows = sparqlSelectResponse.results.bindings + rows = sparqlSelectResponse.results.bindings _ = if ( - rows.isEmpty || !stringFormatter.optionStringToBoolean( - rows.head.rowMap.get("isDeleted"), - throw InconsistentRepositoryDataException( - s"Invalid boolean for isDeleted: ${rows.head.rowMap.get("isDeleted")}" - ) - ) - ) { - throw UpdateNotPerformedException( - s"The request to mark value <${deleteValueRequest.valueIri}> (or a new version of that value) as deleted did not succeed. Please report this as a possible bug." - ) - } + rows.isEmpty || !stringFormatter.optionStringToBoolean( + rows.head.rowMap.get("isDeleted"), + throw InconsistentRepositoryDataException( + s"Invalid boolean for isDeleted: ${rows.head.rowMap.get("isDeleted")}" + ) + ) + ) { + throw UpdateNotPerformedException( + s"The request to mark value <${deleteValueRequest.valueIri}> (or a new version of that value) as deleted did not succeed. Please report this as a possible bug." + ) + } } yield SuccessResponseV2(s"Value <$deletedValueIri> marked as deleted") } for { // Don't allow anonymous users to create values. _ <- Future { - if (deleteValueRequest.requestingUser.isAnonymousUser) { - throw ForbiddenException("Anonymous users aren't allowed to update values") - } else { - deleteValueRequest.requestingUser.id - } - } + if (deleteValueRequest.requestingUser.isAnonymousUser) { + throw ForbiddenException("Anonymous users aren't allowed to update values") + } else { + deleteValueRequest.requestingUser.id + } + } // Do the remaining pre-update checks and the update while holding an update lock on the resource. taskResult <- IriLocker.runWithIriLock( - deleteValueRequest.apiRequestID, - deleteValueRequest.resourceIri, - () => makeTaskFuture - ) + deleteValueRequest.apiRequestID, + deleteValueRequest.resourceIri, + () => makeTaskFuture + ) } yield taskResult } @@ -1827,24 +1880,24 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde for { // Delete the existing link and decrement its LinkValue's reference count. sparqlTemplateLinkUpdate <- decrementLinkValue( - sourceResourceInfo = resourceInfo, - linkPropertyIri = propertyIri, - targetResourceIri = currentLinkValueContent.referredResourceIri, - valueCreator = currentValue.attachedToUser, - valuePermissions = currentValue.permissions, - requestingUser = requestingUser - ) + sourceResourceInfo = resourceInfo, + linkPropertyIri = propertyIri, + targetResourceIri = currentLinkValueContent.referredResourceIri, + valueCreator = currentValue.attachedToUser, + valuePermissions = currentValue.permissions, + requestingUser = requestingUser + ) sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .deleteLink( - dataNamedGraph = dataNamedGraph, - linkSourceIri = resourceInfo.resourceIri, - linkUpdate = sparqlTemplateLinkUpdate, - maybeComment = deleteComment, - currentTime = currentTime, - requestingUser = requestingUser.id - ) - .toString() + .deleteLink( + dataNamedGraph = dataNamedGraph, + linkSourceIri = resourceInfo.resourceIri, + linkUpdate = sparqlTemplateLinkUpdate, + maybeComment = deleteComment, + currentTime = currentTime, + requestingUser = requestingUser.id + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(sparqlUpdate)).mapTo[SparqlUpdateResponse] } yield sparqlTemplateLinkUpdate.newLinkValueIri @@ -1901,18 +1954,18 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde linkUpdates: Seq[SparqlTemplateLinkUpdate] <- linkUpdateFuture sparqlUpdate = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .deleteValue( - dataNamedGraph = dataNamedGraph, - resourceIri = resourceInfo.resourceIri, - propertyIri = propertyIri, - valueIri = currentValue.valueIri, - maybeDeleteComment = deleteComment, - linkUpdates = linkUpdates, - currentTime = currentTime, - requestingUser = requestingUser.id, - stringFormatter = stringFormatter - ) - .toString() + .deleteValue( + dataNamedGraph = dataNamedGraph, + resourceIri = resourceInfo.resourceIri, + propertyIri = propertyIri, + valueIri = currentValue.valueIri, + maybeDeleteComment = deleteComment, + linkUpdates = linkUpdates, + currentTime = currentTime, + requestingUser = requestingUser.id, + stringFormatter = stringFormatter + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(sparqlUpdate)).mapTo[SparqlUpdateResponse] } yield currentValue.valueIri @@ -1954,13 +2007,13 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde internalLinkPropertyIri <- Future(submittedInternalPropertyIri.fromLinkValuePropToLinkProp) propertyInfoRequestForLinkProperty = PropertiesGetRequestV2( - propertyIris = Set(internalLinkPropertyIri), - allLanguages = false, - requestingUser = requestingUser - ) + propertyIris = Set(internalLinkPropertyIri), + allLanguages = false, + requestingUser = requestingUser + ) linkPropertyInfoResponse: ReadOntologyV2 <- (responderManager ? propertyInfoRequestForLinkProperty) - .mapTo[ReadOntologyV2] + .mapTo[ReadOntologyV2] } yield linkPropertyInfoResponse.properties(internalLinkPropertyIri) } else if (propertyInfoForSubmittedProperty.isLinkProp) { throw BadRequestException( @@ -1989,13 +2042,13 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde } else { for { resourcePreviewRequest <- FastFuture.successful( - ResourcesPreviewGetRequestV2( - resourceIris = targetResourceIris.toSeq, - targetSchema = ApiV2Complex, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) - ) + ResourcesPreviewGetRequestV2( + resourceIris = targetResourceIris.toSeq, + targetSchema = ApiV2Complex, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) + ) // If any of the resources are not found, or the user doesn't have permission to see them, this will throw an exception. @@ -2025,13 +2078,13 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde for { // Get the property's object class constraint. objectClassConstraint: SmartIri <- Future( - propertyInfo.entityInfoContent.requireIriObject( - OntologyConstants.KnoraBase.ObjectClassConstraint.toSmartIri, - throw InconsistentRepositoryDataException( - s"Property ${propertyInfo.entityInfoContent.propertyIri} has no knora-base:objectClassConstraint" - ) - ) - ) + propertyInfo.entityInfoContent.requireIriObject( + OntologyConstants.KnoraBase.ObjectClassConstraint.toSmartIri, + throw InconsistentRepositoryDataException( + s"Property ${propertyInfo.entityInfoContent.propertyIri} has no knora-base:objectClassConstraint" + ) + ) + ) // If the property points to a text value, also query the resource's standoff links. maybeStandoffLinkToPropertyIri: Option[SmartIri] = @@ -2043,28 +2096,28 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde // Convert the property IRIs to be queried to the API v2 complex schema for Gravsearch. propertyIrisForGravsearchQuery: Seq[SmartIri] = (Seq( - propertyInfo.entityInfoContent.propertyIri - ) ++ maybeStandoffLinkToPropertyIri) - .map(_.toOntologySchema(ApiV2Complex)) + propertyInfo.entityInfoContent.propertyIri + ) ++ maybeStandoffLinkToPropertyIri) + .map(_.toOntologySchema(ApiV2Complex)) // Make a Gravsearch query from a template. gravsearchQuery: String = org.knora.webapi.messages.twirl.queries.gravsearch.txt - .getResourceWithSpecifiedProperties( - resourceIri = resourceIri, - propertyIris = propertyIrisForGravsearchQuery - ) - .toString() + .getResourceWithSpecifiedProperties( + resourceIri = resourceIri, + propertyIris = propertyIrisForGravsearchQuery + ) + .toString() // Run the query. parsedGravsearchQuery <- FastFuture.successful(GravsearchParser.parseQuery(gravsearchQuery)) searchResponse <- (responderManager ? GravsearchRequestV2( - constructQuery = parsedGravsearchQuery, - targetSchema = ApiV2Complex, - schemaOptions = SchemaOptions.ForStandoffWithTextValues, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - )).mapTo[ReadResourcesSequenceV2] + constructQuery = parsedGravsearchQuery, + targetSchema = ApiV2Complex, + schemaOptions = SchemaOptions.ForStandoffWithTextValues, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + )).mapTo[ReadResourcesSequenceV2] } yield searchResponse.toResource(resourceIri) /** @@ -2086,31 +2139,31 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde ): Future[VerifiedValueV2] = { val verifiedValueFuture: Future[VerifiedValueV2] = for { resourcesRequest <- Future { - ResourcesGetRequestV2( - resourceIris = Seq(resourceIri), - propertyIri = Some(propertyIri), - versionDate = Some(unverifiedValue.creationDate), - targetSchema = ApiV2Complex, - schemaOptions = SchemaOptions.ForStandoffWithTextValues, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) - } + ResourcesGetRequestV2( + resourceIris = Seq(resourceIri), + propertyIri = Some(propertyIri), + versionDate = Some(unverifiedValue.creationDate), + targetSchema = ApiV2Complex, + schemaOptions = SchemaOptions.ForStandoffWithTextValues, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) + } resourcesResponse <- (responderManager ? resourcesRequest).mapTo[ReadResourcesSequenceV2] - resource = resourcesResponse.toResource(resourceIri) + resource = resourcesResponse.toResource(resourceIri) propertyValues = resource.values.getOrElse(propertyIri, throw UpdateNotPerformedException()) valueInTriplestore: ReadValueV2 = propertyValues - .find(_.valueIri == unverifiedValue.newValueIri) - .getOrElse(throw UpdateNotPerformedException()) + .find(_.valueIri == unverifiedValue.newValueIri) + .getOrElse(throw UpdateNotPerformedException()) _ = if ( - !(unverifiedValue.valueContent.wouldDuplicateCurrentVersion(valueInTriplestore.valueContent) && - valueInTriplestore.permissions == unverifiedValue.permissions && - valueInTriplestore.attachedToUser == requestingUser.id) - ) { - /* + !(unverifiedValue.valueContent.wouldDuplicateCurrentVersion(valueInTriplestore.valueContent) && + valueInTriplestore.permissions == unverifiedValue.permissions && + valueInTriplestore.attachedToUser == requestingUser.id) + ) { + /* import org.knora.webapi.util.MessageUtil println("==============================") println("Submitted value:") @@ -2119,11 +2172,11 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde println("==============================") println("Saved value:") println(MessageUtil.toSource(valueInTriplestore.valueContent)) - */ - throw AssertionException( - s"The value saved as ${unverifiedValue.newValueIri} is not the same as the one that was submitted" - ) - } + */ + throw AssertionException( + s"The value saved as ${unverifiedValue.newValueIri} is not the same as the one that was submitted" + ) + } } yield VerifiedValueV2( newValueIri = unverifiedValue.newValueIri, value = unverifiedValue.valueContent, @@ -2154,13 +2207,13 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde for { // Get a preview of the target resource, because we only need to find out its class and whether the user has permission to view it. resourcePreviewRequest <- FastFuture.successful( - ResourcesPreviewGetRequestV2( - resourceIris = Seq(linkValueContent.referredResourceIri), - targetSchema = ApiV2Complex, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) - ) + ResourcesPreviewGetRequestV2( + resourceIris = Seq(linkValueContent.referredResourceIri), + targetSchema = ApiV2Complex, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) + ) resourcePreviewResponse <- (responderManager ? resourcePreviewRequest).mapTo[ReadResourcesSequenceV2] @@ -2170,19 +2223,19 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde // Ask the ontology responder whether the resource's class is a subclass of the link property's object class constraint. subClassRequest = CheckSubClassRequestV2( - subClassIri = resource.resourceClassIri, - superClassIri = objectClassConstraint, - requestingUser = requestingUser - ) + subClassIri = resource.resourceClassIri, + superClassIri = objectClassConstraint, + requestingUser = requestingUser + ) subClassResponse <- (responderManager ? subClassRequest).mapTo[CheckSubClassResponseV2] // If it isn't, throw an exception. _ = if (!subClassResponse.isSubClass) { - throw OntologyConstraintException( - s"Resource <${linkValueContent.referredResourceIri}> cannot be the target of property <$linkPropertyIri>, because it is not a member of class <$objectClassConstraint>" - ) - } + throw OntologyConstraintException( + s"Resource <${linkValueContent.referredResourceIri}> cannot be the target of property <$linkPropertyIri>, because it is not a member of class <$objectClassConstraint>" + ) + } } yield () /** @@ -2207,21 +2260,21 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde // No. Ask the ontology responder whether it's a subclass of the property's object class constraint. for { subClassRequest <- FastFuture.successful( - CheckSubClassRequestV2( - subClassIri = valueContent.valueType, - superClassIri = objectClassConstraint, - requestingUser = requestingUser - ) - ) + CheckSubClassRequestV2( + subClassIri = valueContent.valueType, + superClassIri = objectClassConstraint, + requestingUser = requestingUser + ) + ) subClassResponse <- (responderManager ? subClassRequest).mapTo[CheckSubClassResponseV2] // If it isn't, throw an exception. _ = if (!subClassResponse.isSubClass) { - throw OntologyConstraintException( - s"A value of type <${valueContent.valueType}> cannot be the target of property <$propertyIri>, because it is not a member of class <$objectClassConstraint>" - ) - } + throw OntologyConstraintException( + s"A value of type <${valueContent.valueType}> cannot be the target of property <$propertyIri>, because it is not a member of class <$objectClassConstraint>" + ) + } } yield () } @@ -2243,44 +2296,44 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde ): Future[Unit] = for { objectClassConstraint: SmartIri <- Future( - propertyInfo.entityInfoContent.requireIriObject( - OntologyConstants.KnoraBase.ObjectClassConstraint.toSmartIri, - throw InconsistentRepositoryDataException( - s"Property ${propertyInfo.entityInfoContent.propertyIri} has no knora-base:objectClassConstraint" - ) - ) - ) + propertyInfo.entityInfoContent.requireIriObject( + OntologyConstants.KnoraBase.ObjectClassConstraint.toSmartIri, + throw InconsistentRepositoryDataException( + s"Property ${propertyInfo.entityInfoContent.propertyIri} has no knora-base:objectClassConstraint" + ) + ) + ) result: Unit <- valueContent match { - case linkValueContent: LinkValueContentV2 => - // We're creating a link. - - // Check that the property whose object class constraint is to be checked is actually a link property. - if (!propertyInfo.isLinkProp) { - throw BadRequestException( - s"Property <${propertyInfo.entityInfoContent.propertyIri.toOntologySchema(ApiV2Complex)}> is not a link property" - ) - } - - // Check that the user has permission to view the target resource, and that the target resource has the correct type. - checkLinkPropertyObjectClassConstraint( - linkPropertyIri = propertyInfo.entityInfoContent.propertyIri, - objectClassConstraint = objectClassConstraint, - linkValueContent = linkValueContent, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) - - case otherValue => - // We're creating an ordinary value. Check that its type is valid for the property's object class constraint. - checkNonLinkPropertyObjectClassConstraint( - propertyIri = propertyInfo.entityInfoContent.propertyIri, - objectClassConstraint = objectClassConstraint, - valueContent = otherValue, - requestingUser = requestingUser - ) - - } + case linkValueContent: LinkValueContentV2 => + // We're creating a link. + + // Check that the property whose object class constraint is to be checked is actually a link property. + if (!propertyInfo.isLinkProp) { + throw BadRequestException( + s"Property <${propertyInfo.entityInfoContent.propertyIri.toOntologySchema(ApiV2Complex)}> is not a link property" + ) + } + + // Check that the user has permission to view the target resource, and that the target resource has the correct type. + checkLinkPropertyObjectClassConstraint( + linkPropertyIri = propertyInfo.entityInfoContent.propertyIri, + objectClassConstraint = objectClassConstraint, + linkValueContent = linkValueContent, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) + + case otherValue => + // We're creating an ordinary value. Check that its type is valid for the property's object class constraint. + checkNonLinkPropertyObjectClassConstraint( + propertyIri = propertyInfo.entityInfoContent.propertyIri, + objectClassConstraint = objectClassConstraint, + valueContent = otherValue, + requestingUser = requestingUser + ) + + } } yield result /** @@ -2349,47 +2402,47 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde for { // Make an IRI for the new LinkValue. newLinkValueIri: IRI <- checkOrCreateEntityIri( - customNewLinkValueIri, - stringFormatter.makeRandomValueIri(sourceResourceInfo.resourceIri) - ) + customNewLinkValueIri, + stringFormatter.makeRandomValueIri(sourceResourceInfo.resourceIri) + ) linkUpdate = maybeLinkValueInfo match { - case Some(linkValueInfo) => - // There's already a LinkValue for links between these two resources. Increment - // its reference count. - SparqlTemplateLinkUpdate( - linkPropertyIri = linkPropertyIri, - directLinkExists = true, - insertDirectLink = false, - deleteDirectLink = false, - linkValueExists = true, - linkTargetExists = true, - newLinkValueIri = newLinkValueIri, - linkTargetIri = targetResourceIri, - currentReferenceCount = linkValueInfo.valueHasRefCount, - newReferenceCount = linkValueInfo.valueHasRefCount + 1, - newLinkValueCreator = valueCreator, - newLinkValuePermissions = valuePermissions - ) - - case None => - // There's no LinkValue for links between these two resources, so create one, and give it - // a reference count of 1. - SparqlTemplateLinkUpdate( - linkPropertyIri = linkPropertyIri, - directLinkExists = false, - insertDirectLink = true, - deleteDirectLink = false, - linkValueExists = false, - linkTargetExists = true, - newLinkValueIri = newLinkValueIri, - linkTargetIri = targetResourceIri, - currentReferenceCount = 0, - newReferenceCount = 1, - newLinkValueCreator = valueCreator, - newLinkValuePermissions = valuePermissions - ) - } + case Some(linkValueInfo) => + // There's already a LinkValue for links between these two resources. Increment + // its reference count. + SparqlTemplateLinkUpdate( + linkPropertyIri = linkPropertyIri, + directLinkExists = true, + insertDirectLink = false, + deleteDirectLink = false, + linkValueExists = true, + linkTargetExists = true, + newLinkValueIri = newLinkValueIri, + linkTargetIri = targetResourceIri, + currentReferenceCount = linkValueInfo.valueHasRefCount, + newReferenceCount = linkValueInfo.valueHasRefCount + 1, + newLinkValueCreator = valueCreator, + newLinkValuePermissions = valuePermissions + ) + + case None => + // There's no LinkValue for links between these two resources, so create one, and give it + // a reference count of 1. + SparqlTemplateLinkUpdate( + linkPropertyIri = linkPropertyIri, + directLinkExists = false, + insertDirectLink = true, + deleteDirectLink = false, + linkValueExists = false, + linkTargetExists = true, + newLinkValueIri = newLinkValueIri, + linkTargetIri = targetResourceIri, + currentReferenceCount = 0, + newReferenceCount = 1, + newLinkValueCreator = valueCreator, + newLinkValuePermissions = valuePermissions + ) + } } yield linkUpdate } @@ -2505,9 +2558,9 @@ class ValuesResponderV2(responderData: ResponderData) extends Responder(responde for { // If no custom IRI was provided, generate an IRI for the new LinkValue. newLinkValueIri: IRI <- checkOrCreateEntityIri( - customNewLinkValueIri, - stringFormatter.makeRandomValueIri(sourceResourceInfo.resourceIri) - ) + customNewLinkValueIri, + stringFormatter.makeRandomValueIri(sourceResourceInfo.resourceIri) + ) } yield SparqlTemplateLinkUpdate( linkPropertyIri = linkPropertyIri, diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v2/ontology/Cache.scala b/webapi/src/main/scala/org/knora/webapi/responders/v2/ontology/Cache.scala index 59626bdeef..5e61197b1f 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/v2/ontology/Cache.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v2/ontology/Cache.scala @@ -107,75 +107,87 @@ object Cache extends LazyLogging { )(implicit ec: ExecutionContext, stringFormat: StringFormatter, timeout: Timeout): Future[SuccessResponseV2] = { val loadOntologiesFuture: Future[SuccessResponseV2] = for { _ <- Future { - if ( - !(requestingUser.id == KnoraSystemInstances.Users.SystemUser.id || requestingUser.permissions.isSystemAdmin) - ) { - throw ForbiddenException(s"Only a system administrator can reload ontologies") - } - } + if ( + !(requestingUser.id == KnoraSystemInstances.Users.SystemUser.id || requestingUser.permissions.isSystemAdmin) + ) { + throw ForbiddenException(s"Only a system administrator can reload ontologies") + } + } // Get all ontology metadata. allOntologyMetadataSparql <- FastFuture.successful( - org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .getAllOntologyMetadata() - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v2.txt + .getAllOntologyMetadata() + .toString() + ) allOntologyMetadataResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(allOntologyMetadataSparql)) - .mapTo[SparqlSelectResult] + .mapTo[SparqlSelectResult] allOntologyMetadata: Map[SmartIri, OntologyMetadataV2] = OntologyHelpers.buildOntologyMetadata( - allOntologyMetadataResponse - ) + allOntologyMetadataResponse + ) - knoraBaseOntologyMetadata: OntologyMetadataV2 = allOntologyMetadata.getOrElse( - OntologyConstants.KnoraBase.KnoraBaseOntologyIri.toSmartIri, - throw InconsistentRepositoryDataException(s"No knora-base ontology found") - ) - knoraBaseOntologyVersion: String = knoraBaseOntologyMetadata.ontologyVersion.getOrElse( - throw InconsistentRepositoryDataException( - "The knora-base ontology in the repository is not up to date. See the Knora documentation on repository updates." + knoraBaseOntologyMetadata: OntologyMetadataV2 = + allOntologyMetadata.getOrElse( + OntologyConstants.KnoraBase.KnoraBaseOntologyIri.toSmartIri, + throw InconsistentRepositoryDataException(s"No knora-base ontology found") + ) + knoraBaseOntologyVersion: String = + knoraBaseOntologyMetadata.ontologyVersion.getOrElse( + throw InconsistentRepositoryDataException( + "The knora-base ontology in the repository is not up to date. See the Knora documentation on repository updates." + ) ) - ) _ = if (knoraBaseOntologyVersion != KnoraBaseVersion) { - throw InconsistentRepositoryDataException( - s"The knora-base ontology in the repository has version '$knoraBaseOntologyVersion', but this version of Knora requires '$KnoraBaseVersion'. See the Knora documentation on repository updates." - ) - } + throw InconsistentRepositoryDataException( + s"The knora-base ontology in the repository has version '$knoraBaseOntologyVersion', but this version of Knora requires '$KnoraBaseVersion'. See the Knora documentation on repository updates." + ) + } // Get the contents of each named graph containing an ontology. ontologyGraphResponseFutures: Iterable[Future[OntologyGraph]] = allOntologyMetadata.keys.map { ontologyIri => - val ontology: OntologyMetadataV2 = allOntologyMetadata.get(ontologyIri).get - val lastModificationDate: Option[Instant] = ontology.lastModificationDate - val attachedToProject: Option[SmartIri] = ontology.projectIri - - // throw an expception if ontology doesn't have lastModificationDate property and isn't attached to system project - lastModificationDate match { - case None => - attachedToProject match { - case Some(iri: SmartIri) => - if (iri != OntologyConstants.KnoraAdmin.SystemProject.toSmartIri) { - throw MissingLastModificationDateOntologyException( - s"Required property knora-base:lastModificationDate is missing in `$ontologyIri`" - ) - } - case _ => () - } - case _ => () - } - - val ontologyGraphConstructQuery = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .getOntologyGraph( - ontologyGraph = ontologyIri - ) - .toString - - (storeManager ? SparqlExtendedConstructRequest( - sparql = ontologyGraphConstructQuery, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse].map { response => - OntologyGraph(ontologyIri = ontologyIri, constructResponse = response) - } - } + val ontology: OntologyMetadataV2 = + allOntologyMetadata.get(ontologyIri).get + val lastModificationDate: Option[Instant] = + ontology.lastModificationDate + val attachedToProject: Option[SmartIri] = + ontology.projectIri + + // throw an expception if ontology doesn't have lastModificationDate property and isn't attached to system project + lastModificationDate match { + case None => + attachedToProject match { + case Some(iri: SmartIri) => + if ( + iri != OntologyConstants.KnoraAdmin.SystemProject.toSmartIri + ) { + throw MissingLastModificationDateOntologyException( + s"Required property knora-base:lastModificationDate is missing in `$ontologyIri`" + ) + } + case _ => () + } + case _ => () + } + + val ontologyGraphConstructQuery = + org.knora.webapi.messages.twirl.queries.sparql.v2.txt + .getOntologyGraph( + ontologyGraph = ontologyIri + ) + .toString + + (storeManager ? SparqlExtendedConstructRequest( + sparql = ontologyGraphConstructQuery, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse].map { + response => + OntologyGraph( + ontologyIri = ontologyIri, + constructResponse = response + ) + } + } ontologyGraphs: Iterable[OntologyGraph] <- Future.sequence(ontologyGraphResponseFutures) @@ -272,7 +284,7 @@ object Cache extends LazyLogging { case (propertyIri, propertyDef) => propertyIri -> propertyDef.subPropertyOf } - val allClassIris = allClassDefs.keySet + val allClassIris = allClassDefs.keySet val allPropertyIris = allPropertyDefs.keySet // A map in which each class IRI points to the full sequence of its base classes. @@ -607,10 +619,10 @@ object Cache extends LazyLogging { errorFun: String => Nothing ): Unit = if (targetEntityIri.isKnoraDefinitionIri) { - val sourceOntologyIri = sourceEntityIri.getOntologyFromEntity + val sourceOntologyIri = sourceEntityIri.getOntologyFromEntity val sourceOntologyMetadata = ontologyCacheData.ontologies(sourceOntologyIri).ontologyMetadata - val targetOntologyIri = targetEntityIri.getOntologyFromEntity + val targetOntologyIri = targetEntityIri.getOntologyFromEntity val targetOntologyMetadata = ontologyCacheData.ontologies(targetOntologyIri).ontologyMetadata if (sourceOntologyMetadata.projectIri != targetOntologyMetadata.projectIri) { @@ -807,7 +819,7 @@ object Cache extends LazyLogging { // Update the cache. - val ontologyIri = directSubClass.entityInfoContent.classIri.getOntologyFromEntity + val ontologyIri = directSubClass.entityInfoContent.classIri.getOntologyFromEntity val ontology: ReadOntologyV2 = cacheDataAcc.ontologies(ontologyIri) val updatedOntology = ontology.copy( diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v2/ontology/Cardinalities.scala b/webapi/src/main/scala/org/knora/webapi/responders/v2/ontology/Cardinalities.scala index b3eee46d6a..96958e6f6c 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/v2/ontology/Cardinalities.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v2/ontology/Cardinalities.scala @@ -60,35 +60,35 @@ object Cardinalities { // Check that the ontology exists and has not been updated by another user since the client last read it. _ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = deleteCardinalitiesFromClassRequest.lastModificationDate, - featureFactoryConfig = deleteCardinalitiesFromClassRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = deleteCardinalitiesFromClassRequest.lastModificationDate, + featureFactoryConfig = deleteCardinalitiesFromClassRequest.featureFactoryConfig + ) // Check that the class's rdf:type is owl:Class. rdfType: SmartIri = submittedClassDefinition.requireIriObject( - OntologyConstants.Rdf.Type.toSmartIri, - throw BadRequestException(s"No rdf:type specified") - ) + OntologyConstants.Rdf.Type.toSmartIri, + throw BadRequestException(s"No rdf:type specified") + ) _ = if (rdfType != OntologyConstants.Owl.Class.toSmartIri) { - throw BadRequestException(s"Invalid rdf:type for property: $rdfType") - } + throw BadRequestException(s"Invalid rdf:type for property: $rdfType") + } // Check that cardinalities were submitted. _ = if (submittedClassDefinition.directCardinalities.isEmpty) { - throw BadRequestException("No cardinalities specified") - } + throw BadRequestException("No cardinalities specified") + } // Check that only one cardinality was submitted. _ = if (submittedClassDefinition.directCardinalities.size > 1) { - throw BadRequestException("Only one cardinality is allowed to be submitted.") - } + throw BadRequestException("Only one cardinality is allowed to be submitted.") + } // Check that the class exists currentClassDefinition: ClassInfoContentV2 <- @@ -108,17 +108,17 @@ object Cardinalities { deleteCardinalitiesFromClassRequest.classInfoContent.toOntologySchema(InternalSchema).directCardinalities isDefinedOnClassList: List[Boolean] <- Future - .sequence(cardinalitiesToDelete.map { p => - for { - isDefined: Boolean <- isCardinalityDefinedOnClass( - cacheData, - p._1, - p._2, - internalClassIri, - internalOntologyIri - ) - } yield isDefined - }.toList) + .sequence(cardinalitiesToDelete.map { p => + for { + isDefined: Boolean <- isCardinalityDefinedOnClass( + cacheData, + p._1, + p._2, + internalClassIri, + internalOntologyIri + ) + } yield isDefined + }.toList) atLeastOneCardinalityNotDefinedOnClass: Boolean = isDefinedOnClassList.contains(false) @@ -126,18 +126,18 @@ object Cardinalities { submittedPropertyToDelete: SmartIri = cardinalitiesToDelete.head._1 propertyIsUsed: Boolean <- isPropertyUsedInResources( - settings, - storeManager, - internalClassIri, - submittedPropertyToDelete - ) + settings, + storeManager, + internalClassIri, + submittedPropertyToDelete + ) // Make an update class definition in which the cardinality to delete is removed submittedPropertyToDeleteIsLinkProperty: Boolean = cacheData - .ontologies(submittedPropertyToDelete.getOntologyFromEntity) - .properties(submittedPropertyToDelete) - .isLinkProp + .ontologies(submittedPropertyToDelete.getOntologyFromEntity) + .properties(submittedPropertyToDelete) + .isLinkProp newClassDefinitionWithRemovedCardinality = currentClassDefinition.copy( @@ -175,19 +175,19 @@ object Cardinalities { newClassDefinitionWithRemovedCardinality.directCardinalities.keySet // gets all keys from the map as a set .map(propertyIri => cacheData.ontologies(propertyIri.getOntologyFromEntity).properties(propertyIri) - ) // turn the propertyIri into a ReadPropertyInfoV2 - .filter(_.isLinkProp) // we are only interested in link properties + ) // turn the propertyIri into a ReadPropertyInfoV2 + .filter(_.isLinkProp) // we are only interested in link properties .map(_.entityInfoContent.propertyIri) // turn whatever is left back to a propertyIri ) // Check that the class definition doesn't refer to any non-shared ontologies in other projects. _ = Cache.checkOntologyReferencesInClassDef( - ontologyCacheData = cacheData, - classDef = newInternalClassDefWithLinkValueProps, - errorFun = { msg: String => - throw BadRequestException(msg) - } - ) + ontologyCacheData = cacheData, + classDef = newInternalClassDefWithLinkValueProps, + errorFun = { msg: String => + throw BadRequestException(msg) + } + ) // response is true only when property is not used in data and cardinality is defined directly on that class } yield CanDoResponseV2(!propertyIsUsed && !atLeastOneCardinalityNotDefinedOnClass) @@ -214,41 +214,41 @@ object Cardinalities { )(implicit ec: ExecutionContext, stringFormatter: StringFormatter, timeout: Timeout): Future[ReadOntologyV2] = for { cacheData: Cache.OntologyCacheData <- Cache.getCacheData - ontology = cacheData.ontologies(internalOntologyIri) + ontology = cacheData.ontologies(internalOntologyIri) submittedClassDefinition: ClassInfoContentV2 = deleteCardinalitiesFromClassRequest.classInfoContent.toOntologySchema(InternalSchema) // Check that the ontology exists and has not been updated by another user since the client last read it. _ <- OntologyHelpers.checkOntologyLastModificationDateBeforeUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = deleteCardinalitiesFromClassRequest.lastModificationDate, - featureFactoryConfig = deleteCardinalitiesFromClassRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = deleteCardinalitiesFromClassRequest.lastModificationDate, + featureFactoryConfig = deleteCardinalitiesFromClassRequest.featureFactoryConfig + ) // Check that the class's rdf:type is owl:Class. rdfType: SmartIri = submittedClassDefinition.requireIriObject( - OntologyConstants.Rdf.Type.toSmartIri, - throw BadRequestException(s"No rdf:type specified") - ) + OntologyConstants.Rdf.Type.toSmartIri, + throw BadRequestException(s"No rdf:type specified") + ) _ = if (rdfType != OntologyConstants.Owl.Class.toSmartIri) { - throw BadRequestException(s"Invalid rdf:type for property: $rdfType") - } + throw BadRequestException(s"Invalid rdf:type for property: $rdfType") + } // Check that cardinalities were submitted. _ = if (submittedClassDefinition.directCardinalities.isEmpty) { - throw BadRequestException("No cardinalities specified") - } + throw BadRequestException("No cardinalities specified") + } // Check that only one cardinality was submitted. _ = if (submittedClassDefinition.directCardinalities.size > 1) { - throw BadRequestException("Only one cardinality is allowed to be submitted.") - } + throw BadRequestException("Only one cardinality is allowed to be submitted.") + } // Check that the class exists currentClassDefinition: ClassInfoContentV2 <- @@ -265,43 +265,43 @@ object Cardinalities { deleteCardinalitiesFromClassRequest.classInfoContent.toOntologySchema(InternalSchema).directCardinalities isDefinedOnClassList: List[Boolean] <- Future - .sequence(cardinalitiesToDelete.map { p => - for { - isDefined: Boolean <- isCardinalityDefinedOnClass( - cacheData, - p._1, - p._2, - internalClassIri, - internalOntologyIri - ) - } yield isDefined - }.toList) + .sequence(cardinalitiesToDelete.map { p => + for { + isDefined: Boolean <- isCardinalityDefinedOnClass( + cacheData, + p._1, + p._2, + internalClassIri, + internalOntologyIri + ) + } yield isDefined + }.toList) _ = if (isDefinedOnClassList.contains(false)) { - throw BadRequestException( - "The cardinality is not defined directly on the class and cannot be deleted." - ) - } + throw BadRequestException( + "The cardinality is not defined directly on the class and cannot be deleted." + ) + } // Check if property is used in resources of this class submittedPropertyToDelete: SmartIri = cardinalitiesToDelete.head._1 propertyIsUsed: Boolean <- isPropertyUsedInResources( - settings, - storeManager, - internalClassIri, - submittedPropertyToDelete - ) + settings, + storeManager, + internalClassIri, + submittedPropertyToDelete + ) _ = if (propertyIsUsed) { - throw BadRequestException("Property is used in data. The cardinality cannot be deleted.") - } + throw BadRequestException("Property is used in data. The cardinality cannot be deleted.") + } // Make an update class definition in which the cardinality to delete is removed submittedPropertyToDeleteIsLinkProperty: Boolean = cacheData - .ontologies(submittedPropertyToDelete.getOntologyFromEntity) - .properties(submittedPropertyToDelete) - .isLinkProp + .ontologies(submittedPropertyToDelete.getOntologyFromEntity) + .properties(submittedPropertyToDelete) + .isLinkProp newClassDefinitionWithRemovedCardinality = currentClassDefinition.copy( @@ -339,19 +339,19 @@ object Cardinalities { newClassDefinitionWithRemovedCardinality.directCardinalities.keySet // gets all keys from the map as a set .map(propertyIri => cacheData.ontologies(propertyIri.getOntologyFromEntity).properties(propertyIri) - ) // turn the propertyIri into a ReadPropertyInfoV2 - .filter(_.isLinkProp) // we are only interested in link properties + ) // turn the propertyIri into a ReadPropertyInfoV2 + .filter(_.isLinkProp) // we are only interested in link properties .map(_.entityInfoContent.propertyIri) // turn whatever is left back to a propertyIri ) // Check that the class definition doesn't refer to any non-shared ontologies in other projects. _ = Cache.checkOntologyReferencesInClassDef( - ontologyCacheData = cacheData, - classDef = newInternalClassDefWithLinkValueProps, - errorFun = { msg: String => - throw BadRequestException(msg) - } - ) + ontologyCacheData = cacheData, + classDef = newInternalClassDefWithLinkValueProps, + errorFun = { msg: String => + throw BadRequestException(msg) + } + ) // Prepare to update the ontology cache. (No need to deal with SPARQL-escaping here, because there // isn't any text to escape in cardinalities.) @@ -364,92 +364,92 @@ object Cardinalities { } readClassInfo = ReadClassInfoV2( - entityInfoContent = newInternalClassDefWithLinkValueProps, - allBaseClasses = allBaseClassIris, - isResourceClass = true, - canBeInstantiated = true, - inheritedCardinalities = inheritedCardinalities, - knoraResourceProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => - OntologyHelpers.isKnoraResourceProperty(propertyIri, cacheData) - ), - linkProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => - OntologyHelpers.isLinkProp(propertyIri, cacheData) - ), - linkValueProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => - OntologyHelpers.isLinkValueProp(propertyIri, cacheData) - ), - fileValueProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => - OntologyHelpers.isFileValueProp(propertyIri, cacheData) - ) - ) + entityInfoContent = newInternalClassDefWithLinkValueProps, + allBaseClasses = allBaseClassIris, + isResourceClass = true, + canBeInstantiated = true, + inheritedCardinalities = inheritedCardinalities, + knoraResourceProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => + OntologyHelpers.isKnoraResourceProperty(propertyIri, cacheData) + ), + linkProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => + OntologyHelpers.isLinkProp(propertyIri, cacheData) + ), + linkValueProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => + OntologyHelpers.isLinkValueProp(propertyIri, cacheData) + ), + fileValueProperties = propertyIrisOfAllCardinalitiesForClass.filter(propertyIri => + OntologyHelpers.isFileValueProp(propertyIri, cacheData) + ) + ) // Add the cardinalities to the class definition in the triplestore. currentTime: Instant = Instant.now updateSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .replaceClassCardinalities( - ontologyNamedGraphIri = internalOntologyIri, - ontologyIri = internalOntologyIri, - classIri = internalClassIri, - newCardinalities = newInternalClassDefWithLinkValueProps.directCardinalities, - lastModificationDate = deleteCardinalitiesFromClassRequest.lastModificationDate, - currentTime = currentTime - ) - .toString() + .replaceClassCardinalities( + ontologyNamedGraphIri = internalOntologyIri, + ontologyIri = internalOntologyIri, + classIri = internalClassIri, + newCardinalities = newInternalClassDefWithLinkValueProps.directCardinalities, + lastModificationDate = deleteCardinalitiesFromClassRequest.lastModificationDate, + currentTime = currentTime + ) + .toString() _ <- (storeManager ? SparqlUpdateRequest(updateSparql)).mapTo[SparqlUpdateResponse] // Check that the ontology's last modification date was updated. _ <- OntologyHelpers.checkOntologyLastModificationDateAfterUpdate( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - expectedLastModificationDate = currentTime, - featureFactoryConfig = deleteCardinalitiesFromClassRequest.featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + expectedLastModificationDate = currentTime, + featureFactoryConfig = deleteCardinalitiesFromClassRequest.featureFactoryConfig + ) // Check that the data that was saved corresponds to the data that was submitted. loadedClassDef <- OntologyHelpers.loadClassDefinition( - settings, - storeManager, - classIri = internalClassIri, - featureFactoryConfig = deleteCardinalitiesFromClassRequest.featureFactoryConfig - ) + settings, + storeManager, + classIri = internalClassIri, + featureFactoryConfig = deleteCardinalitiesFromClassRequest.featureFactoryConfig + ) _ = if (loadedClassDef != newInternalClassDefWithLinkValueProps) { - throw InconsistentRepositoryDataException( - s"Attempted to save class definition $newInternalClassDefWithLinkValueProps, but $loadedClassDef was saved" - ) - } + throw InconsistentRepositoryDataException( + s"Attempted to save class definition $newInternalClassDefWithLinkValueProps, but $loadedClassDef was saved" + ) + } // Update subclasses and write the cache. updatedOntology = ontology.copy( - ontologyMetadata = ontology.ontologyMetadata.copy( - lastModificationDate = Some(currentTime) - ), - classes = ontology.classes + (internalClassIri -> readClassInfo) - ) + ontologyMetadata = ontology.ontologyMetadata.copy( + lastModificationDate = Some(currentTime) + ), + classes = ontology.classes + (internalClassIri -> readClassInfo) + ) _ = Cache.storeCacheData( - Cache.updateSubClasses( - baseClassIri = internalClassIri, - cacheData = cacheData.copy( - ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology) + Cache.updateSubClasses( + baseClassIri = internalClassIri, + cacheData = cacheData.copy( + ontologies = cacheData.ontologies + (internalOntologyIri -> updatedOntology) + ) + ) ) - ) - ) // Read the data back from the cache. response: ReadOntologyV2 <- OntologyHelpers.getClassDefinitionsFromOntologyV2( - classIris = Set(internalClassIri), - allLanguages = true, - requestingUser = deleteCardinalitiesFromClassRequest.requestingUser - ) + classIris = Set(internalClassIri), + allLanguages = true, + requestingUser = deleteCardinalitiesFromClassRequest.requestingUser + ) } yield response @@ -472,15 +472,15 @@ object Cardinalities { )(implicit ec: ExecutionContext, timeout: Timeout): Future[Boolean] = for { request <- Future( - org.knora.webapi.queries.sparql.v2.txt - .isPropertyUsed( - internalPropertyIri = internalPropertyIri.toString, - internalClassIri = internalClassIri.toString, - ignoreKnoraConstraints = true, - ignoreRdfSubjectAndObject = true - ) - .toString() - ) + org.knora.webapi.queries.sparql.v2.txt + .isPropertyUsed( + internalPropertyIri = internalPropertyIri.toString, + internalClassIri = internalClassIri.toString, + ignoreKnoraConstraints = true, + ignoreRdfSubjectAndObject = true + ) + .toString() + ) response: SparqlAskResponse <- (storeManager ? SparqlAskRequest(request)).mapTo[SparqlAskResponse] } yield response.result @@ -502,13 +502,13 @@ object Cardinalities { )(implicit ec: ExecutionContext): Future[ClassInfoContentV2] = for { currentOntologyState: ReadOntologyV2 <- Future(cacheData.ontologies(internalOntologyIri)) currentClassDefinition = currentOntologyState.classes - .getOrElse( - internalClassIri, - throw BadRequestException( - s"Class ${submittedClassInfoContentV2.classIri} does not exist" - ) - ) - .entityInfoContent + .getOrElse( + internalClassIri, + throw BadRequestException( + s"Class ${submittedClassInfoContentV2.classIri} does not exist" + ) + ) + .entityInfoContent } yield currentClassDefinition /** @@ -544,7 +544,7 @@ object Cardinalities { } val currentClassState: ClassInfoContentV2 = readClassInfo.entityInfoContent - val existingCardinality = currentClassState.directCardinalities.get(propertyIri) + val existingCardinality = currentClassState.directCardinalities.get(propertyIri) existingCardinality match { case Some(cardinality) => if (cardinality.cardinality.equals(cardinalityInfo.cardinality)) { diff --git a/webapi/src/main/scala/org/knora/webapi/responders/v2/ontology/OntologyHelpers.scala b/webapi/src/main/scala/org/knora/webapi/responders/v2/ontology/OntologyHelpers.scala index 7f62e9b196..efcee878fb 100644 --- a/webapi/src/main/scala/org/knora/webapi/responders/v2/ontology/OntologyHelpers.scala +++ b/webapi/src/main/scala/org/knora/webapi/responders/v2/ontology/OntologyHelpers.scala @@ -134,21 +134,21 @@ object OntologyHelpers { ): Future[Option[OntologyMetadataV2]] = { for { _ <- Future { - if (!internalOntologyIri.getOntologySchema.contains(InternalSchema)) { - throw AssertionException(s"Expected an internal ontology IRI: $internalOntologyIri") - } - } + if (!internalOntologyIri.getOntologySchema.contains(InternalSchema)) { + throw AssertionException(s"Expected an internal ontology IRI: $internalOntologyIri") + } + } getOntologyInfoSparql = org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .getOntologyInfo( - ontologyIri = internalOntologyIri - ) - .toString() + .getOntologyInfo( + ontologyIri = internalOntologyIri + ) + .toString() getOntologyInfoResponse <- (storeManager ? SparqlConstructRequest( - sparql = getOntologyInfoSparql, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlConstructResponse] + sparql = getOntologyInfoSparql, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlConstructResponse] metadata: Option[OntologyMetadataV2] = if (getOntologyInfoResponse.statements.isEmpty) { @@ -342,9 +342,9 @@ object OntologyHelpers { // Identify the Knora resource properties, link properties, link value properties, and file value properties in the cardinalities. val knoraResourcePropsInClass = allPropertyIrisForCardinalitiesInClass.filter(allKnoraResourceProps) - val linkPropsInClass = allPropertyIrisForCardinalitiesInClass.filter(allLinkProps) - val linkValuePropsInClass = allPropertyIrisForCardinalitiesInClass.filter(allLinkValueProps) - val fileValuePropsInClass = allPropertyIrisForCardinalitiesInClass.filter(allFileValueProps) + val linkPropsInClass = allPropertyIrisForCardinalitiesInClass.filter(allLinkProps) + val linkValuePropsInClass = allPropertyIrisForCardinalitiesInClass.filter(allLinkValueProps) + val fileValuePropsInClass = allPropertyIrisForCardinalitiesInClass.filter(allFileValueProps) // Make sure there is a link value property for each link property. @@ -370,8 +370,8 @@ object OntologyHelpers { // Make sure that the cardinality for each link property is the same as the cardinality for the corresponding link value property. for (linkProp <- linkPropsInClass) { - val linkValueProp: SmartIri = linkProp.fromLinkPropToLinkValueProp - val linkPropCardinality: KnoraCardinalityInfo = allOwlCardinalitiesForClass(linkProp) + val linkValueProp: SmartIri = linkProp.fromLinkPropToLinkValueProp + val linkPropCardinality: KnoraCardinalityInfo = allOwlCardinalitiesForClass(linkProp) val linkValuePropCardinality: KnoraCardinalityInfo = allOwlCardinalitiesForClass(linkValueProp) if (!linkPropCardinality.equalsWithoutGuiOrder(linkValuePropCardinality)) { @@ -386,8 +386,8 @@ object OntologyHelpers { val directCardinalityPropertyIris = directCardinalities.keySet val allBaseClasses: Seq[SmartIri] = allSubClassOfRelations(classIri) - val isKnoraResourceClass = allBaseClasses.contains(OntologyConstants.KnoraBase.Resource.toSmartIri) - val isStandoffClass = allBaseClasses.contains(OntologyConstants.KnoraBase.StandoffTag.toSmartIri) + val isKnoraResourceClass = allBaseClasses.contains(OntologyConstants.KnoraBase.Resource.toSmartIri) + val isStandoffClass = allBaseClasses.contains(OntologyConstants.KnoraBase.StandoffTag.toSmartIri) val isValueClass = !(isKnoraResourceClass || isStandoffClass) && allBaseClasses.contains( OntologyConstants.KnoraBase.Value.toSmartIri ) @@ -698,7 +698,7 @@ object OntologyHelpers { val isResourceProp = allKnoraResourceProps.contains(propertyIri) val isValueProp = allSubPropertyOfRelations(propertyIri).contains(OntologyConstants.KnoraBase.HasValue.toSmartIri) - val isLinkProp = allLinkProps.contains(propertyIri) + val isLinkProp = allLinkProps.contains(propertyIri) val isLinkValueProp = allLinkValueProps.contains(propertyIri) val isFileValueProp = allFileValueProps.contains(propertyIri) @@ -827,7 +827,7 @@ object OntologyHelpers { errorFun: String => Nothing )(implicit stringFormatter: StringFormatter): Unit = { val propertyIri = propertyInfoContent.propertyIri - val predicates = propertyInfoContent.predicates + val predicates = propertyInfoContent.predicates // Find out which salsah-gui:Guielement the property uses, if any. val maybeGuiElementPred: Option[PredicateInfoV2] = @@ -883,8 +883,8 @@ object OntologyHelpers { } // Check that all required GUI attributes are provided. - val requiredAttributeNames = guiAttributeDefs.filter(_.isRequired).map(_.attributeName) - val providedAttributeNames = guiAttributes.map(_.attributeName) + val requiredAttributeNames = guiAttributeDefs.filter(_.isRequired).map(_.attributeName) + val providedAttributeNames = guiAttributes.map(_.attributeName) val missingAttributeNames: Set[String] = requiredAttributeNames -- providedAttributeNames if (missingAttributeNames.nonEmpty) { @@ -1080,21 +1080,21 @@ object OntologyHelpers { ): Future[Set[IRI]] = for { isOntologyUsedSparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .isOntologyUsed( - ontologyNamedGraphIri = ontology.ontologyMetadata.ontologyIri, - classIris = ontology.classes.keySet, - propertyIris = ontology.properties.keySet - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v2.txt + .isOntologyUsed( + ontologyNamedGraphIri = ontology.ontologyMetadata.ontologyIri, + classIris = ontology.classes.keySet, + propertyIris = ontology.properties.keySet + ) + .toString() + ) isOntologyUsedResponse: SparqlSelectResult <- (storeManager ? SparqlSelectRequest(isOntologyUsedSparql)) - .mapTo[SparqlSelectResult] + .mapTo[SparqlSelectResult] subjects = isOntologyUsedResponse.results.bindings.map { row => - row.rowMap("s") - }.toSet + row.rowMap("s") + }.toSet } yield subjects /** @@ -1114,9 +1114,9 @@ object OntologyHelpers { _ <- checkExternalOntologyIriForUpdate(externalOntologyIri) _ <- checkExternalEntityIriForUpdate(externalEntityIri = externalEntityIri) _ <- checkPermissionsForOntologyUpdate( - internalOntologyIri = externalOntologyIri.toOntologySchema(InternalSchema), - requestingUser = requestingUser - ) + internalOntologyIri = externalOntologyIri.toOntologySchema(InternalSchema), + requestingUser = requestingUser + ) } yield () /** @@ -1134,17 +1134,17 @@ object OntologyHelpers { )(implicit ex: ExecutionContext, stringFormatter: StringFormatter, timeout: Timeout): Future[PropertyInfoContentV2] = for { sparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .getPropertyDefinition( - propertyIri = propertyIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v2.txt + .getPropertyDefinition( + propertyIri = propertyIri + ) + .toString() + ) constructResponse <- (storeManager ? SparqlExtendedConstructRequest( - sparql = sparql, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + sparql = sparql, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse] } yield constructResponseToPropertyDefinition( propertyIri = propertyIri, constructResponse = constructResponse @@ -1327,109 +1327,109 @@ object OntologyHelpers { nonKnoraEntities = (classIris ++ propertyIris).filter(!_.isKnoraEntityIri) _ = if (nonKnoraEntities.nonEmpty) { - throw BadRequestException( - s"Some requested entities are not Knora entities: ${nonKnoraEntities.mkString(", ")}" - ) - } + throw BadRequestException( + s"Some requested entities are not Knora entities: ${nonKnoraEntities.mkString(", ")}" + ) + } // See if any of the requested entities are unavailable in the requested schema. classesUnavailableInSchema: Set[SmartIri] = classIris.foldLeft(Set.empty[SmartIri]) { case (acc, classIri) => - // Is this class IRI hard-coded in the requested schema? - if ( - KnoraBaseToApiV2SimpleTransformationRules.externalClassesToAdd - .contains(classIri) || - KnoraBaseToApiV2ComplexTransformationRules.externalClassesToAdd - .contains(classIri) - ) { - // Yes, so it's available. - acc - } else { - // No. Is it among the classes removed from the internal ontology in the requested schema? - classIri.getOntologySchema.get match { - case apiV2Schema: ApiV2Schema => - val internalClassIri = - classIri.toOntologySchema(InternalSchema) - val knoraBaseClassesToRemove = OntologyTransformationRules - .getTransformationRules( - classIri.getOntologyFromEntity, - apiV2Schema - ) - .internalClassesToRemove - - if (knoraBaseClassesToRemove.contains(internalClassIri)) { - // Yes. Include it in the set of unavailable classes. - acc + classIri - } else { - // No. It's available. - acc - } - - case InternalSchema => acc - } - } - } + // Is this class IRI hard-coded in the requested schema? + if ( + KnoraBaseToApiV2SimpleTransformationRules.externalClassesToAdd + .contains(classIri) || + KnoraBaseToApiV2ComplexTransformationRules.externalClassesToAdd + .contains(classIri) + ) { + // Yes, so it's available. + acc + } else { + // No. Is it among the classes removed from the internal ontology in the requested schema? + classIri.getOntologySchema.get match { + case apiV2Schema: ApiV2Schema => + val internalClassIri = + classIri.toOntologySchema(InternalSchema) + val knoraBaseClassesToRemove = OntologyTransformationRules + .getTransformationRules( + classIri.getOntologyFromEntity, + apiV2Schema + ) + .internalClassesToRemove + + if (knoraBaseClassesToRemove.contains(internalClassIri)) { + // Yes. Include it in the set of unavailable classes. + acc + classIri + } else { + // No. It's available. + acc + } + + case InternalSchema => acc + } + } + } propertiesUnavailableInSchema: Set[SmartIri] = propertyIris.foldLeft(Set.empty[SmartIri]) { - case (acc, propertyIri) => - // Is this property IRI hard-coded in the requested schema? - if ( - KnoraBaseToApiV2SimpleTransformationRules.externalPropertiesToAdd - .contains(propertyIri) || - KnoraBaseToApiV2ComplexTransformationRules.externalPropertiesToAdd - .contains(propertyIri) - ) { - // Yes, so it's available. - acc - } else { - // No. See if it's available in the requested schema. - propertyIri.getOntologySchema.get match { - case apiV2Schema: ApiV2Schema => - val internalPropertyIri = - propertyIri.toOntologySchema(InternalSchema) - - // If it's a link value property and it's requested in the simple schema, it's unavailable. - if ( - apiV2Schema == ApiV2Simple && OntologyHelpers - .isLinkValueProp(internalPropertyIri, cacheData) - ) { - acc + propertyIri - } else { - // Is it among the properties removed from the internal ontology in the requested schema? - - val knoraBasePropertiesToRemove = - OntologyTransformationRules - .getTransformationRules( - propertyIri.getOntologyFromEntity, - apiV2Schema - ) - .internalPropertiesToRemove - - if ( - knoraBasePropertiesToRemove.contains( - internalPropertyIri - ) - ) { - // Yes. Include it in the set of unavailable properties. - acc + propertyIri - } else { - // No. It's available. - acc - } - } - - case InternalSchema => acc - } - } - } + case (acc, propertyIri) => + // Is this property IRI hard-coded in the requested schema? + if ( + KnoraBaseToApiV2SimpleTransformationRules.externalPropertiesToAdd + .contains(propertyIri) || + KnoraBaseToApiV2ComplexTransformationRules.externalPropertiesToAdd + .contains(propertyIri) + ) { + // Yes, so it's available. + acc + } else { + // No. See if it's available in the requested schema. + propertyIri.getOntologySchema.get match { + case apiV2Schema: ApiV2Schema => + val internalPropertyIri = + propertyIri.toOntologySchema(InternalSchema) + + // If it's a link value property and it's requested in the simple schema, it's unavailable. + if ( + apiV2Schema == ApiV2Simple && OntologyHelpers + .isLinkValueProp(internalPropertyIri, cacheData) + ) { + acc + propertyIri + } else { + // Is it among the properties removed from the internal ontology in the requested schema? + + val knoraBasePropertiesToRemove = + OntologyTransformationRules + .getTransformationRules( + propertyIri.getOntologyFromEntity, + apiV2Schema + ) + .internalPropertiesToRemove + + if ( + knoraBasePropertiesToRemove.contains( + internalPropertyIri + ) + ) { + // Yes. Include it in the set of unavailable properties. + acc + propertyIri + } else { + // No. It's available. + acc + } + } + + case InternalSchema => acc + } + } + } entitiesUnavailableInSchema = classesUnavailableInSchema ++ propertiesUnavailableInSchema _ = if (entitiesUnavailableInSchema.nonEmpty) { - throw NotFoundException( - s"Some requested entities were not found: ${entitiesUnavailableInSchema.mkString(", ")}" - ) - } + throw NotFoundException( + s"Some requested entities were not found: ${entitiesUnavailableInSchema.mkString(", ")}" + ) + } // See if any of the requested entities are hard-coded for knora-api. @@ -1456,15 +1456,15 @@ object OntologyHelpers { .map(externalIri => externalIri.toOntologySchema(InternalSchema) -> externalIri) .toMap - classIrisForCache = internalToExternalClassIris.keySet + classIrisForCache = internalToExternalClassIris.keySet propertyIrisForCache = internalToExternalPropertyIris.keySet // Get the entities that are available in the ontology cache. classOntologiesForCache: Iterable[ReadOntologyV2] = cacheData.ontologies.view - .filterKeys(classIrisForCache.map(_.getOntologyFromEntity)) - .toMap - .values + .filterKeys(classIrisForCache.map(_.getOntologyFromEntity)) + .toMap + .values propertyOntologiesForCache: Iterable[ReadOntologyV2] = cacheData.ontologies.view .filterKeys(propertyIrisForCache.map(_.getOntologyFromEntity)) @@ -1472,16 +1472,16 @@ object OntologyHelpers { .values classesAvailableFromCache: Map[SmartIri, ReadClassInfoV2] = classOntologiesForCache.flatMap { ontology => - ontology.classes.view - .filterKeys(classIrisForCache) - .toMap - }.toMap + ontology.classes.view + .filterKeys(classIrisForCache) + .toMap + }.toMap propertiesAvailableFromCache: Map[SmartIri, ReadPropertyInfoV2] = propertyOntologiesForCache.flatMap { ontology => - ontology.properties.view - .filterKeys(propertyIrisForCache) - .toMap - }.toMap + ontology.properties.view + .filterKeys(propertyIrisForCache) + .toMap + }.toMap allClassesAvailable: Map[SmartIri, ReadClassInfoV2] = classesAvailableFromCache ++ hardCodedExternalClassesAvailable @@ -1491,34 +1491,34 @@ object OntologyHelpers { // See if any entities are missing. allExternalClassIrisAvailable: Set[SmartIri] = allClassesAvailable.keySet.map { classIri => - if (classIri.getOntologySchema.contains(InternalSchema)) { - internalToExternalClassIris(classIri) - } else { - classIri - } - } + if (classIri.getOntologySchema.contains(InternalSchema)) { + internalToExternalClassIris(classIri) + } else { + classIri + } + } allExternalPropertyIrisAvailable = allPropertiesAvailable.keySet.map { propertyIri => - if (propertyIri.getOntologySchema.contains(InternalSchema)) { - internalToExternalPropertyIris(propertyIri) - } else { - propertyIri - } - } - - missingClasses = classIris -- allExternalClassIrisAvailable + if (propertyIri.getOntologySchema.contains(InternalSchema)) { + internalToExternalPropertyIris(propertyIri) + } else { + propertyIri + } + } + + missingClasses = classIris -- allExternalClassIrisAvailable missingProperties = propertyIris -- allExternalPropertyIrisAvailable missingEntities = missingClasses ++ missingProperties _ = if (missingEntities.nonEmpty) { - throw NotFoundException(s"Some requested entities were not found: ${missingEntities.mkString(", ")}") - } + throw NotFoundException(s"Some requested entities were not found: ${missingEntities.mkString(", ")}") + } response = EntityInfoGetResponseV2( - classInfoMap = new ErrorHandlingMap(allClassesAvailable, key => s"Resource class $key not found"), - propertyInfoMap = new ErrorHandlingMap(allPropertiesAvailable, key => s"Property $key not found") - ) + classInfoMap = new ErrorHandlingMap(allClassesAvailable, key => s"Resource class $key not found"), + propertyInfoMap = new ErrorHandlingMap(allPropertiesAvailable, key => s"Property $key not found") + ) } yield response } @@ -1540,8 +1540,8 @@ object OntologyHelpers { ontologyIris = classIris.map(_.getOntologyFromEntity) _ = if (ontologyIris.size != 1) { - throw BadRequestException(s"Only one ontology may be queried per request") - } + throw BadRequestException(s"Only one ontology may be queried per request") + } classInfoResponse: EntityInfoGetResponseV2 <- getEntityInfoResponseV2(classIris = classIris, requestingUser = requestingUser) @@ -1577,17 +1577,17 @@ object OntologyHelpers { )(implicit ex: ExecutionContext, stringFormatter: StringFormatter, timeout: Timeout): Future[ClassInfoContentV2] = for { sparql <- Future( - org.knora.webapi.messages.twirl.queries.sparql.v2.txt - .getClassDefinition( - classIri = classIri - ) - .toString() - ) + org.knora.webapi.messages.twirl.queries.sparql.v2.txt + .getClassDefinition( + classIri = classIri + ) + .toString() + ) constructResponse <- (storeManager ? SparqlExtendedConstructRequest( - sparql = sparql, - featureFactoryConfig = featureFactoryConfig - )).mapTo[SparqlExtendedConstructResponse] + sparql = sparql, + featureFactoryConfig = featureFactoryConfig + )).mapTo[SparqlExtendedConstructResponse] } yield constructResponseToClassDefinition( classIri = classIri, constructResponse = constructResponse @@ -1825,31 +1825,31 @@ object OntologyHelpers { )(implicit ec: ExecutionContext, stringFormatter: StringFormatter, timeout: Timeout): Future[Unit] = for { existingOntologyMetadata: Option[OntologyMetadataV2] <- loadOntologyMetadata( - settings, - storeManager, - internalOntologyIri = internalOntologyIri, - featureFactoryConfig = featureFactoryConfig - ) + settings, + storeManager, + internalOntologyIri = internalOntologyIri, + featureFactoryConfig = featureFactoryConfig + ) _ = existingOntologyMetadata match { - case Some(metadata) => - metadata.lastModificationDate match { - case Some(lastModificationDate) => - if (lastModificationDate != expectedLastModificationDate) { - errorFun + case Some(metadata) => + metadata.lastModificationDate match { + case Some(lastModificationDate) => + if (lastModificationDate != expectedLastModificationDate) { + errorFun + } + + case None => + throw InconsistentRepositoryDataException( + s"Ontology $internalOntologyIri has no ${OntologyConstants.KnoraBase.LastModificationDate}" + ) } case None => - throw InconsistentRepositoryDataException( - s"Ontology $internalOntologyIri has no ${OntologyConstants.KnoraBase.LastModificationDate}" + throw NotFoundException( + s"Ontology $internalOntologyIri (corresponding to ${internalOntologyIri.toOntologySchema(ApiV2Complex)}) not found" ) } - - case None => - throw NotFoundException( - s"Ontology $internalOntologyIri (corresponding to ${internalOntologyIri.toOntologySchema(ApiV2Complex)}) not found" - ) - } } yield () /** @@ -1900,11 +1900,11 @@ object OntologyHelpers { .get _ = if ( - !requestingUser.permissions.isProjectAdmin(projectIri.toString) && !requestingUser.permissions.isSystemAdmin - ) { - // not a project or system admin - throw ForbiddenException("Ontologies can be modified only by a project or system admin.") - } + !requestingUser.permissions.isProjectAdmin(projectIri.toString) && !requestingUser.permissions.isSystemAdmin + ) { + // not a project or system admin + throw ForbiddenException("Ontologies can be modified only by a project or system admin.") + } } yield projectIri diff --git a/webapi/src/main/scala/org/knora/webapi/routing/Authenticator.scala b/webapi/src/main/scala/org/knora/webapi/routing/Authenticator.scala index 6b6de7d274..5e4a1ff8cd 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/Authenticator.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/Authenticator.scala @@ -76,42 +76,42 @@ trait Authenticator extends InstrumentationSupport { for { userADM <- getUserADMThroughCredentialsV2( - credentials = credentials, - featureFactoryConfig = featureFactoryConfig - ) // will return or throw + credentials = credentials, + featureFactoryConfig = featureFactoryConfig + ) // will return or throw userProfile = userADM.asUserProfileV1 cookieDomain = Some(settings.cookieDomain) sessionToken = JWTHelper.createToken( - userProfile.userData.user_id.get, - settings.jwtSecretKey, - settings.jwtLongevity, - settings.externalKnoraApiHostPort - ) + userProfile.userData.user_id.get, + settings.jwtSecretKey, + settings.jwtLongevity, + settings.externalKnoraApiHostPort + ) httpResponse = HttpResponse( - headers = List( - headers.`Set-Cookie`( - HttpCookie( - KNORA_AUTHENTICATION_COOKIE_NAME, - sessionToken, - domain = cookieDomain, - path = Some("/"), - httpOnly = true - ) - ) - ), // set path to "/" to make the cookie valid for the whole domain (and not just a segment like v1 etc.) - status = StatusCodes.OK, - entity = HttpEntity( - ContentTypes.`application/json`, - JsObject( - "status" -> JsNumber(0), - "message" -> JsString("credentials are OK"), - "sid" -> JsString(sessionToken), - "userProfile" -> userProfile.ofType(UserProfileTypeV1.RESTRICTED).toJsValue - ).compactPrint - ) - ) + headers = List( + headers.`Set-Cookie`( + HttpCookie( + KNORA_AUTHENTICATION_COOKIE_NAME, + sessionToken, + domain = cookieDomain, + path = Some("/"), + httpOnly = true + ) + ) + ), // set path to "/" to make the cookie valid for the whole domain (and not just a segment like v1 etc.) + status = StatusCodes.OK, + entity = HttpEntity( + ContentTypes.`application/json`, + JsObject( + "status" -> JsNumber(0), + "message" -> JsString("credentials are OK"), + "sid" -> JsString(sessionToken), + "userProfile" -> userProfile.ofType(UserProfileTypeV1.RESTRICTED).toJsValue + ).compactPrint + ) + ) } yield httpResponse } @@ -135,45 +135,45 @@ trait Authenticator extends InstrumentationSupport { for { // will throw exception if not valid and thus trigger the correct response _ <- authenticateCredentialsV2( - credentials = Some(credentials), - featureFactoryConfig = featureFactoryConfig - ) + credentials = Some(credentials), + featureFactoryConfig = featureFactoryConfig + ) settings = KnoraSettings(system) userADM <- getUserByIdentifier( - identifier = credentials.identifier, - featureFactoryConfig = featureFactoryConfig - ) + identifier = credentials.identifier, + featureFactoryConfig = featureFactoryConfig + ) cookieDomain = Some(settings.cookieDomain) token = JWTHelper.createToken( - userADM.id, - settings.jwtSecretKey, - settings.jwtLongevity, - settings.externalKnoraApiHostPort - ) + userADM.id, + settings.jwtSecretKey, + settings.jwtLongevity, + settings.externalKnoraApiHostPort + ) httpResponse = HttpResponse( - headers = List( - headers.`Set-Cookie`( - HttpCookie( - KNORA_AUTHENTICATION_COOKIE_NAME, - token, - domain = cookieDomain, - path = Some("/"), - httpOnly = true - ) - ) - ), // set path to "/" to make the cookie valid for the whole domain (and not just a segment like v1 etc.) - status = StatusCodes.OK, - entity = HttpEntity( - ContentTypes.`application/json`, - JsObject( - "token" -> JsString(token) - ).compactPrint - ) - ) + headers = List( + headers.`Set-Cookie`( + HttpCookie( + KNORA_AUTHENTICATION_COOKIE_NAME, + token, + domain = cookieDomain, + path = Some("/"), + httpOnly = true + ) + ) + ), // set path to "/" to make the cookie valid for the whole domain (and not just a segment like v1 etc.) + status = StatusCodes.OK, + entity = HttpEntity( + ContentTypes.`application/json`, + JsObject( + "token" -> JsString(token) + ).compactPrint + ) + ) } yield httpResponse } @@ -249,23 +249,23 @@ trait Authenticator extends InstrumentationSupport { for { // will authenticate and either return or throw userADM: UserADM <- getUserADMThroughCredentialsV2( - credentials = credentials, - featureFactoryConfig = featureFactoryConfig - ) + credentials = credentials, + featureFactoryConfig = featureFactoryConfig + ) userProfile: UserProfileV1 = userADM.asUserProfileV1 httpResponse = HttpResponse( - status = StatusCodes.OK, - entity = HttpEntity( - ContentTypes.`application/json`, - JsObject( - "status" -> JsNumber(0), - "message" -> JsString("credentials are OK"), - "userProfile" -> userProfile.ofType(UserProfileTypeV1.RESTRICTED).toJsValue - ).compactPrint - ) - ) + status = StatusCodes.OK, + entity = HttpEntity( + ContentTypes.`application/json`, + JsObject( + "status" -> JsNumber(0), + "message" -> JsString("credentials are OK"), + "userProfile" -> userProfile.ofType(UserProfileTypeV1.RESTRICTED).toJsValue + ).compactPrint + ) + ) } yield httpResponse } @@ -287,19 +287,19 @@ trait Authenticator extends InstrumentationSupport { for { // will throw exception if not valid _ <- authenticateCredentialsV2( - credentials = credentials, - featureFactoryConfig = featureFactoryConfig - ) + credentials = credentials, + featureFactoryConfig = featureFactoryConfig + ) httpResponse = HttpResponse( - status = StatusCodes.OK, - entity = HttpEntity( - ContentTypes.`application/json`, - JsObject( - "message" -> JsString("credentials are OK") - ).compactPrint - ) - ) + status = StatusCodes.OK, + entity = HttpEntity( + ContentTypes.`application/json`, + JsObject( + "message" -> JsString("credentials are OK") + ).compactPrint + ) + ) } yield httpResponse } @@ -318,7 +318,7 @@ trait Authenticator extends InstrumentationSupport { val credentials = extractCredentialsV2(requestContext) - val settings = KnoraSettings(system) + val settings = KnoraSettings(system) val cookieDomain = Some(settings.cookieDomain) credentials match { @@ -343,7 +343,7 @@ trait Authenticator extends InstrumentationSupport { entity = HttpEntity( ContentTypes.`application/json`, JsObject( - "status" -> JsNumber(0), + "status" -> JsNumber(0), "message" -> JsString("Logout OK") ).compactPrint ) @@ -368,7 +368,7 @@ trait Authenticator extends InstrumentationSupport { entity = HttpEntity( ContentTypes.`application/json`, JsObject( - "status" -> JsNumber(0), + "status" -> JsNumber(0), "message" -> JsString("Logout OK") ).compactPrint ) @@ -380,7 +380,7 @@ trait Authenticator extends InstrumentationSupport { entity = HttpEntity( ContentTypes.`application/json`, JsObject( - "status" -> JsNumber(0), + "status" -> JsNumber(0), "message" -> JsString("Logout OK") ).compactPrint ) @@ -427,11 +427,11 @@ trait Authenticator extends InstrumentationSupport { } else { for { userADM <- getUserADMThroughCredentialsV2( - credentials = credentials, - featureFactoryConfig = featureFactoryConfig - ) + credentials = credentials, + featureFactoryConfig = featureFactoryConfig + ) userProfile: UserProfileV1 = userADM.asUserProfileV1 - _ = log.debug("Authenticator - getUserProfileV1 - userProfile: {}", userProfile) + _ = log.debug("Authenticator - getUserProfileV1 - userProfile: {}", userProfile) /* we return the userProfileV1 without sensitive information */ } yield userProfile.ofType(UserProfileTypeV1.RESTRICTED) @@ -470,9 +470,9 @@ trait Authenticator extends InstrumentationSupport { for { user: UserADM <- getUserADMThroughCredentialsV2( - credentials = credentials, - featureFactoryConfig = featureFactoryConfig - ) + credentials = credentials, + featureFactoryConfig = featureFactoryConfig + ) _ = log.debug("Authenticator - getUserADM - user: {}", user) /* we return the complete UserADM */ @@ -488,19 +488,19 @@ trait Authenticator extends InstrumentationSupport { */ object Authenticator extends InstrumentationSupport { - val BAD_CRED_PASSWORD_MISMATCH = "bad credentials: user found, but password did not match" - val BAD_CRED_USER_NOT_FOUND = "bad credentials: user not found" + val BAD_CRED_PASSWORD_MISMATCH = "bad credentials: user found, but password did not match" + val BAD_CRED_USER_NOT_FOUND = "bad credentials: user not found" val BAD_CRED_EMAIL_NOT_SUPPLIED = "bad credentials: no email supplied" - val BAD_CRED_NONE_SUPPLIED = "bad credentials: none found" - val BAD_CRED_USER_INACTIVE = "bad credentials: user inactive" - val BAD_CRED_NOT_VALID = "bad credentials: not valid" + val BAD_CRED_NONE_SUPPLIED = "bad credentials: none found" + val BAD_CRED_USER_INACTIVE = "bad credentials: user inactive" + val BAD_CRED_NOT_VALID = "bad credentials: not valid" - val KNORA_AUTHENTICATION_COOKIE_NAME = "KnoraAuthentication" + val KNORA_AUTHENTICATION_COOKIE_NAME = "KnoraAuthentication" val AUTHENTICATION_INVALIDATION_CACHE_NAME = "authenticationInvalidationCache" val sessionStore: scala.collection.mutable.Map[String, UserADM] = scala.collection.mutable.Map() - implicit val timeout: Timeout = Duration(5, SECONDS) - val log: Logger = Logger(LoggerFactory.getLogger(this.getClass)) + implicit val timeout: Timeout = Duration(5, SECONDS) + val log: Logger = Logger(LoggerFactory.getLogger(this.getClass)) private implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance @@ -526,40 +526,42 @@ object Authenticator extends InstrumentationSupport { settings <- FastFuture.successful(KnoraSettings(system)) result <- credentials match { - case Some(passCreds: KnoraPasswordCredentialsV2) => - for { - user <- getUserByIdentifier( - identifier = passCreds.identifier, - featureFactoryConfig = featureFactoryConfig - ) - - /* check if the user is active, if not, then no need to check the password */ - _ = if (!user.isActive) { - log.debug("authenticateCredentials - user is not active") - throw BadCredentialsException(BAD_CRED_USER_INACTIVE) - } - - _ = if (!user.passwordMatch(passCreds.password)) { - log.debug("authenticateCredentialsV2 - password did not match") - throw BadCredentialsException(BAD_CRED_NOT_VALID) - } - } yield true - case Some(KnoraJWTTokenCredentialsV2(jwtToken)) => - if (!JWTHelper.validateToken(jwtToken, settings.jwtSecretKey, settings.externalKnoraApiHostPort)) { - log.debug("authenticateCredentialsV2 - token was not valid") - throw BadCredentialsException(BAD_CRED_NOT_VALID) - } - FastFuture.successful(true) - case Some(KnoraSessionCredentialsV2(sessionToken)) => - if (!JWTHelper.validateToken(sessionToken, settings.jwtSecretKey, settings.externalKnoraApiHostPort)) { - log.debug("authenticateCredentialsV2 - session token was not valid") - throw BadCredentialsException(BAD_CRED_NOT_VALID) - } - FastFuture.successful(true) - case None => - log.debug("authenticateCredentialsV2 - no credentials supplied") - throw BadCredentialsException(BAD_CRED_NONE_SUPPLIED) - } + case Some(passCreds: KnoraPasswordCredentialsV2) => + for { + user <- getUserByIdentifier( + identifier = passCreds.identifier, + featureFactoryConfig = featureFactoryConfig + ) + + /* check if the user is active, if not, then no need to check the password */ + _ = if (!user.isActive) { + log.debug("authenticateCredentials - user is not active") + throw BadCredentialsException(BAD_CRED_USER_INACTIVE) + } + + _ = if (!user.passwordMatch(passCreds.password)) { + log.debug("authenticateCredentialsV2 - password did not match") + throw BadCredentialsException(BAD_CRED_NOT_VALID) + } + } yield true + case Some(KnoraJWTTokenCredentialsV2(jwtToken)) => + if (!JWTHelper.validateToken(jwtToken, settings.jwtSecretKey, settings.externalKnoraApiHostPort)) { + log.debug("authenticateCredentialsV2 - token was not valid") + throw BadCredentialsException(BAD_CRED_NOT_VALID) + } + FastFuture.successful(true) + case Some(KnoraSessionCredentialsV2(sessionToken)) => + if ( + !JWTHelper.validateToken(sessionToken, settings.jwtSecretKey, settings.externalKnoraApiHostPort) + ) { + log.debug("authenticateCredentialsV2 - session token was not valid") + throw BadCredentialsException(BAD_CRED_NOT_VALID) + } + FastFuture.successful(true) + case None => + log.debug("authenticateCredentialsV2 - no credentials supplied") + throw BadCredentialsException(BAD_CRED_NONE_SUPPLIED) + } } yield result @@ -607,8 +609,8 @@ object Authenticator extends InstrumentationSupport { // log.debug("extractCredentialsFromParametersV2 - params: {}", params) // check for iri, email, or username parameters - val maybeIriIdentifier: Option[String] = params.get("iri").map(_.head) - val maybeEmailIdentifier: Option[String] = params.get("email").map(_.head) + val maybeIriIdentifier: Option[String] = params.get("iri").map(_.head) + val maybeEmailIdentifier: Option[String] = params.get("email").map(_.head) val maybeUsernameIdentifier: Option[String] = params.get("username").map(_.head) val maybeIdentifier: Option[String] = List(maybeIriIdentifier, maybeEmailIdentifier, maybeUsernameIdentifier).flatten.headOption @@ -691,8 +693,8 @@ object Authenticator extends InstrumentationSupport { // try to decode email/password val (maybeEmail, maybePassword) = maybeBasicAuthValue match { case Some(value) => - val trimmedValue = value.substring(5).trim() // remove 'Basic ' - val decodedValue = ByteString.fromArray(Base64.getDecoder.decode(trimmedValue)).decodeString("UTF8") + val trimmedValue = value.substring(5).trim() // remove 'Basic ' + val decodedValue = ByteString.fromArray(Base64.getDecoder.decode(trimmedValue)).decodeString("UTF8") val decodedValueArr = decodedValue.split(":", 2) (Some(decodedValueArr(0)), Some(decodedValueArr(1))) case None => @@ -756,48 +758,52 @@ object Authenticator extends InstrumentationSupport { authenticated <- authenticateCredentialsV2(credentials = credentials, featureFactoryConfig = featureFactoryConfig) user: UserADM <- credentials match { - case Some(passCreds: KnoraPasswordCredentialsV2) => - // log.debug("getUserADMThroughCredentialsV2 - used identifier: {}", passCreds.identifier) - getUserByIdentifier( - identifier = passCreds.identifier, - featureFactoryConfig = featureFactoryConfig - ) - case Some(KnoraJWTTokenCredentialsV2(jwtToken)) => - val userIri: IRI = JWTHelper.extractUserIriFromToken( - jwtToken, - settings.jwtSecretKey, - settings.externalKnoraApiHostPort - ) match { - case Some(iri) => iri - case None => - // should not happen, as the token is already validated - throw AuthenticationException("No IRI found inside token. Please report this as a possible bug.") - } - // log.debug("getUserADMThroughCredentialsV2 - used token") - getUserByIdentifier( - identifier = UserIdentifierADM(maybeIri = Some(userIri)), - featureFactoryConfig = featureFactoryConfig - ) - case Some(KnoraSessionCredentialsV2(sessionToken)) => - val userIri: IRI = JWTHelper.extractUserIriFromToken( - sessionToken, - settings.jwtSecretKey, - settings.externalKnoraApiHostPort - ) match { - case Some(iri) => iri - case None => - // should not happen, as the token is already validated - throw AuthenticationException("No IRI found inside token. Please report this as a possible bug.") - } - // log.debug("getUserADMThroughCredentialsV2 - used session token") - getUserByIdentifier( - identifier = UserIdentifierADM(maybeIri = Some(userIri)), - featureFactoryConfig = featureFactoryConfig - ) - case None => - // log.debug("getUserADMThroughCredentialsV2 - no credentials supplied") - throw BadCredentialsException(BAD_CRED_NONE_SUPPLIED) - } + case Some(passCreds: KnoraPasswordCredentialsV2) => + // log.debug("getUserADMThroughCredentialsV2 - used identifier: {}", passCreds.identifier) + getUserByIdentifier( + identifier = passCreds.identifier, + featureFactoryConfig = featureFactoryConfig + ) + case Some(KnoraJWTTokenCredentialsV2(jwtToken)) => + val userIri: IRI = JWTHelper.extractUserIriFromToken( + jwtToken, + settings.jwtSecretKey, + settings.externalKnoraApiHostPort + ) match { + case Some(iri) => iri + case None => + // should not happen, as the token is already validated + throw AuthenticationException( + "No IRI found inside token. Please report this as a possible bug." + ) + } + // log.debug("getUserADMThroughCredentialsV2 - used token") + getUserByIdentifier( + identifier = UserIdentifierADM(maybeIri = Some(userIri)), + featureFactoryConfig = featureFactoryConfig + ) + case Some(KnoraSessionCredentialsV2(sessionToken)) => + val userIri: IRI = JWTHelper.extractUserIriFromToken( + sessionToken, + settings.jwtSecretKey, + settings.externalKnoraApiHostPort + ) match { + case Some(iri) => iri + case None => + // should not happen, as the token is already validated + throw AuthenticationException( + "No IRI found inside token. Please report this as a possible bug." + ) + } + // log.debug("getUserADMThroughCredentialsV2 - used session token") + getUserByIdentifier( + identifier = UserIdentifierADM(maybeIri = Some(userIri)), + featureFactoryConfig = featureFactoryConfig + ) + case None => + // log.debug("getUserADMThroughCredentialsV2 - no credentials supplied") + throw BadCredentialsException(BAD_CRED_NONE_SUPPLIED) + } } yield user } @@ -825,18 +831,18 @@ object Authenticator extends InstrumentationSupport { ): Future[UserADM] = tracedFuture("authenticator-get-user-by-identifier") { for { maybeUserADM <- (responderManager ? UserGetADM( - identifier = identifier, - userInformationTypeADM = UserInformationTypeADM.Full, - featureFactoryConfig = featureFactoryConfig, - requestingUser = KnoraSystemInstances.Users.SystemUser - )).mapTo[Option[UserADM]] + identifier = identifier, + userInformationTypeADM = UserInformationTypeADM.Full, + featureFactoryConfig = featureFactoryConfig, + requestingUser = KnoraSystemInstances.Users.SystemUser + )).mapTo[Option[UserADM]] user = maybeUserADM match { - case Some(u) => u - case None => - log.debug(s"getUserByIdentifier - supplied identifier not found - throwing exception") - throw BadCredentialsException(s"$BAD_CRED_USER_NOT_FOUND") - } + case Some(u) => u + case None => + log.debug(s"getUserByIdentifier - supplied identifier not found - throwing exception") + throw BadCredentialsException(s"$BAD_CRED_USER_NOT_FOUND") + } // _ = log.debug(s"getUserByIdentifier - user: $user") } yield user } diff --git a/webapi/src/main/scala/org/knora/webapi/routing/HealthRoute.scala b/webapi/src/main/scala/org/knora/webapi/routing/HealthRoute.scala index 50a3ea383b..86671f9b35 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/HealthRoute.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/HealthRoute.scala @@ -33,25 +33,37 @@ trait HealthCheck { state: AppState <- (applicationActor ? GetAppState()).mapTo[AppState] result: HealthCheckResult = state match { - case AppStates.Stopped => unhealthy("Stopped. Please retry later.") - case AppStates.StartingUp => unhealthy("Starting up. Please retry later.") - case AppStates.WaitingForTriplestore => unhealthy("Waiting for triplestore. Please retry later.") - case AppStates.TriplestoreReady => unhealthy("Triplestore ready. Please retry later.") - case AppStates.UpdatingRepository => unhealthy("Updating repository. Please retry later.") - case AppStates.RepositoryUpToDate => unhealthy("Repository up to date. Please retry later.") - case AppStates.CreatingCaches => unhealthy("Creating caches. Please retry later.") - case AppStates.CachesReady => unhealthy("Caches ready. Please retry later.") - case AppStates.UpdatingSearchIndex => unhealthy("Updating search index. Please retry later.") - case AppStates.SearchIndexReady => unhealthy("Search index ready. Please retry later.") - case AppStates.LoadingOntologies => unhealthy("Loading ontologies. Please retry later.") - case AppStates.OntologiesReady => unhealthy("Ontologies ready. Please retry later.") - case AppStates.WaitingForIIIFService => unhealthy("Waiting for IIIF service. Please retry later.") - case AppStates.IIIFServiceReady => unhealthy("IIIF service ready. Please retry later.") - case AppStates.WaitingForCacheService => unhealthy("Waiting for cache service. Please retry later.") - case AppStates.CacheServiceReady => unhealthy("Cache service ready. Please retry later.") - case AppStates.MaintenanceMode => unhealthy("Application is in maintenance mode. Please retry later.") - case AppStates.Running => healthy() - } + case AppStates.Stopped => unhealthy("Stopped. Please retry later.") + case AppStates.StartingUp => unhealthy("Starting up. Please retry later.") + case AppStates.WaitingForTriplestore => + unhealthy("Waiting for triplestore. Please retry later.") + case AppStates.TriplestoreReady => + unhealthy("Triplestore ready. Please retry later.") + case AppStates.UpdatingRepository => + unhealthy("Updating repository. Please retry later.") + case AppStates.RepositoryUpToDate => + unhealthy("Repository up to date. Please retry later.") + case AppStates.CreatingCaches => unhealthy("Creating caches. Please retry later.") + case AppStates.CachesReady => unhealthy("Caches ready. Please retry later.") + case AppStates.UpdatingSearchIndex => + unhealthy("Updating search index. Please retry later.") + case AppStates.SearchIndexReady => + unhealthy("Search index ready. Please retry later.") + case AppStates.LoadingOntologies => + unhealthy("Loading ontologies. Please retry later.") + case AppStates.OntologiesReady => unhealthy("Ontologies ready. Please retry later.") + case AppStates.WaitingForIIIFService => + unhealthy("Waiting for IIIF service. Please retry later.") + case AppStates.IIIFServiceReady => + unhealthy("IIIF service ready. Please retry later.") + case AppStates.WaitingForCacheService => + unhealthy("Waiting for cache service. Please retry later.") + case AppStates.CacheServiceReady => + unhealthy("Cache service ready. Please retry later.") + case AppStates.MaintenanceMode => + unhealthy("Application is in maintenance mode. Please retry later.") + case AppStates.Running => healthy() + } response = createResponse(result) @@ -63,10 +75,10 @@ trait HealthCheck { entity = HttpEntity( ContentTypes.`application/json`, JsObject( - "name" -> JsString(result.name), + "name" -> JsString(result.name), "severity" -> JsString(result.severity), - "status" -> JsString(status(result.status)), - "message" -> JsString(result.message) + "status" -> JsString(status(result.status)), + "message" -> JsString(result.message) ).compactPrint ) ) diff --git a/webapi/src/main/scala/org/knora/webapi/routing/KnoraRoute.scala b/webapi/src/main/scala/org/knora/webapi/routing/KnoraRoute.scala index 4d613965f0..acd1ac89b3 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/KnoraRoute.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/KnoraRoute.scala @@ -46,19 +46,19 @@ case class KnoraRouteData(system: ActorSystem, appActor: ActorRef) * @param routeData a [[KnoraRouteData]] providing access to the application. */ abstract class KnoraRouteFactory(routeData: KnoraRouteData) { - implicit protected val system: ActorSystem = routeData.system + implicit protected val system: ActorSystem = routeData.system implicit protected val settings: KnoraSettingsImpl = KnoraSettings(system) - implicit protected val timeout: Timeout = settings.defaultTimeout + implicit protected val timeout: Timeout = settings.defaultTimeout implicit protected val executionContext: ExecutionContext = system.dispatchers.lookup(KnoraDispatchers.KnoraActorDispatcher) - implicit protected val materializer: Materializer = Materializer.matFromSystem(system) + implicit protected val materializer: Materializer = Materializer.matFromSystem(system) implicit protected val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - protected val applicationActor: ActorRef = routeData.appActor + protected val applicationActor: ActorRef = routeData.appActor implicit protected val responderManager: ActorRef = routeData.appActor - protected val storeManager: ActorRef = routeData.appActor - protected val log: LoggingAdapter = akka.event.Logging(system, this.getClass) - protected val baseApiUrl: String = settings.internalKnoraApiBaseUrl + protected val storeManager: ActorRef = routeData.appActor + protected val log: LoggingAdapter = akka.event.Logging(system, this.getClass) + protected val baseApiUrl: String = settings.internalKnoraApiBaseUrl /** * Constructs a route. This can be done: @@ -139,11 +139,12 @@ abstract class KnoraRoute(routeData: KnoraRouteData) extends KnoraRouteFactory(r } for { - projectInfoResponse: ProjectGetResponseADM <- (responderManager ? ProjectGetRequestADM( - identifier = ProjectIdentifierADM(maybeIri = Some(checkedProjectIri)), - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - )).mapTo[ProjectGetResponseADM] + projectInfoResponse: ProjectGetResponseADM <- + (responderManager ? ProjectGetRequestADM( + identifier = ProjectIdentifierADM(maybeIri = Some(checkedProjectIri)), + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + )).mapTo[ProjectGetResponseADM] } yield projectInfoResponse.project } diff --git a/webapi/src/main/scala/org/knora/webapi/routing/RouteUtilADM.scala b/webapi/src/main/scala/org/knora/webapi/routing/RouteUtilADM.scala index 6ff0dc79f8..374eb2d57e 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/RouteUtilADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/RouteUtilADM.scala @@ -51,23 +51,25 @@ object RouteUtilADM { // Optionally log the request message. TODO: move this to the testing framework. _ = if (settings.dumpMessages) { - log.debug(requestMessage.toString) - } + log.debug(requestMessage.toString) + } // Make sure the responder sent a reply of type KnoraResponseV2. knoraResponse <- (responderManager ? requestMessage).map { - case replyMessage: KnoraResponseADM => replyMessage + case replyMessage: KnoraResponseADM => replyMessage - case other => - // The responder returned an unexpected message type (not an exception). This isn't the client's - // fault, so log it and return an error message to the client. - throw UnexpectedMessageException(s"Responder sent a reply of type ${other.getClass.getCanonicalName}") - } + case other => + // The responder returned an unexpected message type (not an exception). This isn't the client's + // fault, so log it and return an error message to the client. + throw UnexpectedMessageException( + s"Responder sent a reply of type ${other.getClass.getCanonicalName}" + ) + } // Optionally log the reply message. TODO: move this to the testing framework. _ = if (settings.dumpMessages) { - log.debug(knoraResponse.toString) - } + log.debug(knoraResponse.toString) + } jsonResponse = knoraResponse.toJsValue.asJsObject } yield featureFactoryConfig.addHeaderToHttpResponse( diff --git a/webapi/src/main/scala/org/knora/webapi/routing/RouteUtilV1.scala b/webapi/src/main/scala/org/knora/webapi/routing/RouteUtilV1.scala index 6534b5282f..5f87c02998 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/RouteUtilV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/RouteUtilV1.scala @@ -68,23 +68,26 @@ object RouteUtilV1 { val httpResponse: Future[HttpResponse] = for { // Make sure the responder sent a reply of type KnoraResponseV1. knoraResponse <- (responderManager ? requestMessage).map { - case replyMessage: KnoraResponseV1 => replyMessage + case replyMessage: KnoraResponseV1 => replyMessage - case other => - // The responder returned an unexpected message type (not an exception). This isn't the client's - // fault, so log it and return an error message to the client. - throw UnexpectedMessageException(s"Responder sent a reply of type ${other.getClass.getCanonicalName}") - } + case other => + // The responder returned an unexpected message type (not an exception). This isn't the client's + // fault, so log it and return an error message to the client. + throw UnexpectedMessageException( + s"Responder sent a reply of type ${other.getClass.getCanonicalName}" + ) + } // Optionally log the reply message. TODO: move this to the testing framework. _ = if (settings.dumpMessages) { - log.debug(knoraResponse.toString) - } + log.debug(knoraResponse.toString) + } // The request was successful, so add a status of ApiStatusCodesV1.OK to the response. - jsonResponseWithStatus = JsObject( - knoraResponse.toJsValue.asJsObject.fields + ("status" -> JsNumber(ApiStatusCodesV1.OK.id)) - ) + jsonResponseWithStatus = + JsObject( + knoraResponse.toJsValue.asJsObject.fields + ("status" -> JsNumber(ApiStatusCodesV1.OK.id)) + ) } yield HttpResponse( status = StatusCodes.OK, @@ -119,12 +122,12 @@ object RouteUtilV1 { for { requestMessage <- requestMessageF routeResult <- runJsonRoute( - requestMessage = requestMessage, - requestContext = requestContext, - settings = settings, - responderManager = responderManager, - log = log - ) + requestMessage = requestMessage, + requestContext = requestContext, + settings = settings, + responderManager = responderManager, + log = log + ) } yield routeResult /** @@ -156,24 +159,24 @@ object RouteUtilV1 { // Optionally log the request message. TODO: move this to the testing framework. _ = if (settings.dumpMessages) { - log.debug(requestMessage.toString) - } + log.debug(requestMessage.toString) + } // Make sure the responder sent a reply of type ReplyMessageT. knoraResponse <- (responderManager ? requestMessage).map { - case replyMessage: ReplyMessageT => replyMessage + case replyMessage: ReplyMessageT => replyMessage - case other => - // The responder returned an unexpected message type. This isn't the client's fault, so - // log the error and notify the client. - val msg = s"Responder sent a reply of type ${other.getClass.getCanonicalName}" - throw UnexpectedMessageException(msg) - } + case other => + // The responder returned an unexpected message type. This isn't the client's fault, so + // log the error and notify the client. + val msg = s"Responder sent a reply of type ${other.getClass.getCanonicalName}" + throw UnexpectedMessageException(msg) + } // Optionally log the reply message. TODO: move this to the testing framework. _ = if (settings.dumpMessages) { - log.debug(knoraResponse.toString) - } + log.debug(knoraResponse.toString) + } } yield HttpResponse( status = StatusCodes.OK, @@ -217,17 +220,17 @@ object RouteUtilV1 { // get the mapping directly from v2 responder directly (to avoid useless back and forth conversions between v2 and v1 message formats) mappingResponse: GetMappingResponseV2 <- (responderManager ? GetMappingRequestV2( - mappingIri = mappingIri, - featureFactoryConfig = featureFactoryConfig, - requestingUser = userProfile - )).mapTo[GetMappingResponseV2] + mappingIri = mappingIri, + featureFactoryConfig = featureFactoryConfig, + requestingUser = userProfile + )).mapTo[GetMappingResponseV2] textWithStandoffTagV1 = StandoffTagUtilV2.convertXMLtoStandoffTagV2( - xml = xml, - mapping = mappingResponse, - acceptStandoffLinksToClientIDs = acceptStandoffLinksToClientIDs, - log = log - ) + xml = xml, + mapping = mappingResponse, + acceptStandoffLinksToClientIDs = acceptStandoffLinksToClientIDs, + log = log + ) } yield textWithStandoffTagV1 diff --git a/webapi/src/main/scala/org/knora/webapi/routing/RouteUtilV2.scala b/webapi/src/main/scala/org/knora/webapi/routing/RouteUtilV2.scala index 83cfe362b1..ccf3b03125 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/RouteUtilV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/RouteUtilV2.scala @@ -222,18 +222,20 @@ object RouteUtilV2 { val httpResponse: Future[HttpResponse] = for { // Make sure the responder sent a reply of type KnoraResponseV2. knoraResponse <- (responderManager ? requestMessage).map { - case replyMessage: KnoraResponseV2 => replyMessage + case replyMessage: KnoraResponseV2 => replyMessage - case other => - // The responder returned an unexpected message type (not an exception). This isn't the client's - // fault, so log it and return an error message to the client. - throw UnexpectedMessageException(s"Responder sent a reply of type ${other.getClass.getCanonicalName}") - } + case other => + // The responder returned an unexpected message type (not an exception). This isn't the client's + // fault, so log it and return an error message to the client. + throw UnexpectedMessageException( + s"Responder sent a reply of type ${other.getClass.getCanonicalName}" + ) + } // Optionally log the reply message. TODO: move this to the testing framework. _ = if (settings.dumpMessages) { - log.debug(knoraResponse.toString) - } + log.debug(knoraResponse.toString) + } // Choose a media type for the response. responseMediaType: MediaType.NonBinary = chooseRdfMediaTypeForResponse(requestContext) @@ -246,12 +248,12 @@ object RouteUtilV2 { // Format the response message. formattedResponseContent: String = knoraResponse.format( - rdfFormat = RdfFormat.fromMediaType(specificMediaType), - targetSchema = targetSchema, - settings = settings, - featureFactoryConfig = featureFactoryConfig, - schemaOptions = schemaOptions - ) + rdfFormat = RdfFormat.fromMediaType(specificMediaType), + targetSchema = targetSchema, + settings = settings, + featureFactoryConfig = featureFactoryConfig, + schemaOptions = schemaOptions + ) } yield featureFactoryConfig.addHeaderToHttpResponse( HttpResponse( status = StatusCodes.OK, @@ -296,13 +298,15 @@ object RouteUtilV2 { requestMessage <- requestMessageF teiResponse <- (responderManager ? requestMessage).map { - case replyMessage: ResourceTEIGetResponseV2 => replyMessage + case replyMessage: ResourceTEIGetResponseV2 => replyMessage - case other => - // The responder returned an unexpected message type (not an exception). This isn't the client's - // fault, so log it and return an error message to the client. - throw UnexpectedMessageException(s"Responder sent a reply of type ${other.getClass.getCanonicalName}") - } + case other => + // The responder returned an unexpected message type (not an exception). This isn't the client's + // fault, so log it and return an error message to the client. + throw UnexpectedMessageException( + s"Responder sent a reply of type ${other.getClass.getCanonicalName}" + ) + } } yield featureFactoryConfig.addHeaderToHttpResponse( HttpResponse( @@ -345,15 +349,15 @@ object RouteUtilV2 { for { requestMessage <- requestMessageF routeResult <- runRdfRoute( - requestMessage = requestMessage, - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - responderManager = responderManager, - log = log, - targetSchema = targetSchema, - schemaOptions = schemaOptions - ) + requestMessage = requestMessage, + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + responderManager = responderManager, + log = log, + targetSchema = targetSchema, + schemaOptions = schemaOptions + ) } yield routeResult diff --git a/webapi/src/main/scala/org/knora/webapi/routing/SwaggerApiDocsRoute.scala b/webapi/src/main/scala/org/knora/webapi/routing/SwaggerApiDocsRoute.scala index dfb26f22f2..5a6b53487b 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/SwaggerApiDocsRoute.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/SwaggerApiDocsRoute.scala @@ -41,12 +41,12 @@ class SwaggerApiDocsRoute(routeData: KnoraRouteData) extends KnoraRoute(routeDat // swagger will publish at: http://locahost:3333/api-docs/swagger.json - override val host: String = settings.externalKnoraApiHostPort // the url of your api, not swagger's json endpoint - override val basePath = "/" //the basePath for the API you are exposing - override val apiDocsPath = "api-docs" //where you want the swagger-json endpoint exposed - override val info: Info = Info(version = "1.8.0") //provides license and other description details + override val host: String = settings.externalKnoraApiHostPort // the url of your api, not swagger's json endpoint + override val basePath = "/" //the basePath for the API you are exposing + override val apiDocsPath = "api-docs" //where you want the swagger-json endpoint exposed + override val info: Info = Info(version = "1.8.0") //provides license and other description details override val externalDocs: Option[ExternalDocs] = Some(new ExternalDocs("Knora Docs", "http://docs.knora.org")) - override val securitySchemeDefinitions = Map("basicAuth" -> new BasicAuthDefinition()) + override val securitySchemeDefinitions = Map("basicAuth" -> new BasicAuthDefinition()) /** * Returns the route. diff --git a/webapi/src/main/scala/org/knora/webapi/routing/VersionRoute.scala b/webapi/src/main/scala/org/knora/webapi/routing/VersionRoute.scala index 3fc64993b2..87f7158477 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/VersionRoute.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/VersionRoute.scala @@ -24,20 +24,20 @@ trait VersionCheck { override implicit val timeout: Timeout = 1.second protected def createResponse(): HttpResponse = { - val sipiVersion: String = BuildInfo.sipi.split(":").apply(1) - val fusekiVersion: String = BuildInfo.fuseki.split(":").apply(1) + val sipiVersion: String = BuildInfo.sipi.split(":").apply(1) + val fusekiVersion: String = BuildInfo.fuseki.split(":").apply(1) HttpResponse( status = StatusCodes.OK, entity = HttpEntity( ContentTypes.`application/json`, JsObject( - "name" -> JsString("version"), - "webapi" -> JsString(BuildInfo.version), - "scala" -> JsString(BuildInfo.scalaVersion), + "name" -> JsString("version"), + "webapi" -> JsString(BuildInfo.version), + "scala" -> JsString(BuildInfo.scalaVersion), "akkaHttp" -> JsString(BuildInfo.akkaHttp), - "sipi" -> JsString(sipiVersion), - "fuseki" -> JsString(fusekiVersion) + "sipi" -> JsString(sipiVersion), + "fuseki" -> JsString(fusekiVersion) ).prettyPrint ) ) diff --git a/webapi/src/main/scala/org/knora/webapi/routing/admin/GroupsRouteADM.scala b/webapi/src/main/scala/org/knora/webapi/routing/admin/GroupsRouteADM.scala index 3e27ccc3b2..fc6d07daf2 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/admin/GroupsRouteADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/admin/GroupsRouteADM.scala @@ -51,9 +51,9 @@ class GroupsRouteADM(routeData: KnoraRouteData) get { requestContext => val requestMessage = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield GroupsGetRequestADM( featureFactoryConfig = featureFactoryConfig, requestingUser = requestingUser @@ -80,9 +80,9 @@ class GroupsRouteADM(routeData: KnoraRouteData) val requestMessage = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield GroupGetRequestADM( groupIri = checkedGroupIri, featureFactoryConfig = featureFactoryConfig, @@ -111,9 +111,9 @@ class GroupsRouteADM(routeData: KnoraRouteData) val requestMessage = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield GroupMembersGetRequestADM( groupIri = checkedGroupIri, featureFactoryConfig = featureFactoryConfig, @@ -137,18 +137,18 @@ class GroupsRouteADM(routeData: KnoraRouteData) private def createGroup(featureFactoryConfig: FeatureFactoryConfig): Route = path(GroupsBasePath) { post { entity(as[CreateGroupApiRequestADM]) { apiRequest => requestContext => - val id: Validation[Throwable, Option[GroupIRI]] = GroupIRI.make(apiRequest.id) - val name: Validation[Throwable, GroupName] = GroupName.make(apiRequest.name) + val id: Validation[Throwable, Option[GroupIRI]] = GroupIRI.make(apiRequest.id) + val name: Validation[Throwable, GroupName] = GroupName.make(apiRequest.name) val descriptions: Validation[Throwable, GroupDescriptions] = GroupDescriptions.make(apiRequest.descriptions) - val project: Validation[Throwable, ProjectIRI] = ProjectIRI.make(apiRequest.project) - val status: Validation[Throwable, GroupStatus] = GroupStatus.make(apiRequest.status) - val selfjoin: Validation[Throwable, GroupSelfJoin] = GroupSelfJoin.make(apiRequest.selfjoin) + val project: Validation[Throwable, ProjectIRI] = ProjectIRI.make(apiRequest.project) + val status: Validation[Throwable, GroupStatus] = GroupStatus.make(apiRequest.status) + val selfjoin: Validation[Throwable, GroupSelfJoin] = GroupSelfJoin.make(apiRequest.selfjoin) val validatedGroupCreatePayload: Validation[Throwable, GroupCreatePayloadADM] = Validation.validateWith(id, name, descriptions, project, status, selfjoin)(GroupCreatePayloadADM) val requestMessage = for { - payload <- toFuture(validatedGroupCreatePayload) + payload <- toFuture(validatedGroupCreatePayload) requestingUser <- getUserADM(requestContext, featureFactoryConfig) } yield GroupCreateRequestADM( createRequest = payload, @@ -191,14 +191,14 @@ class GroupsRouteADM(routeData: KnoraRouteData) val name: Validation[Throwable, Option[GroupName]] = GroupName.make(apiRequest.name) val descriptions: Validation[Throwable, Option[GroupDescriptions]] = GroupDescriptions.make(apiRequest.descriptions) - val status: Validation[Throwable, Option[GroupStatus]] = GroupStatus.make(apiRequest.status) + val status: Validation[Throwable, Option[GroupStatus]] = GroupStatus.make(apiRequest.status) val selfjoin: Validation[Throwable, Option[GroupSelfJoin]] = GroupSelfJoin.make(apiRequest.selfjoin) val validatedGroupUpdatePayload: Validation[Throwable, GroupUpdatePayloadADM] = Validation.validateWith(name, descriptions, status, selfjoin)(GroupUpdatePayloadADM) val requestMessage = for { - payload <- toFuture(validatedGroupUpdatePayload) + payload <- toFuture(validatedGroupUpdatePayload) requestingUser <- getUserADM(requestContext, featureFactoryConfig) } yield GroupChangeRequestADM( groupIri = checkedGroupIri, @@ -243,9 +243,9 @@ class GroupsRouteADM(routeData: KnoraRouteData) val requestMessage = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield GroupChangeStatusRequestADM( groupIri = checkedGroupIri, changeGroupRequest = apiRequest, @@ -276,9 +276,9 @@ class GroupsRouteADM(routeData: KnoraRouteData) val requestMessage = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield GroupChangeStatusRequestADM( groupIri = checkedGroupIri, changeGroupRequest = ChangeGroupApiRequestADM(status = Some(false)), diff --git a/webapi/src/main/scala/org/knora/webapi/routing/admin/ListsRouteADM.scala b/webapi/src/main/scala/org/knora/webapi/routing/admin/ListsRouteADM.scala index 088ab232b0..643cc07254 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/admin/ListsRouteADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/admin/ListsRouteADM.scala @@ -15,7 +15,7 @@ import org.knora.webapi.routing.{KnoraRoute, KnoraRouteData} * Provides an akka-http-routing function for API routes that deal with lists. */ class ListsRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) { - private val oldListRoute: OldListsRouteADMFeature = new OldListsRouteADMFeature(routeData) + private val oldListRoute: OldListsRouteADMFeature = new OldListsRouteADMFeature(routeData) private val deleteNodeRoute: DeleteListItemsRouteADM = new DeleteListItemsRouteADM(routeData) private val updateNodeRoute: UpdateListItemsRouteADM = new UpdateListItemsRouteADM(routeData) diff --git a/webapi/src/main/scala/org/knora/webapi/routing/admin/PermissionsRouteADM.scala b/webapi/src/main/scala/org/knora/webapi/routing/admin/PermissionsRouteADM.scala index 51015906c4..c9c3843821 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/admin/PermissionsRouteADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/admin/PermissionsRouteADM.scala @@ -16,7 +16,7 @@ import org.knora.webapi.routing.{KnoraRoute, KnoraRouteData} */ class PermissionsRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) { private val createPermissionRoute: CreatePermissionRouteADM = new CreatePermissionRouteADM(routeData) - private val getPermissionRoute: GetPermissionsRouteADM = new GetPermissionsRouteADM(routeData) + private val getPermissionRoute: GetPermissionsRouteADM = new GetPermissionsRouteADM(routeData) private val updatePermissionRoute: UpdatePermissionRouteADM = new UpdatePermissionRouteADM(routeData) private val deletePermissionRoute: DeletePermissionRouteADM = new DeletePermissionRouteADM(routeData) diff --git a/webapi/src/main/scala/org/knora/webapi/routing/admin/ProjectsRouteADM.scala b/webapi/src/main/scala/org/knora/webapi/routing/admin/ProjectsRouteADM.scala index 6c342c2d17..90ac5f984c 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/admin/ProjectsRouteADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/admin/ProjectsRouteADM.scala @@ -83,9 +83,9 @@ class ProjectsRouteADM(routeData: KnoraRouteData) get { requestContext => val requestMessage: Future[ProjectsGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield ProjectsGetRequestADM( featureFactoryConfig = featureFactoryConfig, requestingUser = requestingUser @@ -129,15 +129,15 @@ class ProjectsRouteADM(routeData: KnoraRouteData) post { entity(as[CreateProjectApiRequestADM]) { apiRequest => requestContext => // zio prelude: validation - val id: Validation[Throwable, Option[ProjectIRI]] = ProjectIRI.make(apiRequest.id) - val shortname: Validation[Throwable, Shortname] = Shortname.make(apiRequest.shortname) - val shortcode: Validation[Throwable, Shortcode] = Shortcode.make(apiRequest.shortcode) - val longname: Validation[Throwable, Option[Longname]] = Longname.make(apiRequest.longname) + val id: Validation[Throwable, Option[ProjectIRI]] = ProjectIRI.make(apiRequest.id) + val shortname: Validation[Throwable, Shortname] = Shortname.make(apiRequest.shortname) + val shortcode: Validation[Throwable, Shortcode] = Shortcode.make(apiRequest.shortcode) + val longname: Validation[Throwable, Option[Longname]] = Longname.make(apiRequest.longname) val description: Validation[Throwable, ProjectDescription] = ProjectDescription.make(apiRequest.description) - val keywords: Validation[Throwable, Keywords] = Keywords.make(apiRequest.keywords) - val logo: Validation[Throwable, Option[Logo]] = Logo.make(apiRequest.logo) - val status: Validation[Throwable, ProjectStatus] = ProjectStatus.make(apiRequest.status) - val selfjoin: Validation[Throwable, ProjectSelfJoin] = ProjectSelfJoin.make(apiRequest.selfjoin) + val keywords: Validation[Throwable, Keywords] = Keywords.make(apiRequest.keywords) + val logo: Validation[Throwable, Option[Logo]] = Logo.make(apiRequest.logo) + val status: Validation[Throwable, ProjectStatus] = ProjectStatus.make(apiRequest.status) + val selfjoin: Validation[Throwable, ProjectSelfJoin] = ProjectSelfJoin.make(apiRequest.selfjoin) val projectCreatePayload: Validation[Throwable, ProjectCreatePayloadADM] = Validation.validateWith(id, shortname, shortcode, longname, description, keywords, logo, status, selfjoin)( @@ -146,7 +146,7 @@ class ProjectsRouteADM(routeData: KnoraRouteData) val requestMessage: Future[ProjectCreateRequestADM] = for { projectCreatePayload <- toFuture(projectCreatePayload) - requestingUser <- getUserADM(requestContext, featureFactoryConfig) + requestingUser <- getUserADM(requestContext, featureFactoryConfig) } yield ProjectCreateRequestADM( createRequest = projectCreatePayload, featureFactoryConfig = featureFactoryConfig, @@ -171,9 +171,9 @@ class ProjectsRouteADM(routeData: KnoraRouteData) get { requestContext => val requestMessage: Future[ProjectsKeywordsGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield ProjectsKeywordsGetRequestADM( featureFactoryConfig = featureFactoryConfig, requestingUser = requestingUser @@ -199,9 +199,9 @@ class ProjectsRouteADM(routeData: KnoraRouteData) val requestMessage: Future[ProjectKeywordsGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield ProjectKeywordsGetRequestADM( projectIri = checkedProjectIri, featureFactoryConfig = featureFactoryConfig, @@ -227,9 +227,9 @@ class ProjectsRouteADM(routeData: KnoraRouteData) get { requestContext => val requestMessage: Future[ProjectGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) checkedProjectIri = stringFormatter.validateAndEscapeProjectIri(value, throw BadRequestException(s"Invalid project IRI $value")) @@ -258,13 +258,13 @@ class ProjectsRouteADM(routeData: KnoraRouteData) get { requestContext => val requestMessage: Future[ProjectGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) shortNameDec = stringFormatter.validateAndEscapeProjectShortname( - value, - throw BadRequestException(s"Invalid project shortname $value") - ) + value, + throw BadRequestException(s"Invalid project shortname $value") + ) } yield ProjectGetRequestADM( identifier = ProjectIdentifierADM(maybeShortname = Some(shortNameDec)), @@ -291,13 +291,13 @@ class ProjectsRouteADM(routeData: KnoraRouteData) get { requestContext => val requestMessage: Future[ProjectGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) checkedShortcode = stringFormatter.validateAndEscapeProjectShortcode( - value, - throw BadRequestException(s"Invalid project shortcode $value") - ) + value, + throw BadRequestException(s"Invalid project shortcode $value") + ) } yield ProjectGetRequestADM( identifier = ProjectIdentifierADM(maybeShortcode = Some(checkedShortcode)), @@ -330,9 +330,9 @@ class ProjectsRouteADM(routeData: KnoraRouteData) val requestMessage: Future[ProjectChangeRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield ProjectChangeRequestADM( projectIri = checkedProjectIri, changeProjectRequest = apiRequest.validateAndEscape, @@ -365,9 +365,9 @@ class ProjectsRouteADM(routeData: KnoraRouteData) val requestMessage: Future[ProjectChangeRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield ProjectChangeRequestADM( projectIri = checkedProjectIri, changeProjectRequest = ChangeProjectApiRequestADM(status = Some(false)), @@ -396,9 +396,9 @@ class ProjectsRouteADM(routeData: KnoraRouteData) get { requestContext => val requestMessage: Future[ProjectMembersGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) checkedProjectIri = stringFormatter.validateAndEscapeProjectIri(value, throw BadRequestException(s"Invalid project IRI $value")) @@ -428,13 +428,13 @@ class ProjectsRouteADM(routeData: KnoraRouteData) get { requestContext => val requestMessage: Future[ProjectMembersGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) shortNameDec = stringFormatter.validateAndEscapeProjectShortname( - value, - throw BadRequestException(s"Invalid project shortname $value") - ) + value, + throw BadRequestException(s"Invalid project shortname $value") + ) } yield ProjectMembersGetRequestADM( identifier = ProjectIdentifierADM(maybeShortname = Some(shortNameDec)), @@ -462,13 +462,13 @@ class ProjectsRouteADM(routeData: KnoraRouteData) get { requestContext => val requestMessage: Future[ProjectMembersGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) checkedShortcode = stringFormatter.validateAndEscapeProjectShortcode( - value, - throw BadRequestException(s"Invalid project shortcode $value") - ) + value, + throw BadRequestException(s"Invalid project shortcode $value") + ) } yield ProjectMembersGetRequestADM( identifier = ProjectIdentifierADM(maybeShortcode = Some(checkedShortcode)), @@ -496,9 +496,9 @@ class ProjectsRouteADM(routeData: KnoraRouteData) get { requestContext => val requestMessage: Future[ProjectAdminMembersGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) checkedProjectIri = stringFormatter.validateAndEscapeProjectIri(value, throw BadRequestException(s"Invalid project IRI $value")) @@ -528,13 +528,13 @@ class ProjectsRouteADM(routeData: KnoraRouteData) get { requestContext => val requestMessage: Future[ProjectAdminMembersGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) checkedShortname = stringFormatter.validateAndEscapeProjectShortname( - value, - throw BadRequestException(s"Invalid project shortname $value") - ) + value, + throw BadRequestException(s"Invalid project shortname $value") + ) } yield ProjectAdminMembersGetRequestADM( identifier = ProjectIdentifierADM(maybeShortname = Some(checkedShortname)), @@ -562,13 +562,13 @@ class ProjectsRouteADM(routeData: KnoraRouteData) get { requestContext => val requestMessage: Future[ProjectAdminMembersGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) checkedShortcode = stringFormatter.validateProjectShortcode( - value, - throw BadRequestException(s"Invalid project shortcode $value") - ) + value, + throw BadRequestException(s"Invalid project shortcode $value") + ) } yield ProjectAdminMembersGetRequestADM( identifier = ProjectIdentifierADM(maybeShortcode = Some(checkedShortcode)), @@ -596,9 +596,9 @@ class ProjectsRouteADM(routeData: KnoraRouteData) get { requestContext => val requestMessage: Future[ProjectRestrictedViewSettingsGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield ProjectRestrictedViewSettingsGetRequestADM( identifier = ProjectIdentifierADM(maybeIri = Some(value)), @@ -626,9 +626,9 @@ class ProjectsRouteADM(routeData: KnoraRouteData) get { requestContext => val requestMessage: Future[ProjectRestrictedViewSettingsGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) shortNameDec = java.net.URLDecoder.decode(value, "utf-8") } yield ProjectRestrictedViewSettingsGetRequestADM( @@ -657,9 +657,9 @@ class ProjectsRouteADM(routeData: KnoraRouteData) get { requestContext => val requestMessage: Future[ProjectRestrictedViewSettingsGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield ProjectRestrictedViewSettingsGetRequestADM( identifier = ProjectIdentifierADM(maybeShortcode = Some(value)), featureFactoryConfig = featureFactoryConfig, @@ -713,24 +713,26 @@ class ProjectsRouteADM(routeData: KnoraRouteData) val httpEntityFuture: Future[HttpEntity.Chunked] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestMessage = ProjectDataGetRequestADM( - projectIdentifier = projectIdentifier, - featureFactoryConfig = featureFactoryConfig, - requestingUser = requestingUser - ) + projectIdentifier = projectIdentifier, + featureFactoryConfig = featureFactoryConfig, + requestingUser = requestingUser + ) responseMessage <- (responderManager ? requestMessage).mapTo[ProjectDataGetResponseADM] // Stream the output file back to the client, then delete the file. source: Source[ByteString, Unit] = FileIO.fromPath(responseMessage.projectDataFile).watchTermination() { - case (_: Future[IOResult], result: Future[Done]) => - result.onComplete((_: Try[Done]) => Files.delete(responseMessage.projectDataFile)) - } + case (_: Future[IOResult], result: Future[Done]) => + result.onComplete((_: Try[Done]) => + Files.delete(responseMessage.projectDataFile) + ) + } httpEntity = HttpEntity(ContentTypes.`application/octet-stream`, source) } yield httpEntity diff --git a/webapi/src/main/scala/org/knora/webapi/routing/admin/SipiRouteADM.scala b/webapi/src/main/scala/org/knora/webapi/routing/admin/SipiRouteADM.scala index a12a2a7c8d..76882ae113 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/admin/SipiRouteADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/admin/SipiRouteADM.scala @@ -28,17 +28,17 @@ class SipiRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) with get { requestContext => val requestMessage = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) projectID = stringFormatter.validateProjectShortcode( - projectIDAndFile.head, - throw BadRequestException(s"Invalid project ID: '${projectIDAndFile.head}'") - ) + projectIDAndFile.head, + throw BadRequestException(s"Invalid project ID: '${projectIDAndFile.head}'") + ) filename = stringFormatter.toSparqlEncodedString( - projectIDAndFile(1), - throw BadRequestException(s"Invalid filename: '${projectIDAndFile(1)}'") - ) + projectIDAndFile(1), + throw BadRequestException(s"Invalid filename: '${projectIDAndFile(1)}'") + ) _ = log.info(s"/admin/files route called for filename $filename") } yield SipiFileInfoGetRequestADM( projectID = projectID, diff --git a/webapi/src/main/scala/org/knora/webapi/routing/admin/UsersRouteADM.scala b/webapi/src/main/scala/org/knora/webapi/routing/admin/UsersRouteADM.scala index 99cae9e520..af499422d5 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/admin/UsersRouteADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/admin/UsersRouteADM.scala @@ -69,9 +69,9 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit get { requestContext => val requestMessage: Future[UsersGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield UsersGetRequestADM( featureFactoryConfig = featureFactoryConfig, requestingUser = requestingUser @@ -115,15 +115,15 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit post { entity(as[CreateUserApiRequestADM]) { apiRequest => requestContext => // get all values from request and make value objects from it - val id: Validation[Throwable, Option[UserIRI]] = UserIRI.make(apiRequest.id) - val username: Validation[Throwable, Username] = Username.make(apiRequest.username) - val email: Validation[Throwable, Email] = Email.make(apiRequest.email) - val givenName: Validation[Throwable, GivenName] = GivenName.make(apiRequest.givenName) - val familyName: Validation[Throwable, FamilyName] = FamilyName.make(apiRequest.familyName) - val password: Validation[Throwable, Password] = Password.make(apiRequest.password) - val status: Validation[Throwable, UserStatus] = UserStatus.make(apiRequest.status) + val id: Validation[Throwable, Option[UserIRI]] = UserIRI.make(apiRequest.id) + val username: Validation[Throwable, Username] = Username.make(apiRequest.username) + val email: Validation[Throwable, Email] = Email.make(apiRequest.email) + val givenName: Validation[Throwable, GivenName] = GivenName.make(apiRequest.givenName) + val familyName: Validation[Throwable, FamilyName] = FamilyName.make(apiRequest.familyName) + val password: Validation[Throwable, Password] = Password.make(apiRequest.password) + val status: Validation[Throwable, UserStatus] = UserStatus.make(apiRequest.status) val languageCode: Validation[Throwable, LanguageCode] = LanguageCode.make(apiRequest.lang) - val systemAdmin: Validation[Throwable, SystemAdmin] = SystemAdmin.make(apiRequest.systemAdmin) + val systemAdmin: Validation[Throwable, SystemAdmin] = SystemAdmin.make(apiRequest.systemAdmin) val validatedUserCreatePayload: Validation[Throwable, UserCreatePayloadADM] = Validation.validateWith( @@ -139,7 +139,7 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit )(UserCreatePayloadADM) val requestMessage: Future[UserCreateRequestADM] = for { - payload <- toFuture(validatedUserCreatePayload) + payload <- toFuture(validatedUserCreatePayload) requestingUser <- getUserADM(requestContext, featureFactoryConfig) } yield UserCreateRequestADM( userCreatePayloadADM = payload, @@ -168,9 +168,9 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit get { requestContext => val requestMessage: Future[UserGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield UserGetRequestADM( identifier = UserIdentifierADM(maybeIri = Some(userIri)), userInformationTypeADM = UserInformationTypeADM.Restricted, @@ -197,9 +197,9 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit get { requestContext => val requestMessage: Future[UserGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield UserGetRequestADM( identifier = UserIdentifierADM(maybeEmail = Some(userIri)), userInformationTypeADM = UserInformationTypeADM.Restricted, @@ -226,9 +226,9 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit get { requestContext => val requestMessage: Future[UserGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield UserGetRequestADM( identifier = UserIdentifierADM(maybeUsername = Some(userIri)), userInformationTypeADM = UserInformationTypeADM.Restricted, @@ -268,8 +268,8 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit throw BadRequestException("Changes to built-in users are not allowed.") } - val maybeUsername: Option[Username] = Username.make(apiRequest.username).fold(e => throw e.head, v => v) - val maybeEmail: Option[Email] = Email.make(apiRequest.email).fold(e => throw e.head, v => v) + val maybeUsername: Option[Username] = Username.make(apiRequest.username).fold(e => throw e.head, v => v) + val maybeEmail: Option[Email] = Email.make(apiRequest.email).fold(e => throw e.head, v => v) val maybeGivenName: Option[GivenName] = GivenName.make(apiRequest.givenName).fold(e => throw e.head, v => v) val maybeFamilyName: Option[FamilyName] = FamilyName.make(apiRequest.familyName).fold(e => throw e.head, v => v) @@ -288,9 +288,9 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit /* the api request is already checked at time of creation. see case class. */ val requestMessage: Future[UsersResponderRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield UserChangeBasicInformationRequestADM( userIri = checkedUserIri, userUpdateBasicInformationPayload = userUpdatePayload, @@ -343,9 +343,9 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessage: Future[UsersResponderRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield UserChangePasswordRequestADM( userIri = checkedUserIri, userUpdatePasswordPayload = UserUpdatePasswordPayloadADM(requesterPassword, changedPassword), @@ -394,9 +394,9 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessage: Future[UsersResponderRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield UserChangeStatusRequestADM( userIri = checkedUserIri, status = newStatus, @@ -442,9 +442,9 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessage: Future[UserChangeStatusRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield UserChangeStatusRequestADM( userIri = checkedUserIri, status = status, @@ -492,9 +492,9 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessage: Future[UsersResponderRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield UserChangeSystemAdminMembershipStatusRequestADM( userIri = checkedUserIri, systemAdmin = newSystemAdmin, @@ -529,9 +529,9 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessage: Future[UserProjectMembershipsGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield UserProjectMembershipsGetRequestADM( userIri = checkedUserIri, featureFactoryConfig = featureFactoryConfig, @@ -577,9 +577,9 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessage: Future[UserProjectMembershipAddRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield UserProjectMembershipAddRequestADM( userIri = checkedUserIri, projectIri = checkedProjectIri, @@ -627,9 +627,9 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessage: Future[UserProjectMembershipRemoveRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield UserProjectMembershipRemoveRequestADM( userIri = checkedUserIri, projectIri = checkedProjectIri, @@ -663,9 +663,9 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessage: Future[UserProjectAdminMembershipsGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield UserProjectAdminMembershipsGetRequestADM( userIri = checkedUserIri, featureFactoryConfig = featureFactoryConfig, @@ -712,9 +712,9 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessage: Future[UserProjectAdminMembershipAddRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield UserProjectAdminMembershipAddRequestADM( userIri = checkedUserIri, projectIri = checkedProjectIri, @@ -762,9 +762,9 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessage: Future[UserProjectAdminMembershipRemoveRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield UserProjectAdminMembershipRemoveRequestADM( userIri = checkedUserIri, projectIri = checkedProjectIri, @@ -798,9 +798,9 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessage: Future[UserGroupMembershipsGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield UserGroupMembershipsGetRequestADM( userIri = checkedUserIri, featureFactoryConfig = featureFactoryConfig, @@ -843,9 +843,9 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessage: Future[UserGroupMembershipAddRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield UserGroupMembershipAddRequestADM( userIri = checkedUserIri, groupIri = checkedGroupIri, @@ -890,9 +890,9 @@ class UsersRouteADM(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessage: Future[UserGroupMembershipRemoveRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield UserGroupMembershipRemoveRequestADM( userIri = checkedUserIri, groupIri = checkedGroupIri, diff --git a/webapi/src/main/scala/org/knora/webapi/routing/admin/lists/OldListsRouteADMFeature.scala b/webapi/src/main/scala/org/knora/webapi/routing/admin/lists/OldListsRouteADMFeature.scala index a52332716d..0b84d565a2 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/admin/lists/OldListsRouteADMFeature.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/admin/lists/OldListsRouteADMFeature.scala @@ -77,9 +77,9 @@ class OldListsRouteADMFeature(routeData: KnoraRouteData) val requestMessage: Future[ListsGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield ListsGetRequestADM( projectIri = projectIri, featureFactoryConfig = featureFactoryConfig, @@ -115,9 +115,9 @@ class OldListsRouteADMFeature(routeData: KnoraRouteData) val requestMessage: Future[ListGetRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield ListGetRequestADM( iri = listIri, featureFactoryConfig = featureFactoryConfig, @@ -219,27 +219,27 @@ class OldListsRouteADMFeature(routeData: KnoraRouteData) private def createListRootNode(featureFactoryConfig: FeatureFactoryConfig): Route = path(ListsBasePath) { post { entity(as[ListRootNodeCreateApiRequestADM]) { apiRequest => requestContext => - val maybeId: Validation[Throwable, Option[ListIRI]] = ListIRI.make(apiRequest.id) - val projectIri: Validation[Throwable, ProjectIRI] = ProjectIRI.make(apiRequest.projectIri) + val maybeId: Validation[Throwable, Option[ListIRI]] = ListIRI.make(apiRequest.id) + val projectIri: Validation[Throwable, ProjectIRI] = ProjectIRI.make(apiRequest.projectIri) val maybeName: Validation[Throwable, Option[ListName]] = ListName.make(apiRequest.name) - val labels: Validation[Throwable, Labels] = Labels.make(apiRequest.labels) - val comments: Validation[Throwable, Comments] = Comments.make(apiRequest.comments) + val labels: Validation[Throwable, Labels] = Labels.make(apiRequest.labels) + val comments: Validation[Throwable, Comments] = Comments.make(apiRequest.comments) val validatedListRootNodeCreatePayload: Validation[Throwable, ListRootNodeCreatePayloadADM] = Validation.validateWith(maybeId, projectIri, maybeName, labels, comments)(ListRootNodeCreatePayloadADM) val requestMessage: Future[ListRootNodeCreateRequestADM] = for { - payload <- toFuture(validatedListRootNodeCreatePayload) + payload <- toFuture(validatedListRootNodeCreatePayload) requestingUser <- getUserADM(requestContext, featureFactoryConfig) // check if the requesting user is allowed to perform operation _ = if ( - !requestingUser.permissions.isProjectAdmin( - projectIri.toOption.get.value - ) && !requestingUser.permissions.isSystemAdmin - ) { - // not project or a system admin - throw ForbiddenException(LIST_CREATE_PERMISSION_ERROR) - } + !requestingUser.permissions.isProjectAdmin( + projectIri.toOption.get.value + ) && !requestingUser.permissions.isSystemAdmin + ) { + // not project or a system admin + throw ForbiddenException(LIST_CREATE_PERMISSION_ERROR) + } } yield ListRootNodeCreateRequestADM( createRootNode = payload, featureFactoryConfig = featureFactoryConfig, @@ -296,11 +296,11 @@ class OldListsRouteADMFeature(routeData: KnoraRouteData) Validation.fail(throw BadRequestException("Route and payload parentNodeIri mismatch.")) } - val id: Validation[Throwable, Option[ListIRI]] = ListIRI.make(apiRequest.id) - val projectIri: Validation[Throwable, ProjectIRI] = ProjectIRI.make(apiRequest.projectIri) - val name: Validation[Throwable, Option[ListName]] = ListName.make(apiRequest.name) + val id: Validation[Throwable, Option[ListIRI]] = ListIRI.make(apiRequest.id) + val projectIri: Validation[Throwable, ProjectIRI] = ProjectIRI.make(apiRequest.projectIri) + val name: Validation[Throwable, Option[ListName]] = ListName.make(apiRequest.name) val position: Validation[Throwable, Option[Position]] = Position.make(apiRequest.position) - val labels: Validation[Throwable, Labels] = Labels.make(apiRequest.labels) + val labels: Validation[Throwable, Labels] = Labels.make(apiRequest.labels) val comments: Validation[Throwable, Option[Comments]] = Comments.make(apiRequest.comments) val validatedCreateChildNodePeyload: Validation[Throwable, ListChildNodeCreatePayloadADM] = Validation.validateWith(id, parentNodeIri, projectIri, name, position, labels, comments)( @@ -308,18 +308,18 @@ class OldListsRouteADMFeature(routeData: KnoraRouteData) ) val requestMessage: Future[ListChildNodeCreateRequestADM] = for { - payload <- toFuture(validatedCreateChildNodePeyload) + payload <- toFuture(validatedCreateChildNodePeyload) requestingUser <- getUserADM(requestContext, featureFactoryConfig) // check if the requesting user is allowed to perform operation _ = if ( - !requestingUser.permissions.isProjectAdmin( - projectIri.toOption.get.value - ) && !requestingUser.permissions.isSystemAdmin - ) { - // not project or a system admin - throw ForbiddenException(LIST_CREATE_PERMISSION_ERROR) - } + !requestingUser.permissions.isProjectAdmin( + projectIri.toOption.get.value + ) && !requestingUser.permissions.isSystemAdmin + ) { + // not project or a system admin + throw ForbiddenException(LIST_CREATE_PERMISSION_ERROR) + } } yield ListChildNodeCreateRequestADM( createChildNodeRequest = payload, featureFactoryConfig = featureFactoryConfig, @@ -375,12 +375,12 @@ class OldListsRouteADMFeature(routeData: KnoraRouteData) Validation.fail(throw BadRequestException("Route and payload listIri mismatch.")) } - val projectIri: Validation[Throwable, ProjectIRI] = ProjectIRI.make(apiRequest.projectIri) + val projectIri: Validation[Throwable, ProjectIRI] = ProjectIRI.make(apiRequest.projectIri) val hasRootNode: Validation[Throwable, Option[ListIRI]] = ListIRI.make(apiRequest.hasRootNode) - val position: Validation[Throwable, Option[Position]] = Position.make(apiRequest.position) - val name: Validation[Throwable, Option[ListName]] = ListName.make(apiRequest.name) - val labels: Validation[Throwable, Option[Labels]] = Labels.make(apiRequest.labels) - val comments: Validation[Throwable, Option[Comments]] = Comments.make(apiRequest.comments) + val position: Validation[Throwable, Option[Position]] = Position.make(apiRequest.position) + val name: Validation[Throwable, Option[ListName]] = ListName.make(apiRequest.name) + val labels: Validation[Throwable, Option[Labels]] = Labels.make(apiRequest.labels) + val comments: Validation[Throwable, Option[Comments]] = Comments.make(apiRequest.comments) val validatedChangeNodeInfoPayload: Validation[Throwable, ListNodeChangePayloadADM] = Validation.validateWith(listIri, projectIri, hasRootNode, position, name, labels, comments)( @@ -388,17 +388,17 @@ class OldListsRouteADMFeature(routeData: KnoraRouteData) ) val requestMessage: Future[NodeInfoChangeRequestADM] = for { - payload <- toFuture(validatedChangeNodeInfoPayload) + payload <- toFuture(validatedChangeNodeInfoPayload) requestingUser <- getUserADM(requestContext, featureFactoryConfig) // check if the requesting user is allowed to perform operation _ = if ( - !requestingUser.permissions.isProjectAdmin( - projectIri.toOption.get.value - ) && !requestingUser.permissions.isSystemAdmin - ) { - // not project or a system admin - throw ForbiddenException(LIST_NODE_CREATE_PERMISSION_ERROR) - } + !requestingUser.permissions.isProjectAdmin( + projectIri.toOption.get.value + ) && !requestingUser.permissions.isSystemAdmin + ) { + // not project or a system admin + throw ForbiddenException(LIST_NODE_CREATE_PERMISSION_ERROR) + } } yield NodeInfoChangeRequestADM( listIri = listIri.toOption.get.value, changeNodeRequest = payload, diff --git a/webapi/src/main/scala/org/knora/webapi/routing/admin/permissions/CreatePermissionRouteADM.scala b/webapi/src/main/scala/org/knora/webapi/routing/admin/permissions/CreatePermissionRouteADM.scala index 16ed9f87df..64dd15a388 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/admin/permissions/CreatePermissionRouteADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/admin/permissions/CreatePermissionRouteADM.scala @@ -47,9 +47,9 @@ class CreatePermissionRouteADM(routeData: KnoraRouteData) entity(as[CreateAdministrativePermissionAPIRequestADM]) { apiRequest => requestContext => val requestMessage = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield AdministrativePermissionCreateRequestADM( createRequest = apiRequest, featureFactoryConfig = featureFactoryConfig, @@ -79,9 +79,9 @@ class CreatePermissionRouteADM(routeData: KnoraRouteData) entity(as[CreateDefaultObjectAccessPermissionAPIRequestADM]) { apiRequest => requestContext => val requestMessage: Future[DefaultObjectAccessPermissionCreateRequestADM] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield DefaultObjectAccessPermissionCreateRequestADM( createRequest = apiRequest, featureFactoryConfig = featureFactoryConfig, diff --git a/webapi/src/main/scala/org/knora/webapi/routing/admin/permissions/DeletePermissionRouteADM.scala b/webapi/src/main/scala/org/knora/webapi/routing/admin/permissions/DeletePermissionRouteADM.scala index bd317c9341..284436d274 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/admin/permissions/DeletePermissionRouteADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/admin/permissions/DeletePermissionRouteADM.scala @@ -43,9 +43,9 @@ class DeletePermissionRouteADM(routeData: KnoraRouteData) delete { requestContext => val requestMessage = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield PermissionDeleteRequestADM( permissionIri = iri, requestingUser = requestingUser, diff --git a/webapi/src/main/scala/org/knora/webapi/routing/admin/permissions/GetPermissionsRouteADM.scala b/webapi/src/main/scala/org/knora/webapi/routing/admin/permissions/GetPermissionsRouteADM.scala index 3c55f4aed3..5d83d030fe 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/admin/permissions/GetPermissionsRouteADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/admin/permissions/GetPermissionsRouteADM.scala @@ -42,9 +42,9 @@ class GetPermissionsRouteADM(routeData: KnoraRouteData) get { requestContext => val requestMessage = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield AdministrativePermissionForProjectGroupGetRequestADM(projectIri, groupIri, requestingUser) RouteUtilADM.runJsonRoute( @@ -63,9 +63,9 @@ class GetPermissionsRouteADM(routeData: KnoraRouteData) get { requestContext => val requestMessage = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield AdministrativePermissionsForProjectGetRequestADM( projectIri = projectIri, requestingUser = requestingUser, @@ -88,9 +88,9 @@ class GetPermissionsRouteADM(routeData: KnoraRouteData) get { requestContext => val requestMessage = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield DefaultObjectAccessPermissionsForProjectGetRequestADM( projectIri = projectIri, requestingUser = requestingUser, @@ -113,9 +113,9 @@ class GetPermissionsRouteADM(routeData: KnoraRouteData) get { requestContext => val requestMessage = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield PermissionsForProjectGetRequestADM( projectIri = projectIri, featureFactoryConfig = featureFactoryConfig, diff --git a/webapi/src/main/scala/org/knora/webapi/routing/admin/permissions/UpdatePermissionRouteADM.scala b/webapi/src/main/scala/org/knora/webapi/routing/admin/permissions/UpdatePermissionRouteADM.scala index 5e365d58ce..4719c6041a 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/admin/permissions/UpdatePermissionRouteADM.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/admin/permissions/UpdatePermissionRouteADM.scala @@ -50,9 +50,9 @@ class UpdatePermissionRouteADM(routeData: KnoraRouteData) val requestMessage = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield PermissionChangeGroupRequestADM( permissionIri = permissionIri, changePermissionGroupRequest = apiRequest, @@ -84,9 +84,9 @@ class UpdatePermissionRouteADM(routeData: KnoraRouteData) val requestMessage = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield PermissionChangeHasPermissionsRequestADM( permissionIri = permissionIri, changePermissionHasPermissionsRequest = apiRequest, @@ -118,9 +118,9 @@ class UpdatePermissionRouteADM(routeData: KnoraRouteData) val requestMessage = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield PermissionChangeResourceClassRequestADM( permissionIri = permissionIri, changePermissionResourceClassRequest = apiRequest, @@ -152,9 +152,9 @@ class UpdatePermissionRouteADM(routeData: KnoraRouteData) val requestMessage = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield PermissionChangePropertyRequestADM( permissionIri = permissionIri, changePermissionPropertyRequest = apiRequest, diff --git a/webapi/src/main/scala/org/knora/webapi/routing/v1/AssetsRouteV1.scala b/webapi/src/main/scala/org/knora/webapi/routing/v1/AssetsRouteV1.scala index 5f2317574c..a203900449 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/v1/AssetsRouteV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/v1/AssetsRouteV1.scala @@ -42,7 +42,7 @@ class AssetsRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit tmpImage } else { /* make dummy images with the image name as content */ - val tmpImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) + val tmpImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB) val g: Graphics = tmpImage.getGraphics //g.setColor(new Color(0,0,0)) //background color g.setColor(new Color(255, 125, 65)) //background color diff --git a/webapi/src/main/scala/org/knora/webapi/routing/v1/CkanRouteV1.scala b/webapi/src/main/scala/org/knora/webapi/routing/v1/CkanRouteV1.scala index 2c9c1b736e..61dd452388 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/v1/CkanRouteV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/v1/CkanRouteV1.scala @@ -24,13 +24,13 @@ class CkanRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) with get { requestContext => val requestMessage = for { userProfile <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) - params = requestContext.request.uri.query().toMap + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) + params = requestContext.request.uri.query().toMap project: Option[Seq[String]] = params.get("project").map(_.split(",").toSeq) - limit: Option[Int] = params.get("limit").map(_.toInt) - info: Boolean = params.getOrElse("info", false) == true + limit: Option[Int] = params.get("limit").map(_.toInt) + info: Boolean = params.getOrElse("info", false) == true } yield CkanRequestV1( projects = project, limit = limit, diff --git a/webapi/src/main/scala/org/knora/webapi/routing/v1/ListsRouteV1.scala b/webapi/src/main/scala/org/knora/webapi/routing/v1/ListsRouteV1.scala index ede237b9f8..9c4ca28113 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/v1/ListsRouteV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/v1/ListsRouteV1.scala @@ -29,19 +29,19 @@ class ListsRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) with get { requestContext => val requestMessageFuture = for { userProfile <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ).map(_.asUserProfileV1) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ).map(_.asUserProfileV1) listIri = stringFormatter.validateAndEscapeIri( - iri, - throw BadRequestException(s"Invalid param list IRI: $iri") - ) + iri, + throw BadRequestException(s"Invalid param list IRI: $iri") + ) requestMessage = requestContext.request.uri.query().get("reqtype") match { - case Some("node") => NodePathGetRequestV1(listIri, userProfile) - case Some(reqtype) => throw BadRequestException(s"Invalid reqtype: $reqtype") - case None => HListGetRequestV1(listIri, userProfile) - } + case Some("node") => NodePathGetRequestV1(listIri, userProfile) + case Some(reqtype) => throw BadRequestException(s"Invalid reqtype: $reqtype") + case None => HListGetRequestV1(listIri, userProfile) + } } yield requestMessage RouteUtilV1.runJsonRouteWithFuture( @@ -57,19 +57,19 @@ class ListsRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) with get { requestContext => val requestMessageFuture = for { userProfile <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ).map(_.asUserProfileV1) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ).map(_.asUserProfileV1) selIri = stringFormatter.validateAndEscapeIri( - iri, - throw BadRequestException(s"Invalid param list IRI: $iri") - ) + iri, + throw BadRequestException(s"Invalid param list IRI: $iri") + ) requestMessage = requestContext.request.uri.query().get("reqtype") match { - case Some("node") => NodePathGetRequestV1(selIri, userProfile) - case Some(reqtype) => throw BadRequestException(s"Invalid reqtype: $reqtype") - case None => SelectionGetRequestV1(selIri, userProfile) - } + case Some("node") => NodePathGetRequestV1(selIri, userProfile) + case Some(reqtype) => throw BadRequestException(s"Invalid reqtype: $reqtype") + case None => SelectionGetRequestV1(selIri, userProfile) + } } yield requestMessage RouteUtilV1.runJsonRouteWithFuture( diff --git a/webapi/src/main/scala/org/knora/webapi/routing/v1/ProjectsRouteV1.scala b/webapi/src/main/scala/org/knora/webapi/routing/v1/ProjectsRouteV1.scala index 7de17fab01..c6b2c82960 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/v1/ProjectsRouteV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/v1/ProjectsRouteV1.scala @@ -27,9 +27,9 @@ class ProjectsRouteV1(routeData: KnoraRouteData) requestContext => val requestMessage = for { userProfile <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ).map(_.asUserProfileV1) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ).map(_.asUserProfileV1) } yield ProjectsGetRequestV1( featureFactoryConfig = featureFactoryConfig, userProfile = Some(userProfile) @@ -51,9 +51,9 @@ class ProjectsRouteV1(routeData: KnoraRouteData) val shortNameDec = java.net.URLDecoder.decode(value, "utf-8") for { userProfile <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ).map(_.asUserProfileV1) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ).map(_.asUserProfileV1) } yield ProjectInfoByShortnameGetRequestV1( shortname = shortNameDec, featureFactoryConfig = featureFactoryConfig, @@ -64,9 +64,9 @@ class ProjectsRouteV1(routeData: KnoraRouteData) stringFormatter.validateAndEscapeIri(value, throw BadRequestException(s"Invalid project IRI $value")) for { userProfile <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ).map(_.asUserProfileV1) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ).map(_.asUserProfileV1) } yield ProjectInfoByIRIGetRequestV1( iri = checkedProjectIri, featureFactoryConfig = featureFactoryConfig, diff --git a/webapi/src/main/scala/org/knora/webapi/routing/v1/ResourceTypesRouteV1.scala b/webapi/src/main/scala/org/knora/webapi/routing/v1/ResourceTypesRouteV1.scala index 89e1952664..8da8fbf2ee 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/v1/ResourceTypesRouteV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/v1/ResourceTypesRouteV1.scala @@ -26,15 +26,15 @@ class ResourceTypesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeDa get { requestContext => val requestMessage = for { userProfile <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) // TODO: Check that this is the IRI of a resource type and not just any IRI resourceTypeIri = stringFormatter.validateAndEscapeIri( - iri, - throw BadRequestException(s"Invalid resource class IRI: $iri") - ) + iri, + throw BadRequestException(s"Invalid resource class IRI: $iri") + ) } yield ResourceTypeGetRequestV1(resourceTypeIri, userProfile) @@ -50,26 +50,26 @@ class ResourceTypesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeDa get { requestContext => val requestMessage = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) params = requestContext.request.uri.query().toMap vocabularyId = params.getOrElse( - "vocabulary", - throw BadRequestException("Required param vocabulary is missing") - ) + "vocabulary", + throw BadRequestException("Required param vocabulary is missing") + ) namedGraphIri = vocabularyId match { - case "0" => None // if param vocabulary is set to 0, query all named graphs - case other => - Some( - stringFormatter.validateAndEscapeIri( - vocabularyId, - throw BadRequestException(s"Invalid vocabulary IRI: $vocabularyId") - ) - ) - } + case "0" => None // if param vocabulary is set to 0, query all named graphs + case other => + Some( + stringFormatter.validateAndEscapeIri( + vocabularyId, + throw BadRequestException(s"Invalid vocabulary IRI: $vocabularyId") + ) + ) + } } yield ResourceTypesForNamedGraphGetRequestV1( namedGraph = namedGraphIri, @@ -90,17 +90,17 @@ class ResourceTypesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeDa get { requestContext => val requestMessage = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) params = requestContext.request.uri.query().toMap - vocabularyId: Option[String] = params.get("vocabulary") + vocabularyId: Option[String] = params.get("vocabulary") resourcetypeId: Option[String] = params.get("restype") // either the vocabulary or the restype param is set, but not both _ = if (vocabularyId.nonEmpty && resourcetypeId.nonEmpty) - throw BadRequestException("Both vocabulary and restype params are set, only one is allowed") + throw BadRequestException("Both vocabulary and restype params are set, only one is allowed") } yield vocabularyId match { case Some("0") => // 0 means that all named graphs should be queried PropertyTypesForNamedGraphGetRequestV1( @@ -150,9 +150,9 @@ class ResourceTypesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeDa get { requestContext => val requestMessage = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield NamedGraphsGetRequestV1( featureFactoryConfig = featureFactoryConfig, userADM = userADM @@ -171,9 +171,9 @@ class ResourceTypesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeDa get { requestContext => val requestMessage = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield LoadOntologiesRequestV1( featureFactoryConfig = featureFactoryConfig, userADM = userADM @@ -191,15 +191,15 @@ class ResourceTypesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeDa get { requestContext => val requestMessage = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) // TODO: Check that this is the IRI of a resource type and not just any IRI resourceClassIri = stringFormatter.validateAndEscapeIri( - iri, - throw BadRequestException(s"Invalid resource class IRI: $iri") - ) + iri, + throw BadRequestException(s"Invalid resource class IRI: $iri") + ) } yield SubClassesGetRequestV1(resourceClassIri, userADM) RouteUtilV1.runJsonRouteWithFuture( diff --git a/webapi/src/main/scala/org/knora/webapi/routing/v1/ResourcesRouteV1.scala b/webapi/src/main/scala/org/knora/webapi/routing/v1/ResourcesRouteV1.scala index 77f9e44c8f..8573394dc0 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/v1/ResourcesRouteV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/v1/ResourcesRouteV1.scala @@ -167,20 +167,21 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) for { textWithStandoffTags: TextWithStandoffTagsV2 <- RouteUtilV1.convertXMLtoStandoffTagV1( - xml = richtext.xml.get, - mappingIri = mappingIri, - acceptStandoffLinksToClientIDs = acceptStandoffLinksToClientIDs, - userProfile = userProfile, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - responderManager = responderManager, - log = log - ) + xml = richtext.xml.get, + mappingIri = mappingIri, + acceptStandoffLinksToClientIDs = + acceptStandoffLinksToClientIDs, + userProfile = userProfile, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + responderManager = responderManager, + log = log + ) // collect the resource references from the linking standoff nodes resourceReferences: Set[IRI] = stringFormatter.getResourceIrisFromStandoffTags( - textWithStandoffTags.standoffTagV2 - ) + textWithStandoffTags.standoffTagV2 + ) } yield CreateValueV1WithComment( TextValueWithStandoffV1( @@ -312,44 +313,47 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) for { projectShortcode: String <- for { - projectResponse: ProjectGetResponseADM <- (responderManager ? ProjectGetRequestADM( - ProjectIdentifierADM(maybeIri = Some(projectIri)), - featureFactoryConfig = featureFactoryConfig, - requestingUser = userADM - )).mapTo[ProjectGetResponseADM] - } yield projectResponse.project.shortcode + projectResponse: ProjectGetResponseADM <- + (responderManager ? ProjectGetRequestADM( + ProjectIdentifierADM(maybeIri = Some(projectIri)), + featureFactoryConfig = featureFactoryConfig, + requestingUser = userADM + )).mapTo[ProjectGetResponseADM] + } yield projectResponse.project.shortcode file: Option[FileValueV1] <- apiRequest.file match { - case Some(filename) => - // Ask Sipi about the file's metadata. - val tempFileUrl = stringFormatter.makeSipiTempFileUrl(settings, filename) - - for { - fileMetadataResponse: GetFileMetadataResponse <- (storeManager ? GetFileMetadataRequest( - fileUrl = tempFileUrl, - requestingUser = userADM - )).mapTo[GetFileMetadataResponse] - } yield Some( - RouteUtilV1.makeFileValue( - filename = filename, - fileMetadataResponse = fileMetadataResponse, - projectShortcode = projectShortcode - ) - ) - - case None => FastFuture.successful(None) - } - - valuesToBeCreatedWithFuture: Map[IRI, Future[Seq[CreateValueV1WithComment]]] = valuesToCreate( - properties = apiRequest.properties, - acceptStandoffLinksToClientIDs = false, - userProfile = userADM - ) + case Some(filename) => + // Ask Sipi about the file's metadata. + val tempFileUrl = stringFormatter.makeSipiTempFileUrl(settings, filename) + + for { + fileMetadataResponse: GetFileMetadataResponse <- + (storeManager ? GetFileMetadataRequest( + fileUrl = tempFileUrl, + requestingUser = userADM + )).mapTo[GetFileMetadataResponse] + } yield Some( + RouteUtilV1.makeFileValue( + filename = filename, + fileMetadataResponse = fileMetadataResponse, + projectShortcode = projectShortcode + ) + ) + + case None => FastFuture.successful(None) + } + + valuesToBeCreatedWithFuture: Map[IRI, Future[Seq[CreateValueV1WithComment]]] = + valuesToCreate( + properties = apiRequest.properties, + acceptStandoffLinksToClientIDs = false, + userProfile = userADM + ) // make the whole Map a Future valuesToBeCreated: Map[IRI, Seq[CreateValueV1WithComment]] <- ActorUtil.sequenceFutureSeqsInMap( - valuesToBeCreatedWithFuture - ) + valuesToBeCreatedWithFuture + ) } yield ResourceCreateRequestV1( resourceTypeIri = resourceTypeIri, label = label, @@ -379,25 +383,25 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) valuesToBeCreated: Map[IRI, Seq[CreateValueV1WithComment]] <- ActorUtil.sequenceFutureSeqsInMap(values) convertedFile <- resourceRequest.file match { - case Some(filename) => - // Ask Sipi about the file's metadata. - val tempFileUrl = stringFormatter.makeSipiTempFileUrl(settings, filename) - - for { - fileMetadataResponse: GetFileMetadataResponse <- (storeManager ? GetFileMetadataRequest( - fileUrl = tempFileUrl, - requestingUser = userProfile - )).mapTo[GetFileMetadataResponse] - } yield Some( - RouteUtilV1.makeFileValue( - filename = filename, - fileMetadataResponse = fileMetadataResponse, - projectShortcode = projectShortcode - ) - ) - - case None => FastFuture.successful(None) - } + case Some(filename) => + // Ask Sipi about the file's metadata. + val tempFileUrl = stringFormatter.makeSipiTempFileUrl(settings, filename) + + for { + fileMetadataResponse: GetFileMetadataResponse <- (storeManager ? GetFileMetadataRequest( + fileUrl = tempFileUrl, + requestingUser = userProfile + )).mapTo[GetFileMetadataResponse] + } yield Some( + RouteUtilV1.makeFileValue( + filename = filename, + fileMetadataResponse = fileMetadataResponse, + projectShortcode = projectShortcode + ) + ) + + case None => FastFuture.successful(None) + } } yield OneOfMultipleResourceCreateRequestV1( resourceTypeIri = resourceRequest.restype_id, clientResourceID = resourceRequest.client_id, @@ -432,21 +436,22 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) for { projectShortcode: String <- for { - projectResponse: ProjectGetResponseADM <- (responderManager ? ProjectGetRequestADM( - identifier = ProjectIdentifierADM(maybeIri = Some(projectId)), - featureFactoryConfig = featureFactoryConfig, - requestingUser = userProfile - )).mapTo[ProjectGetResponseADM] - } yield projectResponse.project.shortcode - - resourcesToCreate: Seq[Future[OneOfMultipleResourceCreateRequestV1]] = resourceRequest.map { - createResourceRequest => + projectResponse: ProjectGetResponseADM <- + (responderManager ? ProjectGetRequestADM( + identifier = ProjectIdentifierADM(maybeIri = Some(projectId)), + featureFactoryConfig = featureFactoryConfig, + requestingUser = userProfile + )).mapTo[ProjectGetResponseADM] + } yield projectResponse.project.shortcode + + resourcesToCreate: Seq[Future[OneOfMultipleResourceCreateRequestV1]] = + resourceRequest.map { createResourceRequest => createOneResourceRequestFromXmlImport( resourceRequest = createResourceRequest, projectShortcode = projectShortcode, userProfile = userProfile ) - } + } resToCreateCollection: Seq[OneOfMultipleResourceCreateRequestV1] <- Future.sequence(resourcesToCreate) } yield MultipleResourceCreateRequestV1( @@ -516,98 +521,106 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) for { // Get a NamedGraphEntityInfoV1 listing the IRIs of the classes and properties defined in the initial ontology. initialNamedGraphInfo: NamedGraphEntityInfoV1 <- (responderManager ? NamedGraphEntityInfoRequestV1( - initialOntologyIri, - userProfile - )).mapTo[NamedGraphEntityInfoV1] + initialOntologyIri, + userProfile + )).mapTo[NamedGraphEntityInfoV1] // Get details about those classes and properties. entityInfoResponse: EntityInfoGetResponseV1 <- (responderManager ? EntityInfoGetRequestV1( - resourceClassIris = initialNamedGraphInfo.resourceClasses, - propertyIris = initialNamedGraphInfo.propertyIris, - userProfile = userProfile - )).mapTo[EntityInfoGetResponseV1] + resourceClassIris = initialNamedGraphInfo.resourceClasses, + propertyIris = initialNamedGraphInfo.propertyIris, + userProfile = userProfile + )).mapTo[EntityInfoGetResponseV1] // Look at the base classes of all the resource classes in the initial ontology. Make a set of // the ontologies containing the definitions of those classes, not including including the initial ontology itself // or any other ontologies we've already looked at. ontologyIrisFromBaseClasses: Set[IRI] = entityInfoResponse.resourceClassInfoMap.foldLeft(Set.empty[IRI]) { - case (acc, (resourceClassIri, resourceClassInfo)) => - val subClassOfOntologies: Set[IRI] = resourceClassInfo.subClassOf - .map(_.toSmartIri) - .filter(_.isKnoraDefinitionIri) - .map(_.getOntologyFromEntity.toString) - acc ++ subClassOfOntologies - } -- intermediateResults.keySet - initialOntologyIri + case (acc, (resourceClassIri, resourceClassInfo)) => + val subClassOfOntologies: Set[IRI] = resourceClassInfo.subClassOf + .map(_.toSmartIri) + .filter(_.isKnoraDefinitionIri) + .map(_.getOntologyFromEntity.toString) + acc ++ subClassOfOntologies + } -- intermediateResults.keySet - initialOntologyIri // Look at the properties that have cardinalities in the resource classes in the initial ontology. // Make a set of the ontologies containing the definitions of those properties, not including the initial ontology itself // or any other ontologies we've already looked at. ontologyIrisFromCardinalities: Set[IRI] = entityInfoResponse.resourceClassInfoMap.foldLeft(Set.empty[IRI]) { - case (acc, (resourceClassIri, resourceClassInfo)) => - val resourceCardinalityOntologies: Set[IRI] = resourceClassInfo.knoraResourceCardinalities.map { - case (propertyIri, _) => propertyIri.toSmartIri.getOntologyFromEntity.toString - }.toSet + case (acc, (resourceClassIri, resourceClassInfo)) => + val resourceCardinalityOntologies: Set[IRI] = + resourceClassInfo.knoraResourceCardinalities.map { + case (propertyIri, _) => + propertyIri.toSmartIri.getOntologyFromEntity.toString + }.toSet - acc ++ resourceCardinalityOntologies - } -- intermediateResults.keySet - initialOntologyIri + acc ++ resourceCardinalityOntologies + } -- intermediateResults.keySet - initialOntologyIri // Look at the object class constraints of the properties in the initial ontology. Make a set of the ontologies containing those classes, // not including the initial ontology itself or any other ontologies we've already looked at. ontologyIrisFromObjectClassConstraints: Set[IRI] = entityInfoResponse.propertyInfoMap.map { - case (propertyIri, propertyInfo) => - val propertyObjectClassConstraint = - propertyInfo.getPredicateObject(OntologyConstants.KnoraBase.ObjectClassConstraint).getOrElse { - throw InconsistentRepositoryDataException( - s"Property $propertyIri has no knora-base:objectClassConstraint" - ) - } - - propertyObjectClassConstraint.toSmartIri.getOntologyFromEntity.toString - }.toSet -- intermediateResults.keySet - initialOntologyIri + case (propertyIri, propertyInfo) => + val propertyObjectClassConstraint = + propertyInfo + .getPredicateObject( + OntologyConstants.KnoraBase.ObjectClassConstraint + ) + .getOrElse { + throw InconsistentRepositoryDataException( + s"Property $propertyIri has no knora-base:objectClassConstraint" + ) + } + + propertyObjectClassConstraint.toSmartIri.getOntologyFromEntity.toString + }.toSet -- intermediateResults.keySet - initialOntologyIri // Make a set of all the ontologies referenced by the initial ontology. referencedOntologies: Set[IRI] = ontologyIrisFromBaseClasses ++ ontologyIrisFromCardinalities ++ ontologyIrisFromObjectClassConstraints // Recursively get NamedGraphEntityInfoV1 instances for each of those ontologies. - lastResults: Map[IRI, NamedGraphEntityInfoV1] <- referencedOntologies.foldLeft( - FastFuture.successful(intermediateResults + (initialOntologyIri -> initialNamedGraphInfo)) - ) { case (accFuture, ontologyIri) => - for { - acc: Map[IRI, NamedGraphEntityInfoV1] <- accFuture - - // Has a previous recursion already dealt with this ontology? - nextResults: Map[IRI, NamedGraphEntityInfoV1] <- - if (acc.contains(ontologyIri)) { - // Yes, so there's no need to get it again. - FastFuture.successful(acc) - } else { - // No. Recursively get it and the ontologies it depends on. - getNamedGraphInfosRec( - initialOntologyIri = ontologyIri, - intermediateResults = acc, - userProfile = userProfile - ) - } - } yield acc ++ nextResults - } + lastResults: Map[IRI, NamedGraphEntityInfoV1] <- + referencedOntologies.foldLeft( + FastFuture.successful(intermediateResults + (initialOntologyIri -> initialNamedGraphInfo)) + ) { case (accFuture, ontologyIri) => + for { + acc: Map[IRI, NamedGraphEntityInfoV1] <- accFuture + + // Has a previous recursion already dealt with this ontology? + nextResults: Map[IRI, NamedGraphEntityInfoV1] <- + if (acc.contains(ontologyIri)) { + // Yes, so there's no need to get it again. + FastFuture.successful(acc) + } else { + // No. Recursively get it and the ontologies it depends on. + getNamedGraphInfosRec( + initialOntologyIri = ontologyIri, + intermediateResults = acc, + userProfile = userProfile + ) + } + } yield acc ++ nextResults + } } yield lastResults } for { // Get a NamedGraphEntityInfoV1 for the knora-base ontology. knoraBaseGraphEntityInfo <- (responderManager ? NamedGraphEntityInfoRequestV1( - OntologyConstants.KnoraBase.KnoraBaseOntologyIri, - userProfile - )).mapTo[NamedGraphEntityInfoV1] + OntologyConstants.KnoraBase.KnoraBaseOntologyIri, + userProfile + )).mapTo[NamedGraphEntityInfoV1] // Recursively get NamedGraphEntityInfoV1 instances for the main ontology to be used in the XML import, // as well as any other project-specific ontologies it depends on. graphInfos <- getNamedGraphInfosRec( - initialOntologyIri = mainOntologyIri, - intermediateResults = Map(OntologyConstants.KnoraBase.KnoraBaseOntologyIri -> knoraBaseGraphEntityInfo), - userProfile = userProfile - ) + initialOntologyIri = mainOntologyIri, + intermediateResults = + Map(OntologyConstants.KnoraBase.KnoraBaseOntologyIri -> knoraBaseGraphEntityInfo), + userProfile = userProfile + ) } yield graphInfos } @@ -658,26 +671,26 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) for { // Get a NamedGraphEntityInfoV1 for each ontology that we need to generate an XML schema for. namedGraphInfos: Map[IRI, NamedGraphEntityInfoV1] <- getNamedGraphInfos( - mainOntologyIri = internalOntologyIri, - userProfile = userProfile - ) + mainOntologyIri = internalOntologyIri, + userProfile = userProfile + ) // Get information about the resource classes and properties in each ontology. - entityInfoResponseFutures: immutable.Iterable[Future[(IRI, EntityInfoGetResponseV1)]] = namedGraphInfos.map { - case (ontologyIri: IRI, namedGraphInfo: NamedGraphEntityInfoV1) => + entityInfoResponseFutures: immutable.Iterable[Future[(IRI, EntityInfoGetResponseV1)]] = + namedGraphInfos.map { case (ontologyIri: IRI, namedGraphInfo: NamedGraphEntityInfoV1) => for { entityInfoResponse: EntityInfoGetResponseV1 <- (responderManager ? EntityInfoGetRequestV1( - resourceClassIris = namedGraphInfo.resourceClasses, - propertyIris = namedGraphInfo.propertyIris, - userProfile = userProfile - )).mapTo[EntityInfoGetResponseV1] + resourceClassIris = namedGraphInfo.resourceClasses, + propertyIris = namedGraphInfo.propertyIris, + userProfile = userProfile + )).mapTo[EntityInfoGetResponseV1] } yield ontologyIri -> entityInfoResponse - } + } // Sequence the futures of entity info responses. entityInfoResponses: immutable.Iterable[(IRI, EntityInfoGetResponseV1)] <- Future.sequence( - entityInfoResponseFutures - ) + entityInfoResponseFutures + ) // Make a Map of internal ontology IRIs to EntityInfoGetResponseV1 objects. entityInfoResponsesMap: Map[IRI, EntityInfoGetResponseV1] = entityInfoResponses.toMap @@ -696,69 +709,79 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) // Make an XmlImportNamespaceInfoV1 for the standard Knora XML import v1 schema's namespace. knoraXmlImportSchemaNamespaceInfo: XmlImportNamespaceInfoV1 = XmlImportNamespaceInfoV1( - namespace = OntologyConstants.KnoraXmlImportV1.KnoraXmlImportNamespaceV1, - prefixLabel = OntologyConstants.KnoraXmlImportV1.KnoraXmlImportNamespacePrefixLabel - ) + namespace = + OntologyConstants.KnoraXmlImportV1.KnoraXmlImportNamespaceV1, + prefixLabel = + OntologyConstants.KnoraXmlImportV1.KnoraXmlImportNamespacePrefixLabel + ) // Read the standard Knora XML import v1 schema from a file. - knoraXmlImportSchemaXml: String = FileUtil.readTextResource( - OntologyConstants.KnoraXmlImportV1.KnoraXmlImportNamespacePrefixLabel + ".xsd" - ) + knoraXmlImportSchemaXml: String = + FileUtil.readTextResource( + OntologyConstants.KnoraXmlImportV1.KnoraXmlImportNamespacePrefixLabel + ".xsd" + ) // Construct an XmlImportSchemaV1 for the standard Knora XML import v1 schema. knoraXmlImportSchema: XmlImportSchemaV1 = XmlImportSchemaV1( - namespaceInfo = knoraXmlImportSchemaNamespaceInfo, - schemaXml = knoraXmlImportSchemaXml - ) + namespaceInfo = knoraXmlImportSchemaNamespaceInfo, + schemaXml = knoraXmlImportSchemaXml + ) // Generate a schema for each project-specific ontology. generatedSchemas: Map[IRI, XmlImportSchemaV1] = schemasToGenerate.map { case (ontologyIri, namespaceInfo) => - // Each schema imports all the other generated schemas, plus the standard Knora XML import v1 schema. - // Sort the imports to make schema generation deterministic. - val importedNamespaceInfos: Seq[XmlImportNamespaceInfoV1] = - (schemasToGenerate - ontologyIri).values.toVector.sortBy { importedNamespaceInfo => - importedNamespaceInfo.prefixLabel - } :+ knoraXmlImportSchemaNamespaceInfo - - // Generate the schema using a Twirl template. - val unformattedSchemaXml = org.knora.webapi.messages.twirl.xsd.v1.xml - .xmlImport( - targetNamespaceInfo = namespaceInfo, - importedNamespaces = importedNamespaceInfos, - knoraXmlImportNamespacePrefixLabel = - OntologyConstants.KnoraXmlImportV1.KnoraXmlImportNamespacePrefixLabel, - resourceClassInfoMap = entityInfoResponsesMap(ontologyIri).resourceClassInfoMap, - propertyInfoMap = propertyInfoMap, - getNamespacePrefixLabel = internalEntityIri => getNamespacePrefixLabel(internalEntityIri), - getEntityName = internalEntityIri => getEntityName(internalEntityIri) - ) - .toString() - .trim - - // Parse the generated XML schema. - val parsedSchemaXml = - try { - XML.loadString(unformattedSchemaXml) - } catch { - case parseEx: org.xml.sax.SAXParseException => - throw AssertionException( - s"Generated XML schema for namespace ${namespaceInfo.namespace} is not valid XML. Please report this as a bug.", - parseEx, - log - ) - } - - // Format the generated XML schema nicely. - val formattedSchemaXml = xmlPrettyPrinter.format(parsedSchemaXml) - - // Wrap it in an XmlImportSchemaV1 object along with its XML namespace information. - val schema = XmlImportSchemaV1( - namespaceInfo = namespaceInfo, - schemaXml = formattedSchemaXml - ) - - namespaceInfo.namespace -> schema - } + // Each schema imports all the other generated schemas, plus the standard Knora XML import v1 schema. + // Sort the imports to make schema generation deterministic. + val importedNamespaceInfos: Seq[XmlImportNamespaceInfoV1] = + (schemasToGenerate - ontologyIri).values.toVector.sortBy { + importedNamespaceInfo => + importedNamespaceInfo.prefixLabel + } :+ knoraXmlImportSchemaNamespaceInfo + + // Generate the schema using a Twirl template. + val unformattedSchemaXml = + org.knora.webapi.messages.twirl.xsd.v1.xml + .xmlImport( + targetNamespaceInfo = namespaceInfo, + importedNamespaces = importedNamespaceInfos, + knoraXmlImportNamespacePrefixLabel = + OntologyConstants.KnoraXmlImportV1.KnoraXmlImportNamespacePrefixLabel, + resourceClassInfoMap = entityInfoResponsesMap( + ontologyIri + ).resourceClassInfoMap, + propertyInfoMap = propertyInfoMap, + getNamespacePrefixLabel = internalEntityIri => + getNamespacePrefixLabel(internalEntityIri), + getEntityName = + internalEntityIri => getEntityName(internalEntityIri) + ) + .toString() + .trim + + // Parse the generated XML schema. + val parsedSchemaXml = + try { + XML.loadString(unformattedSchemaXml) + } catch { + case parseEx: org.xml.sax.SAXParseException => + throw AssertionException( + s"Generated XML schema for namespace ${namespaceInfo.namespace} is not valid XML. Please report this as a bug.", + parseEx, + log + ) + } + + // Format the generated XML schema nicely. + val formattedSchemaXml = + xmlPrettyPrinter.format(parsedSchemaXml) + + // Wrap it in an XmlImportSchemaV1 object along with its XML namespace information. + val schema = XmlImportSchemaV1( + namespaceInfo = namespaceInfo, + schemaXml = formattedSchemaXml + ) + + namespaceInfo.namespace -> schema + } // The schema bundle to be returned contains the generated schemas plus the standard Knora XML import v1 schema. allSchemasForBundle: Map[IRI, XmlImportSchemaV1] = @@ -780,16 +803,18 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) for { // Generate a bundle of XML schemas. schemaBundle: XmlImportSchemaBundleV1 <- generateSchemasFromOntologies( - internalOntologyIri = internalOntologyIri, - userProfile = userProfile - ) + internalOntologyIri = internalOntologyIri, + userProfile = userProfile + ) // Generate the contents of the Zip file: a Map of file names to file contents (byte arrays). zipFileContents: Map[String, Array[Byte]] = schemaBundle.schemas.values.map { schema: XmlImportSchemaV1 => - val schemaFilename: String = schema.namespaceInfo.prefixLabel + ".xsd" - val schemaXmlBytes: Array[Byte] = schema.schemaXml.getBytes(StandardCharsets.UTF_8) - schemaFilename -> schemaXmlBytes - }.toMap + val schemaFilename: String = + schema.namespaceInfo.prefixLabel + ".xsd" + val schemaXmlBytes: Array[Byte] = + schema.schemaXml.getBytes(StandardCharsets.UTF_8) + schemaFilename -> schemaXmlBytes + }.toMap } yield FileUtil.createZipFileBytes(zipFileContents) /** @@ -823,12 +848,12 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) // Use the SchemaFactory to instantiate a javax.xml.validation.Schema representing the main schema in // the bundle. - mainSchemaXml: String = schemaBundle.schemas(schemaBundle.mainNamespace).schemaXml + mainSchemaXml: String = schemaBundle.schemas(schemaBundle.mainNamespace).schemaXml schemaInstance: Schema = schemaFactory.newSchema(new StreamSource(new StringReader(mainSchemaXml))) // Validate the submitted XML using a validator based on the main schema. schemaValidator: Validator = schemaInstance.newValidator() - _ = schemaValidator.validate(new StreamSource(new StringReader(xml))) + _ = schemaValidator.validate(new StreamSource(new StringReader(xml))) } yield () // If the XML fails schema validation, return a failed Future containing a BadRequestException. @@ -990,7 +1015,7 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) if (childElements.nonEmpty) { val embeddedXmlRootNode = childElements.head - val embeddedXmlDoc = """""" + embeddedXmlRootNode.toString + val embeddedXmlDoc = """""" + embeddedXmlRootNode.toString CreateResourceValueV1( richtext_value = Some( CreateRichtextV1( @@ -1165,47 +1190,48 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) requestContext => val requestMessage = for { userProfile <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) - params = requestContext.request.uri.query().toMap + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) + params = requestContext.request.uri.query().toMap searchstr = params.getOrElse("searchstr", throw BadRequestException(s"required param searchstr is missing")) // default -1 means: no restriction at all restype = params.getOrElse("restype_id", "-1") numprops = params.getOrElse("numprops", "1") - limit = params.getOrElse("limit", "11") + limit = params.getOrElse("limit", "11") // input validation searchString = stringFormatter.toSparqlEncodedString( - searchstr, - throw BadRequestException(s"Invalid search string: '$searchstr'") - ) + searchstr, + throw BadRequestException(s"Invalid search string: '$searchstr'") + ) resourceTypeIri: Option[IRI] = restype match { - case "-1" => None - case restype: IRI => - Some( - stringFormatter.validateAndEscapeIri( - restype, - throw BadRequestException(s"Invalid param restype: $restype") - ) - ) - } + case "-1" => None + case restype: IRI => + Some( + stringFormatter.validateAndEscapeIri( + restype, + throw BadRequestException(s"Invalid param restype: $restype") + ) + ) + } numberOfProps: Int = stringFormatter.validateInt( - numprops, - throw BadRequestException(s"Invalid param numprops: $numprops") - ) match { - case number: Int => if (number < 1) 1 else number // numberOfProps must not be smaller than 1 - } + numprops, + throw BadRequestException(s"Invalid param numprops: $numprops") + ) match { + case number: Int => + if (number < 1) 1 else number // numberOfProps must not be smaller than 1 + } limitOfResults = stringFormatter.validateInt( - limit, - throw BadRequestException(s"Invalid param limit: $limit") - ) + limit, + throw BadRequestException(s"Invalid param limit: $limit") + ) } yield makeResourceSearchRequestMessage( searchString = searchString, @@ -1229,14 +1255,14 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) entity(as[CreateResourceApiRequestV1]) { apiRequest => requestContext => val requestMessageFuture = for { userProfile <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) request <- makeCreateResourceRequestMessage( - apiRequest = apiRequest, - featureFactoryConfig = featureFactoryConfig, - userADM = userProfile - ) + apiRequest = apiRequest, + featureFactoryConfig = featureFactoryConfig, + userADM = userProfile + ) } yield request RouteUtilV1.runJsonRouteWithFuture( @@ -1254,11 +1280,11 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessage = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestType = reqtypeParam.getOrElse("") - resinfo = resinfoParam.getOrElse(false) + resinfo = resinfoParam.getOrElse(false) } yield makeResourceRequestMessage( resIri = resIri, resinfo = resinfo, @@ -1278,9 +1304,9 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) parameters("deleteComment".?) { deleteCommentParam => requestContext => val requestMessage = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield makeResourceDeleteMessage(resIri = resIri, deleteComment = deleteCommentParam, userADM = userADM) RouteUtilV1.runJsonRouteWithFuture( @@ -1294,20 +1320,20 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) } } ~ path("v1" / "resources.html" / Segment) { iri => get { requestContext => - val params = requestContext.request.uri.query().toMap + val params = requestContext.request.uri.query().toMap val requestType = params.getOrElse("reqtype", "") val requestMessage = requestType match { case "properties" => for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) resIri = stringFormatter.validateAndEscapeIri( - iri, - throw BadRequestException(s"Invalid param resource IRI: $iri") - ) + iri, + throw BadRequestException(s"Invalid param resource IRI: $iri") + ) } yield ResourceFullGetRequestV1( iri = resIri, featureFactoryConfig = featureFactoryConfig, @@ -1329,13 +1355,13 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) get { requestContext => val requestMessage = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) resIri = stringFormatter.validateAndEscapeIri( - iri, - throw BadRequestException(s"Invalid param resource IRI: $iri") - ) + iri, + throw BadRequestException(s"Invalid param resource IRI: $iri") + ) } yield makeGetPropertiesRequestMessage(resIri, userADM) RouteUtilV1.runJsonRouteWithFuture( @@ -1352,17 +1378,17 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) entity(as[ChangeResourceLabelApiRequestV1]) { apiRequest => requestContext => val requestMessage = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) resIri = stringFormatter.validateAndEscapeIri( - iri, - throw BadRequestException(s"Invalid param resource IRI: $iri") - ) + iri, + throw BadRequestException(s"Invalid param resource IRI: $iri") + ) label = stringFormatter.toSparqlEncodedString( - apiRequest.label, - throw BadRequestException(s"Invalid label: '${apiRequest.label}'") - ) + apiRequest.label, + throw BadRequestException(s"Invalid label: '${apiRequest.label}'") + ) } yield ChangeResourceLabelRequestV1( resourceIri = resIri, label = label, @@ -1385,13 +1411,13 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) parameters("depth".as[Int].?) { depth => requestContext => val requestMessage = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) resourceIri = stringFormatter.validateAndEscapeIri( - iri, - throw BadRequestException(s"Invalid param resource IRI: $iri") - ) + iri, + throw BadRequestException(s"Invalid param resource IRI: $iri") + ) } yield GraphDataGetRequestV1(resourceIri, depth.getOrElse(4), userADM) RouteUtilV1.runJsonRouteWithFuture( @@ -1427,29 +1453,29 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) entity(as[String]) { xml => requestContext => val requestMessage = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) _ = if (userADM.isAnonymousUser) { - throw ForbiddenException( - "You are not logged in, and only a system administrator or project administrator can perform a bulk import" - ) - } + throw ForbiddenException( + "You are not logged in, and only a system administrator or project administrator can perform a bulk import" + ) + } _ = if (!(userADM.permissions.isSystemAdmin || userADM.permissions.isProjectAdmin(projectId))) { - throw ForbiddenException( - s"You are logged in as ${userADM.email}, but only a system administrator or project administrator can perform a bulk import" - ) - } + throw ForbiddenException( + s"You are logged in as ${userADM.email}, but only a system administrator or project administrator can perform a bulk import" + ) + } // Parse the submitted XML. rootElement: Elem = XML.loadString(xml) // Make sure that the root element is knoraXmlImport:resources. _ = if (rootElement.namespace + rootElement.label != OntologyConstants.KnoraXmlImportV1.Resources) { - throw BadRequestException(s"Root XML element must be ${OntologyConstants.KnoraXmlImportV1.Resources}") - } + throw BadRequestException(s"Root XML element must be ${OntologyConstants.KnoraXmlImportV1.Resources}") + } // Get the default namespace of the submitted XML. This should be the Knora XML import // namespace corresponding to the main internal ontology used in the import. @@ -1457,26 +1483,26 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) // Validate the XML using XML schemas. _ <- validateImportXml( - xml = xml, - defaultNamespace = defaultNamespace, - userADM = userADM - ) + xml = xml, + defaultNamespace = defaultNamespace, + userADM = userADM + ) // Make a CreateResourceFromXmlImportRequestV1 for each resource to be created. resourcesToCreate: Seq[CreateResourceFromXmlImportRequestV1] = importXmlToCreateResourceRequests( - rootElement - ) + rootElement + ) // Make a MultipleResourceCreateRequestV1 for the creation of all the resources. apiRequestID: UUID = UUID.randomUUID updateRequest: MultipleResourceCreateRequestV1 <- makeMultiResourcesRequestMessage( - resourceRequest = resourcesToCreate, - projectId = projectId, - apiRequestID = apiRequestID, - featureFactoryConfig = featureFactoryConfig, - userProfile = userADM - ) + resourceRequest = resourcesToCreate, + projectId = projectId, + apiRequestID = apiRequestID, + featureFactoryConfig = featureFactoryConfig, + userProfile = userADM + ) } yield updateRequest RouteUtilV1.runJsonRouteWithFuture( @@ -1510,13 +1536,13 @@ class ResourcesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) ) { requestContext => val httpResponseFuture: Future[HttpResponse] = for { userProfile <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) schemaZipFileBytes: Array[Byte] <- generateSchemaZipFile( - internalOntologyIri = internalOntologyIri, - userProfile = userProfile - ) + internalOntologyIri = internalOntologyIri, + userProfile = userProfile + ) } yield HttpResponse( status = StatusCodes.OK, entity = HttpEntity(bytes = schemaZipFileBytes) diff --git a/webapi/src/main/scala/org/knora/webapi/routing/v1/SearchRouteV1.scala b/webapi/src/main/scala/org/knora/webapi/routing/v1/SearchRouteV1.scala index ce0c050a23..be8fefc098 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/v1/SearchRouteV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/v1/SearchRouteV1.scala @@ -247,9 +247,9 @@ class SearchRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit get { requestContext => val requestMessage = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) params: Map[String, Seq[String]] = requestContext.request.uri.query().toMultiMap } yield makeExtendedSearchRequestMessage(userADM, params) @@ -267,9 +267,9 @@ class SearchRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit get { requestContext => val requestMessage = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) params: Map[String, String] = requestContext.request.uri.query().toMap } yield makeFulltextSearchRequestMessage(userADM, searchval, params) diff --git a/webapi/src/main/scala/org/knora/webapi/routing/v1/StandoffRouteV1.scala b/webapi/src/main/scala/org/knora/webapi/routing/v1/StandoffRouteV1.scala index a4a3e06fbc..dfee297635 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/v1/StandoffRouteV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/v1/StandoffRouteV1.scala @@ -36,7 +36,7 @@ class StandoffRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) w type Name = String val JSON_PART = "json" - val XML_PART = "xml" + val XML_PART = "xml" // collect all parts of the multipart as it arrives into a map val allPartsFuture: Future[Map[Name, String]] = formdata.parts @@ -66,9 +66,9 @@ class StandoffRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) w val requestMessageFuture: Future[CreateMappingRequestV1] = for { userProfile <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) allParts: Map[Name, String] <- allPartsFuture @@ -87,12 +87,13 @@ class StandoffRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) w throw BadRequestException("JSON params structure is invalid: " + e.toString) } - xml: String = allParts - .getOrElse( - XML_PART, - throw BadRequestException(s"MultiPart POST request was sent without required '$XML_PART' part!") - ) - .toString + xml: String = + allParts + .getOrElse( + XML_PART, + throw BadRequestException(s"MultiPart POST request was sent without required '$XML_PART' part!") + ) + .toString } yield CreateMappingRequestV1( xml = xml, label = stringFormatter.toSparqlEncodedString( diff --git a/webapi/src/main/scala/org/knora/webapi/routing/v1/UsersRouteV1.scala b/webapi/src/main/scala/org/knora/webapi/routing/v1/UsersRouteV1.scala index 9bd0ecb053..be7ad369e9 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/v1/UsersRouteV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/v1/UsersRouteV1.scala @@ -20,7 +20,7 @@ import org.knora.webapi.routing.{Authenticator, KnoraRoute, KnoraRouteData, Rout */ class UsersRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) with Authenticator { - private val schemes = Array("http", "https") + private val schemes = Array("http", "https") private val urlValidator = new UrlValidator(schemes) /** @@ -34,9 +34,9 @@ class UsersRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) with requestContext => val requestMessage = for { userProfile <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ).map(_.asUserProfileV1) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ).map(_.asUserProfileV1) } yield UsersGetRequestV1(userProfile) RouteUtilV1.runJsonRouteWithFuture( @@ -56,9 +56,9 @@ class UsersRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) with val requestMessage = if (identifier == "email") { for { userProfile <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ).map(_.asUserProfileV1) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ).map(_.asUserProfileV1) } yield UserProfileByEmailGetRequestV1( email = value, userProfileType = UserProfileTypeV1.RESTRICTED, @@ -68,13 +68,13 @@ class UsersRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) with } else { for { userProfile <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ).map(_.asUserProfileV1) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ).map(_.asUserProfileV1) userIri = stringFormatter.validateAndEscapeIri( - value, - throw BadRequestException(s"Invalid user IRI $value") - ) + value, + throw BadRequestException(s"Invalid user IRI $value") + ) } yield UserProfileByIRIGetRequestV1( userIri = userIri, userProfileType = UserProfileTypeV1.RESTRICTED, @@ -99,13 +99,13 @@ class UsersRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) with requestContext => val requestMessage = for { userProfile <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ).map(_.asUserProfileV1) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ).map(_.asUserProfileV1) checkedUserIri = stringFormatter.validateAndEscapeIri( - userIri, - throw BadRequestException(s"Invalid user IRI $userIri") - ) + userIri, + throw BadRequestException(s"Invalid user IRI $userIri") + ) } yield UserProjectMembershipsGetRequestV1( userIri = checkedUserIri, userProfileV1 = userProfile, @@ -127,13 +127,13 @@ class UsersRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) with requestContext => val requestMessage = for { userProfile <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ).map(_.asUserProfileV1) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ).map(_.asUserProfileV1) checkedUserIri = stringFormatter.validateAndEscapeIri( - userIri, - throw BadRequestException(s"Invalid user IRI $userIri") - ) + userIri, + throw BadRequestException(s"Invalid user IRI $userIri") + ) } yield UserProjectAdminMembershipsGetRequestV1( userIri = checkedUserIri, userProfileV1 = userProfile, @@ -155,13 +155,13 @@ class UsersRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) with requestContext => val requestMessage = for { userProfile <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ).map(_.asUserProfileV1) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ).map(_.asUserProfileV1) checkedUserIri = stringFormatter.validateAndEscapeIri( - userIri, - throw BadRequestException(s"Invalid user IRI $userIri") - ) + userIri, + throw BadRequestException(s"Invalid user IRI $userIri") + ) } yield UserGroupMembershipsGetRequestV1( userIri = checkedUserIri, userProfileV1 = userProfile, diff --git a/webapi/src/main/scala/org/knora/webapi/routing/v1/ValuesRouteV1.scala b/webapi/src/main/scala/org/knora/webapi/routing/v1/ValuesRouteV1.scala index cec2cab407..dc4d8ce397 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/v1/ValuesRouteV1.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/v1/ValuesRouteV1.scala @@ -108,141 +108,207 @@ class ValuesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit for { (value: UpdateValueV1, commentStr: Option[String]) <- apiRequest.getValueClassIri match { - case OntologyConstants.KnoraBase.TextValue => - val richtext: CreateRichtextV1 = apiRequest.richtext_value.get - - // check if text has markup - if (richtext.utf8str.nonEmpty && richtext.xml.isEmpty && richtext.mapping_id.isEmpty) { - // simple text - Future( - ( - TextValueSimpleV1( - stringFormatter.toSparqlEncodedString( - richtext.utf8str.get, - throw BadRequestException(s"Invalid text: '${richtext.utf8str.get}'") - ), - richtext.language - ), - apiRequest.comment - ) - ) - } else if (richtext.xml.nonEmpty && richtext.mapping_id.nonEmpty) { - // XML: text with markup - - val mappingIri = stringFormatter.validateAndEscapeIri( - richtext.mapping_id.get, - throw BadRequestException(s"mapping_id ${richtext.mapping_id.get} is invalid") - ) - - for { - - textWithStandoffTags: TextWithStandoffTagsV2 <- RouteUtilV1.convertXMLtoStandoffTagV1( - xml = richtext.xml.get, - mappingIri = mappingIri, - acceptStandoffLinksToClientIDs = false, - userProfile = userADM, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - responderManager = responderManager, - log = log - ) - - // collect the resource references from the linking standoff nodes - resourceReferences: Set[IRI] = stringFormatter.getResourceIrisFromStandoffTags( - textWithStandoffTags.standoffTagV2 - ) - - } yield ( - TextValueWithStandoffV1( - utf8str = stringFormatter.toSparqlEncodedString( - textWithStandoffTags.text, - throw InconsistentRepositoryDataException("utf8str for for TextValue contains invalid characters") - ), - language = textWithStandoffTags.language, - resource_reference = resourceReferences, - standoff = textWithStandoffTags.standoffTagV2, - mappingIri = textWithStandoffTags.mapping.mappingIri, - mapping = textWithStandoffTags.mapping.mapping - ), - apiRequest.comment - ) - - } else { - throw BadRequestException("invalid parameters given for TextValueV1") - } - - case OntologyConstants.KnoraBase.LinkValue => - val resourceIRI = stringFormatter.validateAndEscapeIri( - apiRequest.link_value.get, - throw BadRequestException(s"Invalid resource IRI: ${apiRequest.link_value.get}") - ) - Future(LinkUpdateV1(targetResourceIri = resourceIRI), apiRequest.comment) - - case OntologyConstants.KnoraBase.IntValue => - Future((IntegerValueV1(apiRequest.int_value.get), apiRequest.comment)) - - case OntologyConstants.KnoraBase.DecimalValue => - Future((DecimalValueV1(apiRequest.decimal_value.get), apiRequest.comment)) - - case OntologyConstants.KnoraBase.BooleanValue => - Future(BooleanValueV1(apiRequest.boolean_value.get), apiRequest.comment) - - case OntologyConstants.KnoraBase.UriValue => - Future( - ( - UriValueV1( - stringFormatter.validateAndEscapeIri( - apiRequest.uri_value.get, - throw BadRequestException(s"Invalid URI: ${apiRequest.uri_value.get}") - ) - ), - apiRequest.comment - ) - ) - - case OntologyConstants.KnoraBase.DateValue => - Future(DateUtilV1.createJDNValueV1FromDateString(apiRequest.date_value.get), apiRequest.comment) - - case OntologyConstants.KnoraBase.ColorValue => - val colorValue = stringFormatter.validateColor( - apiRequest.color_value.get, - throw BadRequestException(s"Invalid color value: ${apiRequest.color_value.get}") - ) - Future(ColorValueV1(colorValue), apiRequest.comment) - - case OntologyConstants.KnoraBase.GeomValue => - val geometryValue = stringFormatter.validateGeometryString( - apiRequest.geom_value.get, - throw BadRequestException(s"Invalid geometry value: ${apiRequest.geom_value.get}") - ) - Future(GeomValueV1(geometryValue), apiRequest.comment) - - case OntologyConstants.KnoraBase.ListValue => - val listNodeIri = stringFormatter.validateAndEscapeIri( - apiRequest.hlist_value.get, - throw BadRequestException(s"Invalid value IRI: ${apiRequest.hlist_value.get}") - ) - Future(HierarchicalListValueV1(listNodeIri), apiRequest.comment) - - case OntologyConstants.KnoraBase.IntervalValue => - val timeVals: Seq[BigDecimal] = apiRequest.interval_value.get - - if (timeVals.length != 2) throw BadRequestException("parameters for interval_value invalid") - - Future(IntervalValueV1(timeVals.head, timeVals(1)), apiRequest.comment) - - case OntologyConstants.KnoraBase.TimeValue => - val timeStamp: Instant = stringFormatter.xsdDateTimeStampToInstant( - apiRequest.time_value.get, - throw BadRequestException(s"Invalid timestamp: ${apiRequest.time_value.get}") - ) - Future(TimeValueV1(timeStamp), apiRequest.comment) - - case OntologyConstants.KnoraBase.GeonameValue => - Future(GeonameValueV1(apiRequest.geoname_value.get), apiRequest.comment) - - case _ => throw BadRequestException(s"No value submitted") - } + case OntologyConstants.KnoraBase.TextValue => + val richtext: CreateRichtextV1 = + apiRequest.richtext_value.get + + // check if text has markup + if ( + richtext.utf8str.nonEmpty && richtext.xml.isEmpty && richtext.mapping_id.isEmpty + ) { + // simple text + Future( + ( + TextValueSimpleV1( + stringFormatter.toSparqlEncodedString( + richtext.utf8str.get, + throw BadRequestException( + s"Invalid text: '${richtext.utf8str.get}'" + ) + ), + richtext.language + ), + apiRequest.comment + ) + ) + } else if ( + richtext.xml.nonEmpty && richtext.mapping_id.nonEmpty + ) { + // XML: text with markup + + val mappingIri = + stringFormatter.validateAndEscapeIri( + richtext.mapping_id.get, + throw BadRequestException( + s"mapping_id ${richtext.mapping_id.get} is invalid" + ) + ) + + for { + + textWithStandoffTags: TextWithStandoffTagsV2 <- + RouteUtilV1.convertXMLtoStandoffTagV1( + xml = richtext.xml.get, + mappingIri = mappingIri, + acceptStandoffLinksToClientIDs = false, + userProfile = userADM, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + responderManager = responderManager, + log = log + ) + + // collect the resource references from the linking standoff nodes + resourceReferences: Set[IRI] = + stringFormatter.getResourceIrisFromStandoffTags( + textWithStandoffTags.standoffTagV2 + ) + + } yield ( + TextValueWithStandoffV1( + utf8str = stringFormatter.toSparqlEncodedString( + textWithStandoffTags.text, + throw InconsistentRepositoryDataException( + "utf8str for for TextValue contains invalid characters" + ) + ), + language = textWithStandoffTags.language, + resource_reference = resourceReferences, + standoff = textWithStandoffTags.standoffTagV2, + mappingIri = + textWithStandoffTags.mapping.mappingIri, + mapping = textWithStandoffTags.mapping.mapping + ), + apiRequest.comment + ) + + } else { + throw BadRequestException( + "invalid parameters given for TextValueV1" + ) + } + + case OntologyConstants.KnoraBase.LinkValue => + val resourceIRI = + stringFormatter.validateAndEscapeIri( + apiRequest.link_value.get, + throw BadRequestException( + s"Invalid resource IRI: ${apiRequest.link_value.get}" + ) + ) + Future( + LinkUpdateV1(targetResourceIri = resourceIRI), + apiRequest.comment + ) + + case OntologyConstants.KnoraBase.IntValue => + Future( + ( + IntegerValueV1(apiRequest.int_value.get), + apiRequest.comment + ) + ) + + case OntologyConstants.KnoraBase.DecimalValue => + Future( + ( + DecimalValueV1(apiRequest.decimal_value.get), + apiRequest.comment + ) + ) + + case OntologyConstants.KnoraBase.BooleanValue => + Future( + BooleanValueV1(apiRequest.boolean_value.get), + apiRequest.comment + ) + + case OntologyConstants.KnoraBase.UriValue => + Future( + ( + UriValueV1( + stringFormatter.validateAndEscapeIri( + apiRequest.uri_value.get, + throw BadRequestException( + s"Invalid URI: ${apiRequest.uri_value.get}" + ) + ) + ), + apiRequest.comment + ) + ) + + case OntologyConstants.KnoraBase.DateValue => + Future( + DateUtilV1.createJDNValueV1FromDateString( + apiRequest.date_value.get + ), + apiRequest.comment + ) + + case OntologyConstants.KnoraBase.ColorValue => + val colorValue = stringFormatter.validateColor( + apiRequest.color_value.get, + throw BadRequestException( + s"Invalid color value: ${apiRequest.color_value.get}" + ) + ) + Future(ColorValueV1(colorValue), apiRequest.comment) + + case OntologyConstants.KnoraBase.GeomValue => + val geometryValue = stringFormatter.validateGeometryString( + apiRequest.geom_value.get, + throw BadRequestException( + s"Invalid geometry value: ${apiRequest.geom_value.get}" + ) + ) + Future(GeomValueV1(geometryValue), apiRequest.comment) + + case OntologyConstants.KnoraBase.ListValue => + val listNodeIri = stringFormatter.validateAndEscapeIri( + apiRequest.hlist_value.get, + throw BadRequestException( + s"Invalid value IRI: ${apiRequest.hlist_value.get}" + ) + ) + Future( + HierarchicalListValueV1(listNodeIri), + apiRequest.comment + ) + + case OntologyConstants.KnoraBase.IntervalValue => + val timeVals: Seq[BigDecimal] = + apiRequest.interval_value.get + + if (timeVals.length != 2) + throw BadRequestException( + "parameters for interval_value invalid" + ) + + Future( + IntervalValueV1(timeVals.head, timeVals(1)), + apiRequest.comment + ) + + case OntologyConstants.KnoraBase.TimeValue => + val timeStamp + : Instant = stringFormatter.xsdDateTimeStampToInstant( + apiRequest.time_value.get, + throw BadRequestException( + s"Invalid timestamp: ${apiRequest.time_value.get}" + ) + ) + Future(TimeValueV1(timeStamp), apiRequest.comment) + + case OntologyConstants.KnoraBase.GeonameValue => + Future( + GeonameValueV1(apiRequest.geoname_value.get), + apiRequest.comment + ) + + case _ => + throw BadRequestException(s"No value submitted") + } } yield CreateValueRequestV1( resourceIri = resourceIri, propertyIri = propertyIri, @@ -267,141 +333,207 @@ class ValuesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit for { (value: UpdateValueV1, commentStr: Option[String]) <- apiRequest.getValueClassIri match { - case OntologyConstants.KnoraBase.TextValue => - val richtext: CreateRichtextV1 = apiRequest.richtext_value.get - - // check if text has markup - if (richtext.utf8str.nonEmpty && richtext.xml.isEmpty && richtext.mapping_id.isEmpty) { - // simple text - Future( - ( - TextValueSimpleV1( - stringFormatter.toSparqlEncodedString( - richtext.utf8str.get, - throw BadRequestException(s"Invalid text: '${richtext.utf8str.get}'") - ), - richtext.language - ), - apiRequest.comment - ) - ) - } else if (richtext.xml.nonEmpty && richtext.mapping_id.nonEmpty) { - // XML: text with markup - - val mappingIri = stringFormatter.validateAndEscapeIri( - richtext.mapping_id.get, - throw BadRequestException(s"mapping_id ${richtext.mapping_id.get} is invalid") - ) - - for { - - textWithStandoffTags: TextWithStandoffTagsV2 <- RouteUtilV1.convertXMLtoStandoffTagV1( - xml = richtext.xml.get, - mappingIri = mappingIri, - acceptStandoffLinksToClientIDs = false, - userProfile = userADM, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - responderManager = responderManager, - log = log - ) - - // collect the resource references from the linking standoff nodes - resourceReferences: Set[IRI] = stringFormatter.getResourceIrisFromStandoffTags( - textWithStandoffTags.standoffTagV2 - ) - - } yield ( - TextValueWithStandoffV1( - utf8str = stringFormatter.toSparqlEncodedString( - textWithStandoffTags.text, - throw InconsistentRepositoryDataException("utf8str for for TextValue contains invalid characters") - ), - language = richtext.language, - resource_reference = resourceReferences, - standoff = textWithStandoffTags.standoffTagV2, - mappingIri = textWithStandoffTags.mapping.mappingIri, - mapping = textWithStandoffTags.mapping.mapping - ), - apiRequest.comment - ) - - } else { - throw BadRequestException("invalid parameters given for TextValueV1") - } - - case OntologyConstants.KnoraBase.LinkValue => - val resourceIRI = stringFormatter.validateAndEscapeIri( - apiRequest.link_value.get, - throw BadRequestException(s"Invalid resource IRI: ${apiRequest.link_value.get}") - ) - Future(LinkUpdateV1(targetResourceIri = resourceIRI), apiRequest.comment) - - case OntologyConstants.KnoraBase.IntValue => - Future((IntegerValueV1(apiRequest.int_value.get), apiRequest.comment)) - - case OntologyConstants.KnoraBase.DecimalValue => - Future((DecimalValueV1(apiRequest.decimal_value.get), apiRequest.comment)) - - case OntologyConstants.KnoraBase.BooleanValue => - Future(BooleanValueV1(apiRequest.boolean_value.get), apiRequest.comment) - - case OntologyConstants.KnoraBase.UriValue => - Future( - ( - UriValueV1( - stringFormatter.validateAndEscapeIri( - apiRequest.uri_value.get, - throw BadRequestException(s"Invalid URI: ${apiRequest.uri_value.get}") - ) - ), - apiRequest.comment - ) - ) - - case OntologyConstants.KnoraBase.DateValue => - Future(DateUtilV1.createJDNValueV1FromDateString(apiRequest.date_value.get), apiRequest.comment) - - case OntologyConstants.KnoraBase.ColorValue => - val colorValue = stringFormatter.validateColor( - apiRequest.color_value.get, - throw BadRequestException(s"Invalid color value: ${apiRequest.color_value.get}") - ) - Future(ColorValueV1(colorValue), apiRequest.comment) - - case OntologyConstants.KnoraBase.GeomValue => - val geometryValue = stringFormatter.validateGeometryString( - apiRequest.geom_value.get, - throw BadRequestException(s"Invalid geometry value: ${apiRequest.geom_value.get}") - ) - Future(GeomValueV1(geometryValue), apiRequest.comment) - - case OntologyConstants.KnoraBase.ListValue => - val listNodeIri = stringFormatter.validateAndEscapeIri( - apiRequest.hlist_value.get, - throw BadRequestException(s"Invalid value IRI: ${apiRequest.hlist_value.get}") - ) - Future(HierarchicalListValueV1(listNodeIri), apiRequest.comment) - - case OntologyConstants.KnoraBase.IntervalValue => - val timeVals: Seq[BigDecimal] = apiRequest.interval_value.get - - if (timeVals.length != 2) throw BadRequestException("parameters for interval_value invalid") - - Future(IntervalValueV1(timeVals.head, timeVals(1)), apiRequest.comment) - - case OntologyConstants.KnoraBase.TimeValue => - val timeStamp: Instant = stringFormatter.xsdDateTimeStampToInstant( - apiRequest.time_value.get, - throw BadRequestException(s"Invalid timestamp: ${apiRequest.time_value.get}") - ) - Future(TimeValueV1(timeStamp), apiRequest.comment) - - case OntologyConstants.KnoraBase.GeonameValue => - Future(GeonameValueV1(apiRequest.geoname_value.get), apiRequest.comment) - - case _ => throw BadRequestException(s"No value submitted") - } + case OntologyConstants.KnoraBase.TextValue => + val richtext: CreateRichtextV1 = + apiRequest.richtext_value.get + + // check if text has markup + if ( + richtext.utf8str.nonEmpty && richtext.xml.isEmpty && richtext.mapping_id.isEmpty + ) { + // simple text + Future( + ( + TextValueSimpleV1( + stringFormatter.toSparqlEncodedString( + richtext.utf8str.get, + throw BadRequestException( + s"Invalid text: '${richtext.utf8str.get}'" + ) + ), + richtext.language + ), + apiRequest.comment + ) + ) + } else if ( + richtext.xml.nonEmpty && richtext.mapping_id.nonEmpty + ) { + // XML: text with markup + + val mappingIri = + stringFormatter.validateAndEscapeIri( + richtext.mapping_id.get, + throw BadRequestException( + s"mapping_id ${richtext.mapping_id.get} is invalid" + ) + ) + + for { + + textWithStandoffTags: TextWithStandoffTagsV2 <- + RouteUtilV1.convertXMLtoStandoffTagV1( + xml = richtext.xml.get, + mappingIri = mappingIri, + acceptStandoffLinksToClientIDs = false, + userProfile = userADM, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + responderManager = responderManager, + log = log + ) + + // collect the resource references from the linking standoff nodes + resourceReferences: Set[IRI] = + stringFormatter.getResourceIrisFromStandoffTags( + textWithStandoffTags.standoffTagV2 + ) + + } yield ( + TextValueWithStandoffV1( + utf8str = stringFormatter.toSparqlEncodedString( + textWithStandoffTags.text, + throw InconsistentRepositoryDataException( + "utf8str for for TextValue contains invalid characters" + ) + ), + language = richtext.language, + resource_reference = resourceReferences, + standoff = textWithStandoffTags.standoffTagV2, + mappingIri = + textWithStandoffTags.mapping.mappingIri, + mapping = textWithStandoffTags.mapping.mapping + ), + apiRequest.comment + ) + + } else { + throw BadRequestException( + "invalid parameters given for TextValueV1" + ) + } + + case OntologyConstants.KnoraBase.LinkValue => + val resourceIRI = + stringFormatter.validateAndEscapeIri( + apiRequest.link_value.get, + throw BadRequestException( + s"Invalid resource IRI: ${apiRequest.link_value.get}" + ) + ) + Future( + LinkUpdateV1(targetResourceIri = resourceIRI), + apiRequest.comment + ) + + case OntologyConstants.KnoraBase.IntValue => + Future( + ( + IntegerValueV1(apiRequest.int_value.get), + apiRequest.comment + ) + ) + + case OntologyConstants.KnoraBase.DecimalValue => + Future( + ( + DecimalValueV1(apiRequest.decimal_value.get), + apiRequest.comment + ) + ) + + case OntologyConstants.KnoraBase.BooleanValue => + Future( + BooleanValueV1(apiRequest.boolean_value.get), + apiRequest.comment + ) + + case OntologyConstants.KnoraBase.UriValue => + Future( + ( + UriValueV1( + stringFormatter.validateAndEscapeIri( + apiRequest.uri_value.get, + throw BadRequestException( + s"Invalid URI: ${apiRequest.uri_value.get}" + ) + ) + ), + apiRequest.comment + ) + ) + + case OntologyConstants.KnoraBase.DateValue => + Future( + DateUtilV1.createJDNValueV1FromDateString( + apiRequest.date_value.get + ), + apiRequest.comment + ) + + case OntologyConstants.KnoraBase.ColorValue => + val colorValue = stringFormatter.validateColor( + apiRequest.color_value.get, + throw BadRequestException( + s"Invalid color value: ${apiRequest.color_value.get}" + ) + ) + Future(ColorValueV1(colorValue), apiRequest.comment) + + case OntologyConstants.KnoraBase.GeomValue => + val geometryValue = stringFormatter.validateGeometryString( + apiRequest.geom_value.get, + throw BadRequestException( + s"Invalid geometry value: ${apiRequest.geom_value.get}" + ) + ) + Future(GeomValueV1(geometryValue), apiRequest.comment) + + case OntologyConstants.KnoraBase.ListValue => + val listNodeIri = stringFormatter.validateAndEscapeIri( + apiRequest.hlist_value.get, + throw BadRequestException( + s"Invalid value IRI: ${apiRequest.hlist_value.get}" + ) + ) + Future( + HierarchicalListValueV1(listNodeIri), + apiRequest.comment + ) + + case OntologyConstants.KnoraBase.IntervalValue => + val timeVals: Seq[BigDecimal] = + apiRequest.interval_value.get + + if (timeVals.length != 2) + throw BadRequestException( + "parameters for interval_value invalid" + ) + + Future( + IntervalValueV1(timeVals.head, timeVals(1)), + apiRequest.comment + ) + + case OntologyConstants.KnoraBase.TimeValue => + val timeStamp + : Instant = stringFormatter.xsdDateTimeStampToInstant( + apiRequest.time_value.get, + throw BadRequestException( + s"Invalid timestamp: ${apiRequest.time_value.get}" + ) + ) + Future(TimeValueV1(timeStamp), apiRequest.comment) + + case OntologyConstants.KnoraBase.GeonameValue => + Future( + GeonameValueV1(apiRequest.geoname_value.get), + apiRequest.comment + ) + + case _ => + throw BadRequestException(s"No value submitted") + } } yield ChangeValueRequestV1( valueIri = valueIri, value = value, @@ -466,9 +598,9 @@ class ValuesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit for { fileMetadataResponse: GetFileMetadataResponse <- (storeManager ? GetFileMetadataRequest( - fileUrl = tempFileUrl, - requestingUser = userADM - )).mapTo[GetFileMetadataResponse] + fileUrl = tempFileUrl, + requestingUser = userADM + )).mapTo[GetFileMetadataResponse] } yield ChangeFileValueRequestV1( resourceIri = resourceIri, file = RouteUtilV1.makeFileValue( @@ -487,9 +619,9 @@ class ValuesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit get { requestContext => val requestMessage = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield makeVersionHistoryRequestMessage(iris = iris, userADM = userADM) RouteUtilV1.runJsonRouteWithFuture( @@ -505,9 +637,9 @@ class ValuesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit entity(as[CreateValueApiRequestV1]) { apiRequest => requestContext => val requestMessageFuture = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) request <- makeCreateValueRequestMessage(apiRequest = apiRequest, userADM = userADM) } yield request @@ -524,9 +656,9 @@ class ValuesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit get { requestContext => val requestMessage = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield makeGetValueRequest(valueIriStr = valueIriStr, userADM = userADM) RouteUtilV1.runJsonRouteWithFuture( @@ -542,17 +674,25 @@ class ValuesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit // we are getting a request to change either the value or the comment, but not both. val requestMessageFuture = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) request <- apiRequest match { - case ChangeValueApiRequestV1(_, _, _, _, _, _, _, _, _, _, _, _, _, Some(comment)) => - FastFuture.successful( - makeChangeCommentRequestMessage(valueIriStr = valueIriStr, comment = Some(comment), userADM = userADM) - ) - case _ => - makeAddValueVersionRequestMessage(valueIriStr = valueIriStr, apiRequest = apiRequest, userADM = userADM) - } + case ChangeValueApiRequestV1(_, _, _, _, _, _, _, _, _, _, _, _, _, Some(comment)) => + FastFuture.successful( + makeChangeCommentRequestMessage( + valueIriStr = valueIriStr, + comment = Some(comment), + userADM = userADM + ) + ) + case _ => + makeAddValueVersionRequestMessage( + valueIriStr = valueIriStr, + apiRequest = apiRequest, + userADM = userADM + ) + } } yield request RouteUtilV1.runJsonRouteWithFuture( @@ -566,10 +706,10 @@ class ValuesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit } ~ delete { requestContext => val requestMessage = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) - params = requestContext.request.uri.query().toMap + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) + params = requestContext.request.uri.query().toMap deleteComment = params.get("deleteComment") } yield makeDeleteValueRequest(valueIriStr = valueIriStr, deleteComment = deleteComment, userADM = userADM) @@ -585,9 +725,9 @@ class ValuesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit delete { requestContext => val requestMessage = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield makeChangeCommentRequestMessage(valueIriStr = valueIriStr, comment = None, userADM = userADM) RouteUtilV1.runJsonRouteWithFuture( @@ -603,9 +743,9 @@ class ValuesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit get { requestContext => val requestMessage = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield makeLinkValueGetRequestMessage(iris = iris, userADM = userADM) RouteUtilV1.runJsonRouteWithFuture( @@ -621,30 +761,30 @@ class ValuesRouteV1(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit entity(as[ChangeFileValueApiRequestV1]) { apiRequest => requestContext => val requestMessage = for { userADM <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) resourceIri = stringFormatter.validateAndEscapeIri( - resIriStr, - throw BadRequestException(s"Invalid resource IRI: $resIriStr") - ) + resIriStr, + throw BadRequestException(s"Invalid resource IRI: $resIriStr") + ) resourceInfoResponse <- (responderManager ? ResourceInfoGetRequestV1( - iri = resourceIri, - featureFactoryConfig = featureFactoryConfig, - userProfile = userADM - )).mapTo[ResourceInfoResponseV1] + iri = resourceIri, + featureFactoryConfig = featureFactoryConfig, + userProfile = userADM + )).mapTo[ResourceInfoResponseV1] projectShortcode = resourceInfoResponse.resource_info - .getOrElse(throw NotFoundException(s"Resource not found: $resourceIri")) - .project_shortcode + .getOrElse(throw NotFoundException(s"Resource not found: $resourceIri")) + .project_shortcode request <- makeChangeFileValueRequest( - resIriStr = resIriStr, - projectShortcode = projectShortcode, - apiRequest = apiRequest, - userADM = userADM - ) + resIriStr = resIriStr, + projectShortcode = projectShortcode, + apiRequest = apiRequest, + userADM = userADM + ) } yield request RouteUtilV1.runJsonRouteWithFuture( diff --git a/webapi/src/main/scala/org/knora/webapi/routing/v2/ListsRouteV2.scala b/webapi/src/main/scala/org/knora/webapi/routing/v2/ListsRouteV2.scala index a9189a617f..61671c2170 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/v2/ListsRouteV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/v2/ListsRouteV2.scala @@ -34,13 +34,13 @@ class ListsRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) with requestContext => val requestMessage: Future[ListGetRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) listIri: IRI = stringFormatter.validateAndEscapeIri( - lIri, - throw BadRequestException(s"Invalid list IRI: '$lIri'") - ) + lIri, + throw BadRequestException(s"Invalid list IRI: '$lIri'") + ) } yield ListGetRequestV2( listIri = listIri, featureFactoryConfig = featureFactoryConfig, @@ -67,13 +67,13 @@ class ListsRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) with requestContext => val requestMessage: Future[NodeGetRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) nodeIri: IRI = stringFormatter.validateAndEscapeIri( - nIri, - throw BadRequestException(s"Invalid list IRI: '$nIri'") - ) + nIri, + throw BadRequestException(s"Invalid list IRI: '$nIri'") + ) } yield NodeGetRequestV2( nodeIri = nodeIri, featureFactoryConfig = featureFactoryConfig, diff --git a/webapi/src/main/scala/org/knora/webapi/routing/v2/OntologiesRouteV2.scala b/webapi/src/main/scala/org/knora/webapi/routing/v2/OntologiesRouteV2.scala index 6820f4c924..b84497ce9c 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/v2/OntologiesRouteV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/v2/OntologiesRouteV2.scala @@ -31,7 +31,7 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) import OntologiesRouteV2._ - private val ALL_LANGUAGES = "allLanguages" + private val ALL_LANGUAGES = "allLanguages" private val LAST_MODIFICATION_DATE = "lastModificationDate" /** @@ -98,7 +98,7 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) } val params: Map[String, String] = requestContext.request.uri.query().toMap - val allLanguagesStr = params.get(ALL_LANGUAGES) + val allLanguagesStr = params.get(ALL_LANGUAGES) val allLanguages = stringFormatter.optionStringToBoolean( allLanguagesStr, throw BadRequestException(s"Invalid boolean for $ALL_LANGUAGES: $allLanguagesStr") @@ -106,9 +106,9 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[OntologyEntitiesGetRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield OntologyEntitiesGetRequestV2( ontologyIri = requestedOntology, allLanguages = allLanguages, @@ -135,9 +135,9 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[OntologyMetadataGetByProjectRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield OntologyMetadataGetByProjectRequestV2( projectIris = maybeProjectIri.toSet, requestingUser = requestingUser @@ -165,20 +165,20 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[ChangeOntologyMetadataRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestMessage: ChangeOntologyMetadataRequestV2 <- ChangeOntologyMetadataRequestV2.fromJsonLD( - jsonLDDocument = requestDoc, - apiRequestID = UUID.randomUUID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + jsonLDDocument = requestDoc, + apiRequestID = UUID.randomUUID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) } yield requestMessage RouteUtilV2.runRdfRouteWithFuture( @@ -201,9 +201,9 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) get { requestContext => val requestMessageFuture: Future[OntologyMetadataGetByProjectRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) validatedProjectIris = projectIris @@ -242,7 +242,7 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) } val params: Map[String, String] = requestContext.request.uri.query().toMap - val allLanguagesStr = params.get(ALL_LANGUAGES) + val allLanguagesStr = params.get(ALL_LANGUAGES) val allLanguages = stringFormatter.optionStringToBoolean( params.get(ALL_LANGUAGES), throw BadRequestException(s"Invalid boolean for $ALL_LANGUAGES: $allLanguagesStr") @@ -250,9 +250,9 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[OntologyEntitiesGetRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield OntologyEntitiesGetRequestV2( ontologyIri = requestedOntologyIri, allLanguages = allLanguages, @@ -279,22 +279,22 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) { val requestMessageFuture: Future[CreateClassRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestDoc: JsonLDDocument = JsonLDUtil.parseJsonLD(jsonRequest) requestMessage: CreateClassRequestV2 <- CreateClassRequestV2.fromJsonLD( - jsonLDDocument = requestDoc, - apiRequestID = UUID.randomUUID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + jsonLDDocument = requestDoc, + apiRequestID = UUID.randomUUID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) } yield requestMessage RouteUtilV2.runRdfRouteWithFuture( @@ -320,22 +320,22 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) { val requestMessageFuture: Future[ChangeClassLabelsOrCommentsRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestDoc: JsonLDDocument = JsonLDUtil.parseJsonLD(jsonRequest) requestMessage <- ChangeClassLabelsOrCommentsRequestV2.fromJsonLD( - jsonLDDocument = requestDoc, - apiRequestID = UUID.randomUUID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + jsonLDDocument = requestDoc, + apiRequestID = UUID.randomUUID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) } yield requestMessage RouteUtilV2.runRdfRouteWithFuture( @@ -375,9 +375,9 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[DeleteClassCommentRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield DeleteClassCommentRequestV2( classIri = classIri, lastModificationDate = lastModificationDate, @@ -407,22 +407,22 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) { val requestMessageFuture: Future[AddCardinalitiesToClassRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestDoc: JsonLDDocument = JsonLDUtil.parseJsonLD(jsonRequest) requestMessage: AddCardinalitiesToClassRequestV2 <- AddCardinalitiesToClassRequestV2.fromJsonLD( - jsonLDDocument = requestDoc, - apiRequestID = UUID.randomUUID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + jsonLDDocument = requestDoc, + apiRequestID = UUID.randomUUID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) } yield requestMessage RouteUtilV2.runRdfRouteWithFuture( @@ -452,9 +452,9 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[CanChangeCardinalitiesRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield CanChangeCardinalitiesRequestV2( classIri = classIri, featureFactoryConfig = featureFactoryConfig, @@ -483,22 +483,22 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) { val requestMessageFuture: Future[ChangeCardinalitiesRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestDoc: JsonLDDocument = JsonLDUtil.parseJsonLD(jsonRequest) requestMessage: ChangeCardinalitiesRequestV2 <- ChangeCardinalitiesRequestV2.fromJsonLD( - jsonLDDocument = requestDoc, - apiRequestID = UUID.randomUUID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + jsonLDDocument = requestDoc, + apiRequestID = UUID.randomUUID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) } yield requestMessage RouteUtilV2.runRdfRouteWithFuture( @@ -523,9 +523,9 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) { val requestMessageFuture: Future[CanDeleteCardinalitiesFromClassRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestDoc: JsonLDDocument = JsonLDUtil.parseJsonLD(jsonRequest) @@ -566,22 +566,22 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) { val requestMessageFuture: Future[DeleteCardinalitiesFromClassRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestDoc: JsonLDDocument = JsonLDUtil.parseJsonLD(jsonRequest) requestMessage: DeleteCardinalitiesFromClassRequestV2 <- DeleteCardinalitiesFromClassRequestV2.fromJsonLD( - jsonLDDocument = requestDoc, - apiRequestID = UUID.randomUUID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + jsonLDDocument = requestDoc, + apiRequestID = UUID.randomUUID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) } yield requestMessage RouteUtilV2.runRdfRouteWithFuture( @@ -607,22 +607,22 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) { val requestMessageFuture: Future[ChangeGuiOrderRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestDoc: JsonLDDocument = JsonLDUtil.parseJsonLD(jsonRequest) requestMessage: ChangeGuiOrderRequestV2 <- ChangeGuiOrderRequestV2.fromJsonLD( - jsonLDDocument = requestDoc, - apiRequestID = UUID.randomUUID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + jsonLDDocument = requestDoc, + apiRequestID = UUID.randomUUID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) } yield requestMessage RouteUtilV2.runRdfRouteWithFuture( @@ -676,7 +676,7 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) } val params: Map[String, String] = requestContext.request.uri.query().toMap - val allLanguagesStr = params.get(ALL_LANGUAGES) + val allLanguagesStr = params.get(ALL_LANGUAGES) val allLanguages = stringFormatter.optionStringToBoolean( params.get(ALL_LANGUAGES), throw BadRequestException(s"Invalid boolean for $ALL_LANGUAGES: $allLanguagesStr") @@ -684,9 +684,9 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[ClassesGetRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield ClassesGetRequestV2( classIris = classesForResponder, allLanguages = allLanguages, @@ -718,9 +718,9 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[CanDeleteClassRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield CanDeleteClassRequestV2( classIri = classIri, featureFactoryConfig = featureFactoryConfig, @@ -766,9 +766,9 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[DeleteClassRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield DeleteClassRequestV2( classIri = classIri, lastModificationDate = lastModificationDate, @@ -811,9 +811,9 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[DeleteOntologyCommentRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield DeleteOntologyCommentRequestV2( ontologyIri = ontologyIri, lastModificationDate = lastModificationDate, @@ -843,22 +843,22 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) { val requestMessageFuture: Future[CreatePropertyRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestDoc: JsonLDDocument = JsonLDUtil.parseJsonLD(jsonRequest) requestMessage: CreatePropertyRequestV2 <- CreatePropertyRequestV2.fromJsonLD( - jsonLDDocument = requestDoc, - apiRequestID = UUID.randomUUID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + jsonLDDocument = requestDoc, + apiRequestID = UUID.randomUUID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) } yield requestMessage RouteUtilV2.runRdfRouteWithFuture( @@ -884,23 +884,24 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) { val requestMessageFuture: Future[ChangePropertyLabelsOrCommentsRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestDoc: JsonLDDocument = JsonLDUtil.parseJsonLD(jsonRequest) requestMessage: ChangePropertyLabelsOrCommentsRequestV2 <- ChangePropertyLabelsOrCommentsRequestV2 - .fromJsonLD( - jsonLDDocument = requestDoc, - apiRequestID = UUID.randomUUID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + .fromJsonLD( + jsonLDDocument = requestDoc, + apiRequestID = UUID.randomUUID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = + featureFactoryConfig, + settings = settings, + log = log + ) } yield requestMessage RouteUtilV2.runRdfRouteWithFuture( @@ -940,9 +941,9 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[DeletePropertyCommentRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield DeletePropertyCommentRequestV2( propertyIri = propertyIri, lastModificationDate = lastModificationDate, @@ -972,23 +973,23 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) { val requestMessageFuture: Future[ChangePropertyGuiElementRequest] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestDoc: JsonLDDocument = JsonLDUtil.parseJsonLD(jsonRequest) requestMessage: ChangePropertyGuiElementRequest <- ChangePropertyGuiElementRequest - .fromJsonLD( - jsonLDDocument = requestDoc, - apiRequestID = UUID.randomUUID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + .fromJsonLD( + jsonLDDocument = requestDoc, + apiRequestID = UUID.randomUUID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) } yield requestMessage RouteUtilV2.runRdfRouteWithFuture( @@ -1042,7 +1043,7 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) } val params: Map[String, String] = requestContext.request.uri.query().toMap - val allLanguagesStr = params.get(ALL_LANGUAGES) + val allLanguagesStr = params.get(ALL_LANGUAGES) val allLanguages = stringFormatter.optionStringToBoolean( params.get(ALL_LANGUAGES), throw BadRequestException(s"Invalid boolean for $ALL_LANGUAGES: $allLanguagesStr") @@ -1050,9 +1051,9 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[PropertiesGetRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield PropertiesGetRequestV2( propertyIris = propsForResponder, allLanguages = allLanguages, @@ -1084,9 +1085,9 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[CanDeletePropertyRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield CanDeletePropertyRequestV2( propertyIri = propertyIri, featureFactoryConfig = featureFactoryConfig, @@ -1132,9 +1133,9 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[DeletePropertyRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield DeletePropertyRequestV2( propertyIri = propertyIri, lastModificationDate = lastModificationDate, @@ -1163,22 +1164,22 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) { val requestMessageFuture: Future[CreateOntologyRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestDoc: JsonLDDocument = JsonLDUtil.parseJsonLD(jsonRequest) requestMessage: CreateOntologyRequestV2 <- CreateOntologyRequestV2.fromJsonLD( - jsonLDDocument = requestDoc, - apiRequestID = UUID.randomUUID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + jsonLDDocument = requestDoc, + apiRequestID = UUID.randomUUID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) } yield requestMessage RouteUtilV2.runRdfRouteWithFuture( @@ -1208,9 +1209,9 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[CanDeleteOntologyRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield CanDeleteOntologyRequestV2( ontologyIri = ontologyIri, featureFactoryConfig = featureFactoryConfig, @@ -1254,9 +1255,9 @@ class OntologiesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[DeleteOntologyRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield DeleteOntologyRequestV2( ontologyIri = ontologyIri, lastModificationDate = lastModificationDate, diff --git a/webapi/src/main/scala/org/knora/webapi/routing/v2/ResourcesRouteV2.scala b/webapi/src/main/scala/org/knora/webapi/routing/v2/ResourcesRouteV2.scala index 752b1ce6d3..800219fd79 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/v2/ResourcesRouteV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/v2/ResourcesRouteV2.scala @@ -33,16 +33,16 @@ class ResourcesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) import ResourcesRouteV2._ - private val Text_Property = "textProperty" - private val Mapping_Iri = "mappingIri" + private val Text_Property = "textProperty" + private val Mapping_Iri = "mappingIri" private val GravsearchTemplate_Iri = "gravsearchTemplateIri" - private val TEIHeader_XSLT_IRI = "teiHeaderXSLTIri" - private val Depth = "depth" - private val ExcludeProperty = "excludeProperty" - private val Direction = "direction" - private val Inbound = "inbound" - private val Outbound = "outbound" - private val Both = "both" + private val TEIHeader_XSLT_IRI = "teiHeaderXSLTIri" + private val Depth = "depth" + private val ExcludeProperty = "excludeProperty" + private val Direction = "direction" + private val Inbound = "inbound" + private val Outbound = "outbound" + private val Both = "both" /** * Returns the route. @@ -73,9 +73,9 @@ class ResourcesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[ResourceIIIFManifestGetRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield ResourceIIIFManifestGetRequestV2( resourceIri = resourceIri, featureFactoryConfig = featureFactoryConfig, @@ -103,20 +103,20 @@ class ResourcesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[CreateResourceRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestMessage: CreateResourceRequestV2 <- CreateResourceRequestV2.fromJsonLD( - requestDoc, - apiRequestID = UUID.randomUUID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + requestDoc, + apiRequestID = UUID.randomUUID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) } yield requestMessage RouteUtilV2.runRdfRouteWithFuture( @@ -142,20 +142,20 @@ class ResourcesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[UpdateResourceMetadataRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestMessage: UpdateResourceMetadataRequestV2 <- UpdateResourceMetadataRequestV2.fromJsonLD( - requestDoc, - apiRequestID = UUID.randomUUID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + requestDoc, + apiRequestID = UUID.randomUUID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) } yield requestMessage RouteUtilV2.runRdfRouteWithFuture( @@ -215,9 +215,9 @@ class ResourcesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[SearchResourcesByProjectAndClassRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield SearchResourcesByProjectAndClassRequestV2( projectIri = projectIri, resourceClass = resourceClass.toOntologySchema(ApiV2Complex), @@ -265,9 +265,9 @@ class ResourcesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[ResourceVersionHistoryGetRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield ResourceVersionHistoryGetRequestV2( resourceIri = resourceIri, startDate = startDate, @@ -294,9 +294,9 @@ class ResourcesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) get { requestContext => val requestMessageFuture: Future[ResourceHistoryEventsGetRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield ResourceHistoryEventsGetRequestV2( resourceIri = resourceIri, featureFactoryConfig = featureFactoryConfig, @@ -321,9 +321,9 @@ class ResourcesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) get { requestContext => val requestMessageFuture: Future[ProjectResourcesWithHistoryGetRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield ProjectResourcesWithHistoryGetRequestV2( projectIri = projectIri, featureFactoryConfig = featureFactoryConfig, @@ -368,14 +368,14 @@ class ResourcesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) } } - val targetSchema: ApiV2Schema = RouteUtilV2.getOntologySchema(requestContext) + val targetSchema: ApiV2Schema = RouteUtilV2.getOntologySchema(requestContext) val schemaOptions: Set[SchemaOption] = RouteUtilV2.getSchemaOptions(requestContext) val requestMessageFuture: Future[ResourcesGetRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield ResourcesGetRequestV2( resourceIris = resourceIris, versionDate = versionDate, @@ -412,9 +412,9 @@ class ResourcesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[ResourcesPreviewGetRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield ResourcesPreviewGetRequestV2( resourceIris = resourceIris, targetSchema = targetSchema, @@ -454,9 +454,9 @@ class ResourcesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[ResourceTEIGetRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield ResourceTEIGetRequestV2( resourceIri = resourceIri, textProperty = textProperty, @@ -488,7 +488,7 @@ class ResourcesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) throw BadRequestException(s"Invalid resource IRI: <$resIriStr>") ) val params: Map[String, String] = requestContext.request.uri.query().toMap - val depth: Int = params.get(Depth).map(_.toInt).getOrElse(settings.defaultGraphDepth) + val depth: Int = params.get(Depth).map(_.toInt).getOrElse(settings.defaultGraphDepth) if (depth < 1) { throw BadRequestException(s"$Depth must be at least 1") @@ -514,9 +514,9 @@ class ResourcesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[GraphDataGetRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield GraphDataGetRequestV2( resourceIri = resourceIri, depth = depth, @@ -547,19 +547,19 @@ class ResourcesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[DeleteOrEraseResourceRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestMessage: DeleteOrEraseResourceRequestV2 <- DeleteOrEraseResourceRequestV2.fromJsonLD( - requestDoc, - apiRequestID = UUID.randomUUID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + requestDoc, + apiRequestID = UUID.randomUUID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) } yield requestMessage RouteUtilV2.runRdfRouteWithFuture( @@ -585,20 +585,20 @@ class ResourcesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) val requestMessageFuture: Future[DeleteOrEraseResourceRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestMessage: DeleteOrEraseResourceRequestV2 <- DeleteOrEraseResourceRequestV2.fromJsonLD( - requestDoc, - apiRequestID = UUID.randomUUID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + requestDoc, + apiRequestID = UUID.randomUUID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) } yield requestMessage.copy(erase = true) RouteUtilV2.runRdfRouteWithFuture( @@ -624,7 +624,7 @@ class ResourcesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) */ private def getTextPropertyFromParams(params: Map[String, String]): SmartIri = { implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - val textProperty = params.get(Text_Property) + val textProperty = params.get(Text_Property) textProperty match { case Some(textPropIriStr: String) => @@ -649,7 +649,7 @@ class ResourcesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) */ private def getMappingIriFromParams(params: Map[String, String]): Option[IRI] = { implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - val mappingIriStr = params.get(Mapping_Iri) + val mappingIriStr = params.get(Mapping_Iri) mappingIriStr match { case Some(mapping: String) => @@ -669,7 +669,7 @@ class ResourcesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) */ private def getGravsearchTemplateIriFromParams(params: Map[String, String]): Option[IRI] = { implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - val gravsearchTemplateIriStr = params.get(GravsearchTemplate_Iri) + val gravsearchTemplateIriStr = params.get(GravsearchTemplate_Iri) gravsearchTemplateIriStr match { case Some(gravsearch: String) => @@ -692,7 +692,7 @@ class ResourcesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) */ private def getHeaderXSLTIriFromParams(params: Map[String, String]): Option[IRI] = { implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - val headerXSLTIriStr = params.get(TEIHeader_XSLT_IRI) + val headerXSLTIriStr = params.get(TEIHeader_XSLT_IRI) headerXSLTIriStr match { case Some(xslt: String) => diff --git a/webapi/src/main/scala/org/knora/webapi/routing/v2/SearchRouteV2.scala b/webapi/src/main/scala/org/knora/webapi/routing/v2/SearchRouteV2.scala index ce22260741..2a3a34788f 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/v2/SearchRouteV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/v2/SearchRouteV2.scala @@ -23,11 +23,11 @@ import scala.concurrent.Future */ class SearchRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) with Authenticator { - private val LIMIT_TO_PROJECT = "limitToProject" + private val LIMIT_TO_PROJECT = "limitToProject" private val LIMIT_TO_RESOURCE_CLASS = "limitToResourceClass" - private val OFFSET = "offset" + private val OFFSET = "offset" private val LIMIT_TO_STANDOFF_CLASS = "limitToStandoffClass" - private val RETURN_FILES = "returnFiles" + private val RETURN_FILES = "returnFiles" /** * Returns the route. @@ -50,7 +50,7 @@ class SearchRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit */ private def getOffsetFromParams(params: Map[String, String]): Int = { implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - val offsetStr = params.get(OFFSET) + val offsetStr = params.get(OFFSET) offsetStr match { case Some(offset: String) => @@ -75,7 +75,7 @@ class SearchRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit */ private def getProjectFromParams(params: Map[String, String]): Option[IRI] = { implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - val limitToProjectIriStr = params.get(LIMIT_TO_PROJECT) + val limitToProjectIriStr = params.get(LIMIT_TO_PROJECT) val limitToProjectIri: Option[IRI] = limitToProjectIriStr match { @@ -103,7 +103,7 @@ class SearchRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit */ private def getResourceClassFromParams(params: Map[String, String]): Option[SmartIri] = { implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - val limitToResourceClassIriStr = params.get(LIMIT_TO_RESOURCE_CLASS) + val limitToResourceClassIriStr = params.get(LIMIT_TO_RESOURCE_CLASS) limitToResourceClassIriStr match { case Some(resourceClassIriStr: String) => @@ -128,7 +128,7 @@ class SearchRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit * @return the internal standoff class, if any. */ private def getStandoffClass(params: Map[String, String]): Option[SmartIri] = { - implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance + implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance val limitToStandoffClassIriStr: Option[String] = params.get(LIMIT_TO_STANDOFF_CLASS) limitToStandoffClassIriStr match { @@ -179,9 +179,9 @@ class SearchRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessage: Future[FullTextSearchCountRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield FullTextSearchCountRequestV2( searchValue = escapedSearchStr, limitToProject = limitToProject, @@ -238,14 +238,14 @@ class SearchRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit throw BadRequestException(s"Invalid boolean value for '$RETURN_FILES'") ) - val targetSchema: ApiV2Schema = RouteUtilV2.getOntologySchema(requestContext) + val targetSchema: ApiV2Schema = RouteUtilV2.getOntologySchema(requestContext) val schemaOptions: Set[SchemaOption] = RouteUtilV2.getSchemaOptions(requestContext) val requestMessage: Future[FulltextSearchRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield FulltextSearchRequestV2( searchValue = escapedSearchStr, offset = offset, @@ -280,9 +280,9 @@ class SearchRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessage: Future[GravsearchCountRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield GravsearchCountRequestV2( constructQuery = constructQuery, featureFactoryConfig = featureFactoryConfig, @@ -310,9 +310,9 @@ class SearchRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val constructQuery = GravsearchParser.parseQuery(gravsearchQuery) val requestMessage: Future[GravsearchCountRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield GravsearchCountRequestV2( constructQuery = constructQuery, featureFactoryConfig = featureFactoryConfig, @@ -338,15 +338,15 @@ class SearchRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit "v2" / "searchextended" / Segment ) { sparql => // Segment is a URL encoded string representing a Gravsearch query get { requestContext => - val constructQuery = GravsearchParser.parseQuery(sparql) - val targetSchema: ApiV2Schema = RouteUtilV2.getOntologySchema(requestContext) + val constructQuery = GravsearchParser.parseQuery(sparql) + val targetSchema: ApiV2Schema = RouteUtilV2.getOntologySchema(requestContext) val schemaOptions: Set[SchemaOption] = RouteUtilV2.getSchemaOptions(requestContext) val requestMessage: Future[GravsearchRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield GravsearchRequestV2( constructQuery = constructQuery, targetSchema = targetSchema, @@ -372,15 +372,15 @@ class SearchRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit post { entity(as[String]) { gravsearchQuery => requestContext => { - val constructQuery = GravsearchParser.parseQuery(gravsearchQuery) - val targetSchema: ApiV2Schema = RouteUtilV2.getOntologySchema(requestContext) + val constructQuery = GravsearchParser.parseQuery(gravsearchQuery) + val targetSchema: ApiV2Schema = RouteUtilV2.getOntologySchema(requestContext) val schemaOptions: Set[SchemaOption] = RouteUtilV2.getSchemaOptions(requestContext) val requestMessage: Future[GravsearchRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield GravsearchRequestV2( constructQuery = constructQuery, targetSchema = targetSchema, @@ -428,9 +428,9 @@ class SearchRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessage: Future[SearchResourceByLabelCountRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield SearchResourceByLabelCountRequestV2( searchValue = searchString, limitToProject = limitToProject, @@ -480,9 +480,9 @@ class SearchRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessage: Future[SearchResourceByLabelRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield SearchResourceByLabelRequestV2( searchValue = searchString, offset = offset, diff --git a/webapi/src/main/scala/org/knora/webapi/routing/v2/StandoffRouteV2.scala b/webapi/src/main/scala/org/knora/webapi/routing/v2/StandoffRouteV2.scala index 265e1a9100..cbeca529c7 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/v2/StandoffRouteV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/v2/StandoffRouteV2.scala @@ -63,9 +63,9 @@ class StandoffRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) w val requestMessageFuture: Future[GetStandoffPageRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield GetStandoffPageRequestV2( resourceIri = resourceIri.toString, valueIri = valueIri.toString, @@ -90,7 +90,7 @@ class StandoffRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) w post { entity(as[Multipart.FormData]) { formData: Multipart.FormData => requestContext => val JSON_PART = "json" - val XML_PART = "xml" + val XML_PART = "xml" type Name = String val apiRequestID = UUID.randomUUID @@ -124,36 +124,38 @@ class StandoffRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) w val requestMessageFuture: Future[CreateMappingRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) allParts: Map[Name, String] <- allPartsFuture - jsonldDoc = JsonLDUtil.parseJsonLD( + jsonldDoc = + JsonLDUtil.parseJsonLD( + allParts + .getOrElse( + JSON_PART, + throw BadRequestException(s"MultiPart POST request was sent without required '$JSON_PART' part!") + ) + .toString + ) + + metadata: CreateMappingRequestMetadataV2 <- CreateMappingRequestMetadataV2.fromJsonLD( + jsonLDDocument = jsonldDoc, + apiRequestID = apiRequestID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) + + xml: String = allParts .getOrElse( - JSON_PART, - throw BadRequestException(s"MultiPart POST request was sent without required '$JSON_PART' part!") + XML_PART, + throw BadRequestException(s"MultiPart POST request was sent without required '$XML_PART' part!") ) .toString - ) - - metadata: CreateMappingRequestMetadataV2 <- CreateMappingRequestMetadataV2.fromJsonLD( - jsonLDDocument = jsonldDoc, - apiRequestID = apiRequestID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) - - xml: String = allParts - .getOrElse( - XML_PART, - throw BadRequestException(s"MultiPart POST request was sent without required '$XML_PART' part!") - ) - .toString } yield CreateMappingRequestV2( metadata = metadata, xml = CreateMappingRequestXMLV2(xml), diff --git a/webapi/src/main/scala/org/knora/webapi/routing/v2/ValuesRouteV2.scala b/webapi/src/main/scala/org/knora/webapi/routing/v2/ValuesRouteV2.scala index 8734a58401..19db291415 100644 --- a/webapi/src/main/scala/org/knora/webapi/routing/v2/ValuesRouteV2.scala +++ b/webapi/src/main/scala/org/knora/webapi/routing/v2/ValuesRouteV2.scala @@ -73,14 +73,14 @@ class ValuesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit } } - val targetSchema: ApiV2Schema = RouteUtilV2.getOntologySchema(requestContext) + val targetSchema: ApiV2Schema = RouteUtilV2.getOntologySchema(requestContext) val schemaOptions: Set[SchemaOption] = RouteUtilV2.getSchemaOptions(requestContext) val requestMessageFuture: Future[ResourcesGetRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) } yield ResourcesGetRequestV2( resourceIris = Seq(resourceIri.toString), valueUuid = Some(valueUuid), @@ -111,19 +111,19 @@ class ValuesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessageFuture: Future[CreateValueRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestMessage: CreateValueRequestV2 <- CreateValueRequestV2.fromJsonLD( - requestDoc, - apiRequestID = UUID.randomUUID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + requestDoc, + apiRequestID = UUID.randomUUID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) } yield requestMessage RouteUtilV2.runRdfRouteWithFuture( @@ -149,19 +149,19 @@ class ValuesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessageFuture: Future[UpdateValueRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestMessage: UpdateValueRequestV2 <- UpdateValueRequestV2.fromJsonLD( - requestDoc, - apiRequestID = UUID.randomUUID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + requestDoc, + apiRequestID = UUID.randomUUID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) } yield requestMessage RouteUtilV2.runRdfRouteWithFuture( @@ -187,19 +187,19 @@ class ValuesRouteV2(routeData: KnoraRouteData) extends KnoraRoute(routeData) wit val requestMessageFuture: Future[DeleteValueRequestV2] = for { requestingUser <- getUserADM( - requestContext = requestContext, - featureFactoryConfig = featureFactoryConfig - ) + requestContext = requestContext, + featureFactoryConfig = featureFactoryConfig + ) requestMessage: DeleteValueRequestV2 <- DeleteValueRequestV2.fromJsonLD( - requestDoc, - apiRequestID = UUID.randomUUID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + requestDoc, + apiRequestID = UUID.randomUUID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) } yield requestMessage RouteUtilV2.runRdfRouteWithFuture( diff --git a/webapi/src/main/scala/org/knora/webapi/settings/KnoraSettings.scala b/webapi/src/main/scala/org/knora/webapi/settings/KnoraSettings.scala index 4f34f27c2d..58e40c40c3 100644 --- a/webapi/src/main/scala/org/knora/webapi/settings/KnoraSettings.scala +++ b/webapi/src/main/scala/org/knora/webapi/settings/KnoraSettings.scala @@ -41,15 +41,15 @@ class KnoraSettingsImpl(config: Config, log: LoggingAdapter) extends Extension { // used for communication inside the knora stack val internalKnoraApiHost: String = config.getString("app.knora-api.internal-host") - val internalKnoraApiPort: Int = config.getInt("app.knora-api.internal-port") + val internalKnoraApiPort: Int = config.getInt("app.knora-api.internal-port") val internalKnoraApiBaseUrl: String = "http://" + internalKnoraApiHost + (if (internalKnoraApiPort != 80) ":" + internalKnoraApiPort else "") // used for communication between the outside and the knora stack, e.g., browser val externalKnoraApiProtocol: String = config.getString("app.knora-api.external-protocol") - val externalKnoraApiHost: String = config.getString("app.knora-api.external-host") - val externalKnoraApiPort: Int = config.getInt("app.knora-api.external-port") + val externalKnoraApiHost: String = config.getString("app.knora-api.external-host") + val externalKnoraApiPort: Int = config.getInt("app.knora-api.external-port") val externalKnoraApiHostPort: String = externalKnoraApiHost + (if (externalKnoraApiPort != 80) ":" + externalKnoraApiPort else "") @@ -68,11 +68,11 @@ class KnoraSettingsImpl(config: Config, log: LoggingAdapter) extends Extension { externalKnoraApiHost } - val salsah1BaseUrl: String = config.getString("app.salsah1.base-url") + val salsah1BaseUrl: String = config.getString("app.salsah1.base-url") val salsah1ProjectIconsBasePath: String = config.getString("app.salsah1.project-icons-basepath") val tmpDataDir: String = config.getString("app.tmp-datadir") - val dataDir: String = config.getString("app.datadir") + val dataDir: String = config.getString("app.datadir") // try to create the directories if (!Files.exists(Paths.get(tmpDataDir))) { @@ -149,8 +149,8 @@ class KnoraSettingsImpl(config: Config, log: LoggingAdapter) extends Extension { .toSet val internalSipiProtocol: String = config.getString("app.sipi.internal-protocol") - val internalSipiHost: String = config.getString("app.sipi.internal-host") - val internalSipiPort: Int = config.getInt("app.sipi.internal-port") + val internalSipiHost: String = config.getString("app.sipi.internal-host") + val internalSipiPort: Int = config.getInt("app.sipi.internal-port") val internalSipiBaseUrl: String = internalSipiProtocol + "://" + internalSipiHost + (if (internalSipiPort != 80) ":" + internalSipiPort else "") @@ -158,18 +158,18 @@ class KnoraSettingsImpl(config: Config, log: LoggingAdapter) extends Extension { val sipiTimeout: FiniteDuration = getFiniteDuration("app.sipi.timeout", config) val externalSipiProtocol: String = config.getString("app.sipi.external-protocol") - val externalSipiHost: String = config.getString("app.sipi.external-host") - val externalSipiPort: Int = config.getInt("app.sipi.external-port") + val externalSipiHost: String = config.getString("app.sipi.external-host") + val externalSipiPort: Int = config.getInt("app.sipi.external-port") val externalSipiBaseUrl: String = externalSipiProtocol + "://" + externalSipiHost + (if (externalSipiPort != 80) ":" + externalSipiPort else "") - val sipiFileServerPrefix: String = config.getString("app.sipi.file-server-path") - val externalSipiIIIFGetUrl: String = externalSipiBaseUrl - val sipiFileMetadataRouteV2: String = config.getString("app.sipi.v2.file-metadata-route") - val sipiMoveFileRouteV2: String = config.getString("app.sipi.v2.move-file-route") + val sipiFileServerPrefix: String = config.getString("app.sipi.file-server-path") + val externalSipiIIIFGetUrl: String = externalSipiBaseUrl + val sipiFileMetadataRouteV2: String = config.getString("app.sipi.v2.file-metadata-route") + val sipiMoveFileRouteV2: String = config.getString("app.sipi.v2.move-file-route") val sipiDeleteTempFileRouteV2: String = config.getString("app.sipi.v2.delete-temp-file-route") - val arkResolver: String = config.getString("app.ark.resolver") + val arkResolver: String = config.getString("app.ark.resolver") val arkAssignedNumber: Int = config.getInt("app.ark.assigned-number") val caches: Vector[KnoraCacheConfig] = config @@ -191,46 +191,46 @@ class KnoraSettingsImpl(config: Config, log: LoggingAdapter) extends Extension { val defaultTimeout: FiniteDuration = getFiniteDuration("app.default-timeout", config) - val dumpMessages: Boolean = config.getBoolean("app.dump-messages") - val showInternalErrors: Boolean = config.getBoolean("app.show-internal-errors") + val dumpMessages: Boolean = config.getBoolean("app.dump-messages") + val showInternalErrors: Boolean = config.getBoolean("app.show-internal-errors") val maxResultsPerSearchResultPage: Int = config.getInt("app.max-results-per-search-result-page") - val standoffPerPage: Int = config.getInt("app.standoff-per-page") - val defaultIconSizeDimX: Int = config.getInt("app.gui.default-icon-size.dimX") - val defaultIconSizeDimY: Int = config.getInt("app.gui.default-icon-size.dimY") + val standoffPerPage: Int = config.getInt("app.standoff-per-page") + val defaultIconSizeDimX: Int = config.getInt("app.gui.default-icon-size.dimX") + val defaultIconSizeDimY: Int = config.getInt("app.gui.default-icon-size.dimY") - val v2ResultsPerPage: Int = config.getInt("app.v2.resources-sequence.results-per-page") + val v2ResultsPerPage: Int = config.getInt("app.v2.resources-sequence.results-per-page") val searchValueMinLength: Int = config.getInt("app.v2.fulltext-search.search-value-min-length") val defaultGraphDepth: Int = config.getInt("app.v2.graph-route.default-graph-depth") - val maxGraphDepth: Int = config.getInt("app.v2.graph-route.max-graph-depth") - val maxGraphBreadth: Int = config.getInt("app.v2.graph-route.max-graph-breadth") + val maxGraphDepth: Int = config.getInt("app.v2.graph-route.max-graph-depth") + val maxGraphBreadth: Int = config.getInt("app.v2.graph-route.max-graph-breadth") val triplestoreType: String = config.getString("app.triplestore.dbtype") val triplestoreHost: String = config.getString("app.triplestore.host") - val triplestoreQueryTimeout: FiniteDuration = getFiniteDuration("app.triplestore.query-timeout", config) + val triplestoreQueryTimeout: FiniteDuration = getFiniteDuration("app.triplestore.query-timeout", config) val triplestoreUpdateTimeout: FiniteDuration = getFiniteDuration("app.triplestore.update-timeout", config) val triplestoreUseHttps: Boolean = config.getBoolean("app.triplestore.use-https") val triplestoreAutoInit: Boolean = config.getBoolean("app.triplestore.auto-init") - val triplestorePort: Int = config.getInt("app.triplestore.fuseki.port") + val triplestorePort: Int = config.getInt("app.triplestore.fuseki.port") val triplestoreDatabaseName: String = config.getString("app.triplestore.fuseki.repository-name") - val triplestoreUsername: String = config.getString("app.triplestore.fuseki.username") - val triplestorePassword: String = config.getString("app.triplestore.fuseki.password") + val triplestoreUsername: String = config.getString("app.triplestore.fuseki.username") + val triplestorePassword: String = config.getString("app.triplestore.fuseki.password") //used in the store package val tripleStoreConfig: Config = config.getConfig("app.triplestore") private val fakeTriplestore: String = config.getString("app.triplestore.fake-triplestore") val prepareFakeTriplestore: Boolean = fakeTriplestore == "prepare" - val useFakeTriplestore: Boolean = fakeTriplestore == "use" - val fakeTriplestoreDataDir: Path = Paths.get(config.getString("app.triplestore.fake-triplestore-data-dir")) + val useFakeTriplestore: Boolean = fakeTriplestore == "use" + val fakeTriplestoreDataDir: Path = Paths.get(config.getString("app.triplestore.fake-triplestore-data-dir")) val skipAuthentication: Boolean = config.getBoolean("app.skip-authentication") - val jwtSecretKey: String = config.getString("app.jwt-secret-key") + val jwtSecretKey: String = config.getString("app.jwt-secret-key") val jwtLongevity: FiniteDuration = getFiniteDuration("app.jwt-longevity", config) val cookieDomain: String = config.getString("app.cookie-domain") @@ -307,7 +307,7 @@ class KnoraSettingsImpl(config: Config, log: LoggingAdapter) extends Extension { } val enabledByDefault: Boolean = featureConfig.getBoolean(enabledByDefaultKey) - val overrideAllowed: Boolean = featureConfig.getBoolean(overrideAllowedKey) + val overrideAllowed: Boolean = featureConfig.getBoolean(overrideAllowedKey) val expirationDate: Option[Instant] = if (featureConfig.hasPath(expirationDateKey)) { val definedExpirationDate: Instant = Instant.parse(featureConfig.getString(expirationDateKey)) @@ -361,14 +361,14 @@ object KnoraSettings extends ExtensionId[KnoraSettingsImpl] with ExtensionIdProv */ override def get(system: ActorSystem): KnoraSettingsImpl = super.get(system) - val featureTogglesPath: String = "app.feature-toggles" - val descriptionKey: String = "description" + val featureTogglesPath: String = "app.feature-toggles" + val descriptionKey: String = "description" val availableVersionsKey: String = "available-versions" - val developerEmailsKey: String = "developer-emails" - val expirationDateKey: String = "expiration-date" - val enabledByDefaultKey: String = "enabled-by-default" - val defaultVersionKey: String = "default-version" - val overrideAllowedKey: String = "override-allowed" + val developerEmailsKey: String = "developer-emails" + val expirationDateKey: String = "expiration-date" + val enabledByDefaultKey: String = "enabled-by-default" + val defaultVersionKey: String = "default-version" + val overrideAllowedKey: String = "override-allowed" /** * Represents the base configuration of a feature toggle. diff --git a/webapi/src/main/scala/org/knora/webapi/store/StoreManager.scala b/webapi/src/main/scala/org/knora/webapi/store/StoreManager.scala index 46c4860825..0e2aadb212 100644 --- a/webapi/src/main/scala/org/knora/webapi/store/StoreManager.scala +++ b/webapi/src/main/scala/org/knora/webapi/store/StoreManager.scala @@ -78,9 +78,10 @@ class StoreManager(appActor: ActorRef, csm: CacheServiceManager) extends Actor w ) def receive: Receive = LoggingReceive { - case tripleStoreMessage: TriplestoreRequest => triplestoreManager forward tripleStoreMessage - case iiifMessages: IIIFRequest => iiifManager forward iiifMessages - case cacheServiceMessages: CacheServiceRequest => ActorUtil.zio2Message(sender(), csm receive cacheServiceMessages, log) + case tripleStoreMessage: TriplestoreRequest => triplestoreManager forward tripleStoreMessage + case iiifMessages: IIIFRequest => iiifManager forward iiifMessages + case cacheServiceMessages: CacheServiceRequest => + ActorUtil.zio2Message(sender(), csm receive cacheServiceMessages, log) case other => sender() ! Status.Failure(UnexpectedMessageException(s"StoreManager received an unexpected message: $other")) } diff --git a/webapi/src/main/scala/org/knora/webapi/store/cacheservice/impl/CacheServiceInMemImpl.scala b/webapi/src/main/scala/org/knora/webapi/store/cacheservice/impl/CacheServiceInMemImpl.scala index 7622bea4a9..a558678988 100644 --- a/webapi/src/main/scala/org/knora/webapi/store/cacheservice/impl/CacheServiceInMemImpl.scala +++ b/webapi/src/main/scala/org/knora/webapi/store/cacheservice/impl/CacheServiceInMemImpl.scala @@ -57,7 +57,7 @@ case class CacheServiceInMemImpl( _ <- users.put(value.id, value) _ <- lut.put(value.username, value.id) _ <- lut.put(value.email, value.id) - } yield ()).commit.tap(_ => ZIO.logInfo(s"Stored UserADM to Cache: ${value.id}")) + } yield ()).commit.tap(_ => ZIO.logDebug(s"Stored UserADM to Cache: ${value.id}")) /** * Retrieves the user stored under the identifier (either iri, username, or email). @@ -72,7 +72,7 @@ case class CacheServiceInMemImpl( case UserIdentifierType.Iri => getUserByIri(identifier.toIri) case UserIdentifierType.Username => getUserByUsernameOrEmail(identifier.toUsername) case UserIdentifierType.Email => getUserByUsernameOrEmail(identifier.toEmail) - }).tap(_ => ZIO.logInfo(s"Retrieved UserADM from Cache: ${identifier}")) + }).tap(_ => ZIO.logDebug(s"Retrieved UserADM from Cache: ${identifier}")) /** * Retrieves the user stored under the IRI. @@ -111,7 +111,7 @@ case class CacheServiceInMemImpl( _ <- projects.put(value.id, value) _ <- lut.put(value.shortname, value.id) _ <- lut.put(value.shortcode, value.id) - } yield ()).commit.tap(_ => ZIO.logInfo(s"Stored ProjectADM to Cache: ${value.id}")) + } yield ()).commit.tap(_ => ZIO.logDebug(s"Stored ProjectADM to Cache: ${value.id}")) /** * Retrieves the project stored under the identifier (either iri, shortname, or shortcode). @@ -127,7 +127,7 @@ case class CacheServiceInMemImpl( case ProjectIdentifierType.IRI => getProjectByIri(identifier.toIri) case ProjectIdentifierType.SHORTCODE => getProjectByShortcodeOrShortname(identifier.toShortcode) case ProjectIdentifierType.SHORTNAME => getProjectByShortcodeOrShortname(identifier.toShortname) - }).tap(_ => ZIO.logInfo(s"Retrieved ProjectADM from Cache: $identifier")) + }).tap(_ => ZIO.logDebug(s"Retrieved ProjectADM from Cache: $identifier")) /** * Retrieves the project stored under the IRI. @@ -165,7 +165,7 @@ case class CacheServiceInMemImpl( key <- if (key.isEmpty()) Task.fail(emptyKeyError) else Task.succeed(key) value <- if (value.isEmpty()) Task.fail(emptyValueError) else Task.succeed(value) _ <- lut.put(key, value).commit - } yield ()).tap(_ => ZIO.logInfo(s"Wrote key: $key with value: $value to cache.")) + } yield ()).tap(_ => ZIO.logDebug(s"Wrote key: $key with value: $value to cache.")) } /** @@ -175,7 +175,7 @@ case class CacheServiceInMemImpl( * @return an optional [[String]]. */ def getStringValue(key: String): Task[Option[String]] = - lut.get(key).commit.tap(value => ZIO.logInfo(s"Retrieved key: $key with value: $value from cache.")) + lut.get(key).commit.tap(value => ZIO.logDebug(s"Retrieved key: $key with value: $value from cache.")) /** * Removes values for the provided keys. Any invalid keys are ignored. @@ -185,7 +185,7 @@ case class CacheServiceInMemImpl( def removeValues(keys: Set[String]): Task[Unit] = (for { _ <- ZIO.foreach(keys)(key => lut.delete(key).commit) // FIXME: is this realy thread safe? - } yield ()).tap(_ => ZIO.logInfo(s"Removed keys from cache: $keys")) + } yield ()).tap(_ => ZIO.logDebug(s"Removed keys from cache: $keys")) /** * Flushes (removes) all stored content from the in-memory cache. @@ -195,7 +195,7 @@ case class CacheServiceInMemImpl( _ <- users.foreach((k, v) => users.delete(k)) _ <- projects.foreach((k, v) => projects.delete(k)) _ <- lut.foreach((k, v) => lut.delete(k)) - } yield ()).commit.tap(_ => ZIO.logInfo("Flushed in-memory cache")) + } yield ()).commit.tap(_ => ZIO.logDebug("Flushed in-memory cache")) /** * Pings the in-memory cache to see if it is available. diff --git a/webapi/src/main/scala/org/knora/webapi/store/cacheservice/impl/CacheServiceRedisImpl.scala b/webapi/src/main/scala/org/knora/webapi/store/cacheservice/impl/CacheServiceRedisImpl.scala index e80141d606..e51e70d06a 100644 --- a/webapi/src/main/scala/org/knora/webapi/store/cacheservice/impl/CacheServiceRedisImpl.scala +++ b/webapi/src/main/scala/org/knora/webapi/store/cacheservice/impl/CacheServiceRedisImpl.scala @@ -73,7 +73,7 @@ case class CacheServiceRedisImpl(pool: JedisPool) extends CacheService { def getUserByIri(id: String): Task[Option[UserADM]] = (for { bytes <- getBytesValue(id).some - user <- CacheSerialization.deserialize[UserADM](bytes).some + user <- CacheSerialization.deserialize[UserADM](bytes).some } yield user).unsome /** @@ -178,8 +178,9 @@ case class CacheServiceRedisImpl(pool: JedisPool) extends CacheService { for { conn <- ZIO.attempt(pool.getResource) value <- ZIO.attemptBlocking(conn.get(key)) - res <- if (value == "nil".getBytes) Task.succeed(None) - else Task.succeed(Some(value)) + res <- + if (value == "nil".getBytes) Task.succeed(None) + else Task.succeed(Some(value)) _ = conn.close() } yield res }.catchAll(ex => ZIO.logError(s"Reading string from Redis failed: ${ex.getMessage}") *> Task.succeed(None)) @@ -237,8 +238,9 @@ case class CacheServiceRedisImpl(pool: JedisPool) extends CacheService { for { conn <- ZIO.attempt(pool.getResource).onError(ZIO.logErrorCause(_)).orDie value <- ZIO.attemptBlocking(conn.get(key.getBytes)) - res <- if (value == "nil".getBytes) Task.succeed(None) - else Task.succeed(Some(value)) + res <- + if (value == "nil".getBytes) Task.succeed(None) + else Task.succeed(Some(value)) _ = conn.close() } yield res diff --git a/webapi/src/main/scala/org/knora/webapi/store/cacheservice/settings/CacheServiceSettings.scala b/webapi/src/main/scala/org/knora/webapi/store/cacheservice/settings/CacheServiceSettings.scala index fdd89f4d6a..6ddfa0dd6f 100644 --- a/webapi/src/main/scala/org/knora/webapi/store/cacheservice/settings/CacheServiceSettings.scala +++ b/webapi/src/main/scala/org/knora/webapi/store/cacheservice/settings/CacheServiceSettings.scala @@ -11,7 +11,7 @@ import com.typesafe.config.Config * Holds the Cache Service specific settings. */ class CacheServiceSettings(config: Config) { - val cacheServiceEnabled: Boolean = config.getBoolean("app.cache-service.enabled") + val cacheServiceEnabled: Boolean = config.getBoolean("app.cache-service.enabled") val cacheServiceRedisHost: String = config.getString("app.cache-service.redis.host") - val cacheServiceRedisPort: Int = config.getInt("app.cache-service.redis.port") + val cacheServiceRedisPort: Int = config.getInt("app.cache-service.redis.port") } diff --git a/webapi/src/main/scala/org/knora/webapi/store/iiif/SipiConnector.scala b/webapi/src/main/scala/org/knora/webapi/store/iiif/SipiConnector.scala index 031ed14476..3f1e492f34 100644 --- a/webapi/src/main/scala/org/knora/webapi/store/iiif/SipiConnector.scala +++ b/webapi/src/main/scala/org/knora/webapi/store/iiif/SipiConnector.scala @@ -38,7 +38,7 @@ import scala.util.Try */ class SipiConnector extends Actor with ActorLogging { - implicit val system: ActorSystem = context.system + implicit val system: ActorSystem = context.system implicit val executionContext: ExecutionContext = system.dispatchers.lookup(KnoraDispatchers.KnoraActorDispatcher) private val settings = KnoraSettings(system) @@ -142,10 +142,10 @@ class SipiConnector extends Actor with ActorLogging { import SipiKnoraJsonResponseProtocol._ val knoraInfoUrl = getFileMetadataRequest.fileUrl + "/knora.json" - val sipiRequest = new HttpGet(knoraInfoUrl) + val sipiRequest = new HttpGet(knoraInfoUrl) for { - sipiResponseStr <- doSipiRequest(sipiRequest) + sipiResponseStr <- doSipiRequest(sipiRequest) sipiResponse: SipiKnoraJsonResponse = sipiResponseStr.parseJson.convertTo[SipiKnoraJsonResponse] } yield GetFileMetadataResponse( originalFilename = sipiResponse.originalFilename, @@ -177,8 +177,8 @@ class SipiConnector extends Actor with ActorLogging { "knora-data" -> JsObject( Map( "permission" -> JsString("StoreFile"), - "filename" -> JsString(moveTemporaryFileToPermanentStorageRequestV2.internalFilename), - "prefix" -> JsString(moveTemporaryFileToPermanentStorageRequestV2.prefix) + "filename" -> JsString(moveTemporaryFileToPermanentStorageRequestV2.internalFilename), + "prefix" -> JsString(moveTemporaryFileToPermanentStorageRequestV2.prefix) ) ) ) @@ -214,7 +214,7 @@ class SipiConnector extends Actor with ActorLogging { "knora-data" -> JsObject( Map( "permission" -> JsString("DeleteTempFile"), - "filename" -> JsString(deleteTemporaryFileRequestV2.internalFilename) + "filename" -> JsString(deleteTemporaryFileRequestV2.internalFilename) ) ) ) @@ -286,7 +286,7 @@ class SipiConnector extends Actor with ActorLogging { * @return Sipi's response. */ private def doSipiRequest(request: HttpRequest): Try[String] = { - val httpContext: HttpClientContext = HttpClientContext.create() + val httpContext: HttpClientContext = HttpClientContext.create() var maybeResponse: Option[CloseableHttpResponse] = None val sipiResponseTry = Try { @@ -297,7 +297,7 @@ class SipiConnector extends Actor with ActorLogging { case None => "" } - val statusCode: Int = maybeResponse.get.getStatusLine.getStatusCode + val statusCode: Int = maybeResponse.get.getStatusLine.getStatusCode val statusCategory: Int = statusCode / 100 // Was the request successful? diff --git a/webapi/src/main/scala/org/knora/webapi/store/triplestore/http/HttpTriplestoreConnector.scala b/webapi/src/main/scala/org/knora/webapi/store/triplestore/http/HttpTriplestoreConnector.scala index 0d7be38513..72d7683ed1 100644 --- a/webapi/src/main/scala/org/knora/webapi/store/triplestore/http/HttpTriplestoreConnector.scala +++ b/webapi/src/main/scala/org/knora/webapi/store/triplestore/http/HttpTriplestoreConnector.scala @@ -74,16 +74,16 @@ import scala.util.Try class HttpTriplestoreConnector extends Actor with ActorLogging with InstrumentationSupport { // MIME type constants. - private val mimeTypeApplicationJson = "application/json" + private val mimeTypeApplicationJson = "application/json" private val mimeTypeApplicationSparqlResultsJson = "application/sparql-results+json" - private val mimeTypeTextTurtle = "text/turtle" - private val mimeTypeApplicationSparqlUpdate = "application/sparql-update" - private val mimeTypeApplicationNQuads = "application/n-quads" + private val mimeTypeTextTurtle = "text/turtle" + private val mimeTypeApplicationSparqlUpdate = "application/sparql-update" + private val mimeTypeApplicationNQuads = "application/n-quads" - private implicit val system: ActorSystem = context.system - private val settings = KnoraSettings(system) + private implicit val system: ActorSystem = context.system + private val settings = KnoraSettings(system) implicit val executionContext: ExecutionContext = system.dispatchers.lookup(KnoraDispatchers.KnoraBlockingDispatcher) - override val log: LoggingAdapter = akka.event.Logging(system, this.getClass.getName) + override val log: LoggingAdapter = akka.event.Logging(system, this.getClass.getName) private val targetHost: HttpHost = new HttpHost(settings.triplestoreHost, settings.triplestorePort, "http") @@ -192,8 +192,9 @@ class HttpTriplestoreConnector extends Actor with ActorLogging with Instrumentat case DropAllTRepositoryContent() => try2Message(sender(), dropAllTriplestoreContent(), log) case InsertRepositoryContent(rdfDataObjects: Seq[RdfDataObject]) => try2Message(sender(), insertDataIntoTriplestore(rdfDataObjects), log) - case HelloTriplestore(msg: String) if msg == settings.triplestoreType => sender() ! HelloTriplestore(settings.triplestoreType) - case CheckTriplestoreRequest() => try2Message(sender(), checkTriplestore(), log) + case HelloTriplestore(msg: String) if msg == settings.triplestoreType => + sender() ! HelloTriplestore(settings.triplestoreType) + case CheckTriplestoreRequest() => try2Message(sender(), checkTriplestore(), log) case SearchIndexUpdateRequest(subjectIri: Option[String]) => try2Message(sender(), Success(SparqlUpdateResponse()), log) case DownloadRepositoryRequest(outputFile: Path, featureFactoryConfig: FeatureFactoryConfig) => @@ -267,9 +268,9 @@ class HttpTriplestoreConnector extends Actor with ActorLogging with Instrumentat // Are we preparing a fake triplestore? _ = if (settings.prepareFakeTriplestore) { - // Yes: add the query and the response to it. - FakeTriplestore.add(sparql, resultStr, log) - } + // Yes: add the query and the response to it. + FakeTriplestore.add(sparql, resultStr, log) + } // _ = println(s"SPARQL: $logDelimiter$sparql") // _ = println(s"Result: $logDelimiter$resultStr") @@ -296,13 +297,13 @@ class HttpTriplestoreConnector extends Actor with ActorLogging with Instrumentat rdfFormatUtil: RdfFormatUtil ): Try[SparqlConstructResponse] = { val parseTry = Try { - val rdfModel: RdfModel = rdfFormatUtil.parseToRdfModel(rdfStr = turtleStr, rdfFormat = Turtle) + val rdfModel: RdfModel = rdfFormatUtil.parseToRdfModel(rdfStr = turtleStr, rdfFormat = Turtle) val statementMap: mutable.Map[IRI, Seq[(IRI, String)]] = mutable.Map.empty for (st: Statement <- rdfModel) { - val subjectIri = st.subj.stringValue + val subjectIri = st.subj.stringValue val predicateIri = st.pred.stringValue - val objectIri = st.obj.stringValue + val objectIri = st.obj.stringValue val currentStatementsForSubject: Seq[(IRI, String)] = statementMap.getOrElse(subjectIri, Vector.empty[(IRI, String)]) statementMap += (subjectIri -> (currentStatementsForSubject :+ (predicateIri, objectIri))) @@ -338,10 +339,10 @@ class HttpTriplestoreConnector extends Actor with ActorLogging with Instrumentat getSparqlHttpResponse(sparqlConstructRequest.sparql, isUpdate = false, acceptMimeType = mimeTypeTextTurtle) response <- parseTurtleResponse( - sparql = sparqlConstructRequest.sparql, - turtleStr = turtleStr, - rdfFormatUtil = rdfFormatUtil - ) + sparql = sparqlConstructRequest.sparql, + turtleStr = turtleStr, + rdfFormatUtil = rdfFormatUtil + ) } yield response } @@ -367,11 +368,11 @@ class HttpTriplestoreConnector extends Actor with ActorLogging with Instrumentat turtleStr <- getSparqlHttpResponse(sparql, isUpdate = false, acceptMimeType = mimeTypeTextTurtle) _ = rdfFormatUtil.turtleToQuadsFile( - rdfSource = RdfStringSource(turtleStr), - graphIri = graphIri, - outputFile = outputFile, - outputFormat = outputFormat - ) + rdfSource = RdfStringSource(turtleStr), + graphIri = graphIri, + outputFile = outputFile, + outputFormat = outputFormat + ) } yield FileWrittenResponse() } @@ -390,16 +391,16 @@ class HttpTriplestoreConnector extends Actor with ActorLogging with Instrumentat val parseTry = for { turtleStr <- getSparqlHttpResponse( - sparqlExtendedConstructRequest.sparql, - isUpdate = false, - acceptMimeType = mimeTypeTextTurtle - ) + sparqlExtendedConstructRequest.sparql, + isUpdate = false, + acceptMimeType = mimeTypeTextTurtle + ) response <- SparqlExtendedConstructResponse.parseTurtleResponse( - turtleStr = turtleStr, - rdfFormatUtil = rdfFormatUtil, - log = log - ) + turtleStr = turtleStr, + rdfFormatUtil = rdfFormatUtil, + log = log + ) } yield response parseTry match { @@ -438,7 +439,7 @@ class HttpTriplestoreConnector extends Actor with ActorLogging with Instrumentat def sparqlHttpAsk(sparql: String): Try[SparqlAskResponse] = for { resultString <- getSparqlHttpResponse(sparql, isUpdate = false) - _ = log.debug("sparqlHttpAsk - resultString: {}", resultString) + _ = log.debug("sparqlHttpAsk - resultString: {}", resultString) result: Boolean = resultString.parseJson.asJsObject.getFields("boolean").head.convertTo[Boolean] } yield SparqlAskResponse(result) @@ -474,7 +475,7 @@ class HttpTriplestoreConnector extends Actor with ActorLogging with Instrumentat val response: Try[DropAllRepositoryContentACK] = for { result: String <- getSparqlHttpResponse(dropAllSparqlString, isUpdate = true) - _ = log.debug(s"==>> Drop All Data End, Result: $result") + _ = log.debug(s"==>> Drop All Data End, Result: $result") } yield DropAllRepositoryContentACK() response.recover { case t: Exception => @@ -596,7 +597,7 @@ class HttpTriplestoreConnector extends Actor with ActorLogging with Instrumentat responseTry.get } - val nameShouldBe = settings.triplestoreDatabaseName + val nameShouldBe = settings.triplestoreDatabaseName val fusekiServer: FusekiServer = JsonParser(responseStr).convertTo[FusekiServer] val neededDataset: Option[FusekiDataset] = fusekiServer.datasets.find(dataset => dataset.dsName == s"/$nameShouldBe" && dataset.dsState) @@ -674,8 +675,8 @@ class HttpTriplestoreConnector extends Actor with ActorLogging with Instrumentat } val httpContext: HttpClientContext = makeHttpContext - val httpPost: HttpPost = new HttpPost("/$/datasets") - val stringEntity = new StringEntity(triplestoreConfig, ContentType.create(mimeTypeTextTurtle)) + val httpPost: HttpPost = new HttpPost("/$/datasets") + val stringEntity = new StringEntity(triplestoreConfig, ContentType.create(mimeTypeTextTurtle)) httpPost.setEntity(stringEntity) doHttpRequest( @@ -717,7 +718,7 @@ class HttpTriplestoreConnector extends Actor with ActorLogging with Instrumentat featureFactoryConfig: FeatureFactoryConfig ): Try[FileWrittenResponse] = { val httpContext: HttpClientContext = makeHttpContext - val httpGet = new HttpGet(makeNamedGraphDownloadUri(graphIri)) + val httpGet = new HttpGet(makeNamedGraphDownloadUri(graphIri)) httpGet.addHeader("Accept", mimeTypeTextTurtle) val makeResponse: CloseableHttpResponse => FileWrittenResponse = writeResponseFile( @@ -742,7 +743,7 @@ class HttpTriplestoreConnector extends Actor with ActorLogging with Instrumentat */ private def sparqlHttpGraphData(graphIri: IRI): Try[NamedGraphDataResponse] = { val httpContext: HttpClientContext = makeHttpContext - val httpGet = new HttpGet(makeNamedGraphDownloadUri(graphIri)) + val httpGet = new HttpGet(makeNamedGraphDownloadUri(graphIri)) httpGet.addHeader("Accept", mimeTypeTextTurtle) val makeResponse: CloseableHttpResponse => NamedGraphDataResponse = returnGraphDataAsTurtle(graphIri) @@ -774,7 +775,7 @@ class HttpTriplestoreConnector extends Actor with ActorLogging with Instrumentat val (httpClient: CloseableHttpClient, httpPost: HttpPost) = if (isUpdate) { // Send updates as application/sparql-update (as per SPARQL 1.1 Protocol §3.2.2, "UPDATE using POST directly"). - val requestEntity = new StringEntity(sparql, ContentType.create(mimeTypeApplicationSparqlUpdate, "UTF-8")) + val requestEntity = new StringEntity(sparql, ContentType.create(mimeTypeApplicationSparqlUpdate, "UTF-8")) val updateHttpPost = new HttpPost(sparqlUpdatePath) updateHttpPost.setEntity(requestEntity) (updateHttpClient, updateHttpPost) @@ -784,7 +785,7 @@ class HttpTriplestoreConnector extends Actor with ActorLogging with Instrumentat val formParams = new util.ArrayList[NameValuePair]() formParams.add(new BasicNameValuePair("query", sparql)) val requestEntity: UrlEncodedFormEntity = new UrlEncodedFormEntity(formParams, Consts.UTF_8) - val queryHttpPost: HttpPost = new HttpPost(queryPath) + val queryHttpPost: HttpPost = new HttpPost(queryPath) queryHttpPost.setEntity(requestEntity) queryHttpPost.addHeader("Accept", acceptMimeType) (queryHttpClient, queryHttpPost) @@ -851,8 +852,8 @@ class HttpTriplestoreConnector extends Actor with ActorLogging with Instrumentat */ private def uploadRepository(inputFile: Path): Try[RepositoryUploadedResponse] = { val httpContext: HttpClientContext = makeHttpContext - val httpPost: HttpPost = new HttpPost(repositoryUploadPath) - val fileEntity = new FileEntity(inputFile.toFile, ContentType.create(mimeTypeApplicationNQuads, "UTF-8")) + val httpPost: HttpPost = new HttpPost(repositoryUploadPath) + val fileEntity = new FileEntity(inputFile.toFile, ContentType.create(mimeTypeApplicationNQuads, "UTF-8")) httpPost.setEntity(fileEntity) doHttpRequest( @@ -871,10 +872,10 @@ class HttpTriplestoreConnector extends Actor with ActorLogging with Instrumentat */ private def insertDataGraphRequest(graphContent: String, graphName: String): Try[InsertGraphDataContentResponse] = { val httpContext: HttpClientContext = makeHttpContext - val uriBuilder: URIBuilder = new URIBuilder(dataInsertPath) + val uriBuilder: URIBuilder = new URIBuilder(dataInsertPath) uriBuilder.addParameter("graph", graphName) val httpPut: HttpPut = new HttpPut(uriBuilder.build()) - val requestEntity = new StringEntity(graphContent, ContentType.create(mimeTypeTextTurtle, "UTF-8")) + val requestEntity = new StringEntity(graphContent, ContentType.create(mimeTypeTextTurtle, "UTF-8")) httpPut.setEntity(requestEntity) val makeResponse: CloseableHttpResponse => InsertGraphDataContentResponse = returnInsertGraphDataResponse(graphName) @@ -892,7 +893,7 @@ class HttpTriplestoreConnector extends Actor with ActorLogging with Instrumentat * @return httpContext with credentials and authorization */ private def makeHttpContext: HttpClientContext = { - val authCache: AuthCache = new BasicAuthCache + val authCache: AuthCache = new BasicAuthCache val basicAuth: BasicScheme = new BasicScheme authCache.put(targetHost, basicAuth) @@ -930,7 +931,7 @@ class HttpTriplestoreConnector extends Actor with ActorLogging with Instrumentat throw new java.net.SocketTimeoutException("Simulated read timeout") } - val start = System.currentTimeMillis() + val start = System.currentTimeMillis() val response = client.execute(targetHost, request, context) maybeResponse = Some(response) val statusCode: Int = response.getStatusLine.getStatusCode diff --git a/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/RepositoryUpdater.scala b/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/RepositoryUpdater.scala index 7a9ed5f3da..8505a88d46 100644 --- a/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/RepositoryUpdater.scala +++ b/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/RepositoryUpdater.scala @@ -77,17 +77,17 @@ class RepositoryUpdater( private val tempDirNamePrefix: String = "knora" /** - * Deletes directories inside temp directory starting with `tempDirNamePrefix`. - */ + * Deletes directories inside temp directory starting with `tempDirNamePrefix`. + */ def deleteTempDirectories(): Unit = { - val rootDir = new File("/tmp/") + val rootDir = new File("/tmp/") val getTempToDelete = rootDir.listFiles.filter(_.getName.startsWith(tempDirNamePrefix)) if (getTempToDelete.length != 0) { - getTempToDelete.foreach(dir => { + getTempToDelete.foreach { dir => val dirToDelete = new Directory(dir) dirToDelete.deleteRecursively() - }) + } log.info(s"Deleted temp directories: ${getTempToDelete.map(_.getName()).mkString(", ")}") } } @@ -100,7 +100,7 @@ class RepositoryUpdater( def maybeUpdateRepository: Future[RepositoryUpdatedResponse] = for { foundRepositoryVersion: Option[String] <- getRepositoryVersion - requiredRepositoryVersion = org.knora.webapi.KnoraBaseVersion + requiredRepositoryVersion = org.knora.webapi.KnoraBaseVersion // Is the repository up to date? repositoryUpToDate: Boolean = foundRepositoryVersion.contains(requiredRepositoryVersion) @@ -133,7 +133,7 @@ class RepositoryUpdater( private def getRepositoryVersion: Future[Option[String]] = for { repositoryVersionResponse: SparqlSelectResult <- (appActor ? SparqlSelectRequest(knoraBaseVersionQuery)) - .mapTo[SparqlSelectResult] + .mapTo[SparqlSelectResult] bindings = repositoryVersionResponse.results.bindings @@ -190,23 +190,23 @@ class RepositoryUpdater( log.info(s"Repository update using download directory $downloadDir") // The file to save the repository in. - val downloadedRepositoryFile = downloadDir.resolve("downloaded-repository.nq") + val downloadedRepositoryFile = downloadDir.resolve("downloaded-repository.nq") val transformedRepositoryFile = downloadDir.resolve("transformed-repository.nq") log.info("Downloading repository file...") for { // Ask the store actor to download the repository to the file. _: FileWrittenResponse <- (appActor ? DownloadRepositoryRequest( - outputFile = downloadedRepositoryFile, - featureFactoryConfig = featureFactoryConfig - )).mapTo[FileWrittenResponse] + outputFile = downloadedRepositoryFile, + featureFactoryConfig = featureFactoryConfig + )).mapTo[FileWrittenResponse] // Run the transformations to produce an output file. _ = doTransformations( - downloadedRepositoryFile = downloadedRepositoryFile, - transformedRepositoryFile = transformedRepositoryFile, - pluginsForNeededUpdates = pluginsForNeededUpdates - ) + downloadedRepositoryFile = downloadedRepositoryFile, + transformedRepositoryFile = transformedRepositoryFile, + pluginsForNeededUpdates = pluginsForNeededUpdates + ) _ = log.info("Emptying the repository...") @@ -217,7 +217,7 @@ class RepositoryUpdater( // Upload the transformed repository. _: RepositoryUploadedResponse <- (appActor ? UploadRepositoryRequest(transformedRepositoryFile)) - .mapTo[RepositoryUploadedResponse] + .mapTo[RepositoryUploadedResponse] } yield RepositoryUpdatedResponse( message = s"Updated repository to ${org.knora.webapi.KnoraBaseVersion}" ) diff --git a/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1307.scala b/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1307.scala index 80330e88b3..cc1c2e914f 100644 --- a/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1307.scala +++ b/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1307.scala @@ -19,8 +19,8 @@ class UpgradePluginPR1307(featureFactoryConfig: FeatureFactoryConfig) extends Up private val nodeFactory: RdfNodeFactory = RdfFeatureFactory.getRdfNodeFactory(featureFactoryConfig) // IRI objects representing the IRIs used in this transformation. - private val rdfTypeIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.Rdf.Type) - private val TextValueIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.KnoraBase.TextValue) + private val rdfTypeIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.Rdf.Type) + private val TextValueIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.KnoraBase.TextValue) private val ValueHasStandoffIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.KnoraBase.ValueHasStandoff) private val StandoffTagHasStartIndexIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.KnoraBase.StandoffTagHasStartIndex) @@ -63,7 +63,7 @@ class UpgradePluginPR1307(featureFactoryConfig: FeatureFactoryConfig) extends Up */ lazy val newIri: IriNode = { val oldSubjStr: String = oldIri.stringValue - val slashPos: Int = oldSubjStr.lastIndexOf('/') + val slashPos: Int = oldSubjStr.lastIndexOf('/') nodeFactory.makeIriNode(oldSubjStr.substring(0, slashPos + 1) + startIndex.toString) } diff --git a/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1322.scala b/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1322.scala index ebd7110db3..eb554d7ab3 100644 --- a/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1322.scala +++ b/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1322.scala @@ -15,13 +15,13 @@ import org.knora.webapi.store.triplestore.upgrade.UpgradePlugin * Transforms a repository for Knora PR 1322. */ class UpgradePluginPR1322(featureFactoryConfig: FeatureFactoryConfig) extends UpgradePlugin { - private val nodeFactory: RdfNodeFactory = RdfFeatureFactory.getRdfNodeFactory(featureFactoryConfig) + private val nodeFactory: RdfNodeFactory = RdfFeatureFactory.getRdfNodeFactory(featureFactoryConfig) private implicit val stringFormatter: StringFormatter = StringFormatter.getInstanceForConstantOntologies // IRI objects representing the IRIs used in this transformation. - private val ValueHasUUIDIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.KnoraBase.ValueHasUUID) + private val ValueHasUUIDIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.KnoraBase.ValueHasUUID) private val ValueCreationDateIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.KnoraBase.ValueCreationDate) - private val PreviousValueIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.KnoraBase.PreviousValue) + private val PreviousValueIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.KnoraBase.PreviousValue) override def transform(model: RdfModel): Unit = // Add a random UUID to each current value version. diff --git a/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1367.scala b/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1367.scala index 001fab9282..f70697436d 100644 --- a/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1367.scala +++ b/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1367.scala @@ -20,7 +20,7 @@ class UpgradePluginPR1367(featureFactoryConfig: FeatureFactoryConfig) extends Up // Fix the datatypes of decimal literals. val statementsToRemove: collection.mutable.Set[Statement] = collection.mutable.Set.empty - val statementsToAdd: collection.mutable.Set[Statement] = collection.mutable.Set.empty + val statementsToAdd: collection.mutable.Set[Statement] = collection.mutable.Set.empty for (statement: Statement <- model) { statement.obj match { diff --git a/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1372.scala b/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1372.scala index c6813e3cd5..be368cc518 100644 --- a/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1372.scala +++ b/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1372.scala @@ -19,8 +19,8 @@ class UpgradePluginPR1372(featureFactoryConfig: FeatureFactoryConfig) extends Up // IRI objects representing the IRIs used in this transformation. private val ValueCreationDateIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.KnoraBase.ValueCreationDate) - private val PreviousValueIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.KnoraBase.PreviousValue) - private val HasPermissionsIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.KnoraBase.HasPermissions) + private val PreviousValueIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.KnoraBase.PreviousValue) + private val HasPermissionsIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.KnoraBase.HasPermissions) override def transform(model: RdfModel): Unit = // Remove knora-base:hasPermissions from all past value versions. diff --git a/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1746.scala b/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1746.scala index 4fe88a77cb..b8e61f4c53 100644 --- a/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1746.scala +++ b/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1746.scala @@ -21,7 +21,7 @@ class UpgradePluginPR1746(featureFactoryConfig: FeatureFactoryConfig, log: Logge override def transform(model: RdfModel): Unit = { val statementsToRemove: collection.mutable.Set[Statement] = collection.mutable.Set.empty - val statementsToAdd: collection.mutable.Set[Statement] = collection.mutable.Set.empty + val statementsToAdd: collection.mutable.Set[Statement] = collection.mutable.Set.empty def replaceEmptyStringWithDummy(statement: Statement, languageTag: Option[String]): Unit = { val fixMeString: RdfLiteral = languageTag match { diff --git a/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1921.scala b/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1921.scala index 9b2f36127b..c0ce2abbe4 100644 --- a/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1921.scala +++ b/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1921.scala @@ -21,7 +21,7 @@ class UpgradePluginPR1921(featureFactoryConfig: FeatureFactoryConfig, log: Logge override def transform(model: RdfModel): Unit = { val statementsToRemove: collection.mutable.Set[Statement] = collection.mutable.Set.empty - val statementsToAdd: collection.mutable.Set[Statement] = collection.mutable.Set.empty + val statementsToAdd: collection.mutable.Set[Statement] = collection.mutable.Set.empty val newPredicateLabel: IriNode = nodeFactory.makeIriNode("http://www.knora.org/ontology/knora-admin#groupDescriptions") diff --git a/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR2018.scala b/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR2018.scala index 6dd4c6ad5d..3536d7287e 100644 --- a/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR2018.scala +++ b/webapi/src/main/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR2018.scala @@ -22,8 +22,8 @@ import com.typesafe.scalalogging.Logger */ class UpgradePluginPR2018(featureFactoryConfig: FeatureFactoryConfig, log: Logger) extends UpgradePlugin { private val nodeFactory: RdfNodeFactory = RdfFeatureFactory.getRdfNodeFactory(featureFactoryConfig) - private val newModificationDate = Instant.now.toString - private val ontologyType: IriNode = nodeFactory.makeIriNode(Ontology) + private val newModificationDate = Instant.now.toString + private val ontologyType: IriNode = nodeFactory.makeIriNode(Ontology) override def transform(model: RdfModel): Unit = for (ontology: IriNode <- getOntologiesToTransform(model)) { diff --git a/webapi/src/main/scala/org/knora/webapi/util/ActorUtil.scala b/webapi/src/main/scala/org/knora/webapi/util/ActorUtil.scala index 5bb7fa37e2..7163107498 100644 --- a/webapi/src/main/scala/org/knora/webapi/util/ActorUtil.scala +++ b/webapi/src/main/scala/org/knora/webapi/util/ActorUtil.scala @@ -29,7 +29,7 @@ object ActorUtil { /** * Transforms ZIO Task returned to the receive method of an actor to a message. Used mainly during the refactoring * phase, to be able to return ZIO inside an Actor. - * + * * It performs the same functionality as [[future2Message]] does, rewritten completely uzing ZIOs. */ def zio2Message[A](sender: ActorRef, zioTask: zio.Task[A], log: LoggingAdapter): Unit = diff --git a/webapi/src/main/scala/org/knora/webapi/util/FileUtil.scala b/webapi/src/main/scala/org/knora/webapi/util/FileUtil.scala index 2c7247c082..ce12a2deaf 100644 --- a/webapi/src/main/scala/org/knora/webapi/util/FileUtil.scala +++ b/webapi/src/main/scala/org/knora/webapi/util/FileUtil.scala @@ -97,7 +97,7 @@ object FileUtil { */ def createZipFileBytes(contents: Map[String, Array[Byte]]): Array[Byte] = { val byteArrayOutputStream = new ByteArrayOutputStream() - val zipOutputStream = new ZipOutputStream(byteArrayOutputStream) + val zipOutputStream = new ZipOutputStream(byteArrayOutputStream) val bytesTry = Try { contents.foreach { case (filename: String, content: Array[Byte]) => diff --git a/webapi/src/main/scala/org/knora/webapi/util/cache/CacheUtil.scala b/webapi/src/main/scala/org/knora/webapi/util/cache/CacheUtil.scala index cbb3dfd995..fac44da38a 100644 --- a/webapi/src/main/scala/org/knora/webapi/util/cache/CacheUtil.scala +++ b/webapi/src/main/scala/org/knora/webapi/util/cache/CacheUtil.scala @@ -97,7 +97,7 @@ object CacheUtil { */ def put[V](cacheName: String, key: String, value: V): Unit = { val cacheManager = CacheManager.getInstance() - val cacheOption = Option(cacheManager.getCache(cacheName)) + val cacheOption = Option(cacheManager.getCache(cacheName)) cacheOption match { case Some(cache) => @@ -117,7 +117,7 @@ object CacheUtil { */ def get[V](cacheName: String, key: String): Option[V] = { val cacheManager = CacheManager.getInstance() - val cacheOption = Option(cacheManager.getCache(cacheName)) + val cacheOption = Option(cacheManager.getCache(cacheName)) cacheOption match { case Some(cache) => @@ -145,7 +145,7 @@ object CacheUtil { */ def remove(cacheName: String, key: String): Unit = { val cacheManager = CacheManager.getInstance() - val cacheOption = Option(cacheManager.getCache(cacheName)) + val cacheOption = Option(cacheManager.getCache(cacheName)) cacheOption match { case Some(cache) => cache.remove(key) diff --git a/webapi/src/test/scala/org/knora/webapi/AsyncCoreSpec.scala b/webapi/src/test/scala/org/knora/webapi/AsyncCoreSpec.scala index 1fb4932471..83be280cc4 100644 --- a/webapi/src/test/scala/org/knora/webapi/AsyncCoreSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/AsyncCoreSpec.scala @@ -72,7 +72,7 @@ abstract class AsyncCoreSpec(_system: ActorSystem) /* needed by the core trait */ implicit lazy val settings: KnoraSettingsImpl = KnoraSettings(system) - implicit val materializer: Materializer = Materializer.matFromSystem(system) + implicit val materializer: Materializer = Materializer.matFromSystem(system) override implicit val executionContext: ExecutionContext = system.dispatchers.lookup(KnoraDispatchers.KnoraActorDispatcher) @@ -90,7 +90,7 @@ abstract class AsyncCoreSpec(_system: ActorSystem) // The main application actor forwards messages to the responder manager and the store manager. val responderManager: ActorRef = appActor - val storeManager: ActorRef = appActor + val storeManager: ActorRef = appActor val responderData: ResponderData = ResponderData( system = system, diff --git a/webapi/src/test/scala/org/knora/webapi/CoreSpec.scala b/webapi/src/test/scala/org/knora/webapi/CoreSpec.scala index 78ff800beb..3d4db50425 100644 --- a/webapi/src/test/scala/org/knora/webapi/CoreSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/CoreSpec.scala @@ -94,8 +94,8 @@ abstract class CoreSpec(_system: ActorSystem) ) /* needed by the core trait */ - implicit lazy val settings: KnoraSettingsImpl = KnoraSettings(system) - implicit val materializer: Materializer = Materializer.matFromSystem(system) + implicit lazy val settings: KnoraSettingsImpl = KnoraSettings(system) + implicit val materializer: Materializer = Materializer.matFromSystem(system) implicit val executionContext: ExecutionContext = system.dispatchers.lookup(KnoraDispatchers.KnoraActorDispatcher) // can be overridden in individual spec @@ -112,7 +112,7 @@ abstract class CoreSpec(_system: ActorSystem) // The main application actor forwards messages to the responder manager and the store manager. val responderManager: ActorRef = appActor - val storeManager: ActorRef = appActor + val storeManager: ActorRef = appActor val responderData: ResponderData = ResponderData( system = system, diff --git a/webapi/src/test/scala/org/knora/webapi/E2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/E2ESpec.scala index bc94bd193c..ee265f262a 100644 --- a/webapi/src/test/scala/org/knora/webapi/E2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/E2ESpec.scala @@ -70,8 +70,8 @@ class E2ESpec(_system: ActorSystem) def this() = this(ActorSystem("E2ETest", TestContainersAll.PortConfig.withFallback(E2ESpec.defaultConfig))) /* needed by the core trait */ - implicit lazy val settings: KnoraSettingsImpl = KnoraSettings(system) - implicit val materializer: Materializer = Materializer.matFromSystem(system) + implicit lazy val settings: KnoraSettingsImpl = KnoraSettings(system) + implicit val materializer: Materializer = Materializer.matFromSystem(system) implicit val executionContext: ExecutionContext = system.dispatchers.lookup(KnoraDispatchers.KnoraActorDispatcher) // can be overridden in individual spec @@ -138,7 +138,7 @@ class E2ESpec(_system: ActorSystem) protected def responseToJsonLDDocument(httpResponse: HttpResponse): JsonLDDocument = { val responseBodyFuture: Future[String] = httpResponse.entity.toStrict(10.seconds).map(_.data.decodeString("UTF-8")) - val responseBodyStr = Await.result(responseBodyFuture, 10.seconds) + val responseBodyStr = Await.result(responseBodyFuture, 10.seconds) JsonLDUtil.parseJsonLD(responseBodyStr) } @@ -148,7 +148,7 @@ class E2ESpec(_system: ActorSystem) } protected def doGetRequest(urlPath: String): String = { - val request = Get(s"$baseApiUrl$urlPath") + val request = Get(s"$baseApiUrl$urlPath") val response: HttpResponse = singleAwaitingRequest(request) responseToString(response) } diff --git a/webapi/src/test/scala/org/knora/webapi/ITKnoraFakeSpec.scala b/webapi/src/test/scala/org/knora/webapi/ITKnoraFakeSpec.scala index 99e092630a..90c63f1e76 100644 --- a/webapi/src/test/scala/org/knora/webapi/ITKnoraFakeSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/ITKnoraFakeSpec.scala @@ -61,9 +61,9 @@ class ITKnoraFakeSpec(_system: ActorSystem) this(ActorSystem("IntegrationTests", TestContainersAll.PortConfig.withFallback(ITKnoraFakeSpec.defaultConfig))) /* needed by the core trait */ - implicit lazy val system: ActorSystem = _system - implicit lazy val settings: KnoraSettingsImpl = KnoraSettings(system) - implicit val materializer: Materializer = Materializer.matFromSystem(system) + implicit lazy val system: ActorSystem = _system + implicit lazy val settings: KnoraSettingsImpl = KnoraSettings(system) + implicit val materializer: Materializer = Materializer.matFromSystem(system) implicit val executionContext: ExecutionContext = system.dispatchers.lookup(KnoraDispatchers.KnoraActorDispatcher) /* Needs to be initialized before any responders */ @@ -72,7 +72,7 @@ class ITKnoraFakeSpec(_system: ActorSystem) val log: LoggingAdapter = akka.event.Logging(system, this.getClass) - protected val baseApiUrl: String = settings.internalKnoraApiBaseUrl + protected val baseApiUrl: String = settings.internalKnoraApiBaseUrl protected val baseInternalSipiUrl: String = settings.internalSipiBaseUrl protected val baseExternalSipiUrl: String = settings.externalSipiBaseUrl @@ -94,7 +94,7 @@ class ITKnoraFakeSpec(_system: ActorSystem) } protected def getResponseString(request: HttpRequest): String = { - val response = singleAwaitingRequest(request) + val response = singleAwaitingRequest(request) val responseBodyStr = Await.result(Unmarshal(response.entity).to[String], 6.seconds) assert(response.status === StatusCodes.OK, s",\n REQUEST: $request,\n RESPONSE: $responseBodyStr") responseBodyStr diff --git a/webapi/src/test/scala/org/knora/webapi/ITKnoraLiveSpec.scala b/webapi/src/test/scala/org/knora/webapi/ITKnoraLiveSpec.scala index f58293fbfa..a816b17267 100644 --- a/webapi/src/test/scala/org/knora/webapi/ITKnoraLiveSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/ITKnoraLiveSpec.scala @@ -75,8 +75,8 @@ class ITKnoraLiveSpec(_system: ActorSystem) this(ActorSystem("IntegrationTests", TestContainersAll.PortConfig.withFallback(ITKnoraLiveSpec.defaultConfig))) /* needed by the core trait (represents the KnoraTestCore trait)*/ - implicit lazy val settings: KnoraSettingsImpl = KnoraSettings(system) - implicit val materializer: Materializer = Materializer.matFromSystem(system) + implicit lazy val settings: KnoraSettingsImpl = KnoraSettings(system) + implicit val materializer: Materializer = Materializer.matFromSystem(system) implicit val executionContext: ExecutionContext = system.dispatchers.lookup(KnoraDispatchers.KnoraActorDispatcher) // can be overridden in individual spec @@ -91,7 +91,7 @@ class ITKnoraLiveSpec(_system: ActorSystem) lazy val appActor: ActorRef = system.actorOf(Props(new ApplicationActor with LiveManagers), name = APPLICATION_MANAGER_ACTOR_NAME) - protected val baseApiUrl: String = settings.internalKnoraApiBaseUrl + protected val baseApiUrl: String = settings.internalKnoraApiBaseUrl protected val baseInternalSipiUrl: String = settings.internalSipiBaseUrl protected val baseExternalSipiUrl: String = settings.externalSipiBaseUrl @@ -122,7 +122,7 @@ class ITKnoraLiveSpec(_system: ActorSystem) protected def checkIfSipiIsRunning(): Unit = { // This requires that (1) fileserver.docroot is set in Sipi's config file and (2) it contains a file test.html. - val request = Get(baseInternalSipiUrl + "/server/test.html") + val request = Get(baseInternalSipiUrl + "/server/test.html") val response = singleAwaitingRequest(request) assert(response.status == StatusCodes.OK, s"Sipi is probably not running: ${response.status}") if (response.status.isSuccess()) logger.info("Sipi is running.") diff --git a/webapi/src/test/scala/org/knora/webapi/IntegrationSpec.scala b/webapi/src/test/scala/org/knora/webapi/IntegrationSpec.scala index 901daaee94..181241b264 100644 --- a/webapi/src/test/scala/org/knora/webapi/IntegrationSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/IntegrationSpec.scala @@ -79,10 +79,10 @@ abstract class IntegrationSpec(_config: Config) implicit val ctx: MessageDispatcher = system.dispatchers.lookup(KnoraDispatchers.KnoraBlockingDispatcher) val checkTriplestore: Task[Unit] = for { checkResult <- ZIO.attemptBlocking { - Await - .result(actorRef ? CheckTriplestoreRequest(), 1.second.asScala) - .asInstanceOf[CheckTriplestoreResponse] - } + Await + .result(actorRef ? CheckTriplestoreRequest(), 1.second.asScala) + .asInstanceOf[CheckTriplestoreResponse] + } value <- if (checkResult.triplestoreStatus == TriplestoreStatus.ServiceAvailable) { @@ -99,8 +99,8 @@ abstract class IntegrationSpec(_config: Config) Runtime.default.unsafeRun( (checkTriplestore .retry(ScheduleUtil.schedule) - .foldZIO(ex => printLine("Exception Failed"), v => printLine(s"Succeeded with $v")) - ).provide(Console.live) + .foldZIO(ex => printLine("Exception Failed"), v => printLine(s"Succeeded with $v"))) + .provide(Console.live) ) } diff --git a/webapi/src/test/scala/org/knora/webapi/ManagersWithMockedSipi.scala b/webapi/src/test/scala/org/knora/webapi/ManagersWithMockedSipi.scala index 007d11afda..45fd21e710 100644 --- a/webapi/src/test/scala/org/knora/webapi/ManagersWithMockedSipi.scala +++ b/webapi/src/test/scala/org/knora/webapi/ManagersWithMockedSipi.scala @@ -19,7 +19,6 @@ import org.knora.webapi.store.cacheservice.CacheServiceManager import zio.Runtime import zio.ZIO - /** * Mixin trait for running the application with mocked Sipi */ diff --git a/webapi/src/test/scala/org/knora/webapi/R2RSpec.scala b/webapi/src/test/scala/org/knora/webapi/R2RSpec.scala index f6e835dfd6..09ab09c5b8 100644 --- a/webapi/src/test/scala/org/knora/webapi/R2RSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/R2RSpec.scala @@ -86,7 +86,7 @@ class R2RSpec // The main application actor forwards messages to the responder manager and the store manager. val responderManager: ActorRef = appActor - val storeManager: ActorRef = appActor + val storeManager: ActorRef = appActor val routeData: KnoraRouteData = KnoraRouteData( system = system, @@ -116,7 +116,7 @@ class R2RSpec protected def responseToJsonLDDocument(httpResponse: HttpResponse): JsonLDDocument = { val responseBodyFuture: Future[String] = httpResponse.entity.toStrict(5.seconds).map(_.data.decodeString("UTF-8")) - val responseBodyStr = Await.result(responseBodyFuture, 5.seconds) + val responseBodyStr = Await.result(responseBodyFuture, 5.seconds) JsonLDUtil.parseJsonLD(responseBodyStr) } diff --git a/webapi/src/test/scala/org/knora/webapi/TestContainerFuseki.scala b/webapi/src/test/scala/org/knora/webapi/TestContainerFuseki.scala index 68cd9aedca..37dfe9ff1c 100644 --- a/webapi/src/test/scala/org/knora/webapi/TestContainerFuseki.scala +++ b/webapi/src/test/scala/org/knora/webapi/TestContainerFuseki.scala @@ -18,7 +18,7 @@ import org.knora.webapi.http.version.BuildInfo object TestContainerFuseki { val FusekiImageName: DockerImageName = DockerImageName.parse(BuildInfo.fuseki) - val FusekiContainer = new GenericContainer(FusekiImageName) + val FusekiContainer = new GenericContainer(FusekiImageName) FusekiContainer.withExposedPorts(3030) FusekiContainer.withEnv("ADMIN_PASSWORD", "test") diff --git a/webapi/src/test/scala/org/knora/webapi/TestContainerRedis.scala b/webapi/src/test/scala/org/knora/webapi/TestContainerRedis.scala index 39b75b73aa..69bfb20a41 100644 --- a/webapi/src/test/scala/org/knora/webapi/TestContainerRedis.scala +++ b/webapi/src/test/scala/org/knora/webapi/TestContainerRedis.scala @@ -17,7 +17,7 @@ import scala.jdk.CollectionConverters._ object TestContainerRedis { val redisImageName: DockerImageName = DockerImageName.parse("redis:5") - val redisContainer = new GenericContainer(redisImageName) + val redisContainer = new GenericContainer(redisImageName) redisContainer.withExposedPorts(6379) redisContainer.start() diff --git a/webapi/src/test/scala/org/knora/webapi/TestContainersAll.scala b/webapi/src/test/scala/org/knora/webapi/TestContainersAll.scala index 4514dc36d8..3bb68b5ddb 100644 --- a/webapi/src/test/scala/org/knora/webapi/TestContainersAll.scala +++ b/webapi/src/test/scala/org/knora/webapi/TestContainersAll.scala @@ -27,14 +27,14 @@ object TestContainersAll { .getOrElse(throw new UnknownHostException("No suitable network interface found")) val FusekiImageName: DockerImageName = DockerImageName.parse(BuildInfo.fuseki) - val FusekiContainer = new GenericContainer(FusekiImageName) + val FusekiContainer = new GenericContainer(FusekiImageName) FusekiContainer.withExposedPorts(3030) FusekiContainer.withEnv("ADMIN_PASSWORD", "test") FusekiContainer.withEnv("JVM_ARGS", "-Xmx3G") FusekiContainer.start() val SipiImageName: DockerImageName = DockerImageName.parse(s"daschswiss/knora-sipi:${BuildInfo.version}") - val SipiContainer = new GenericContainer(SipiImageName) + val SipiContainer = new GenericContainer(SipiImageName) SipiContainer.withExposedPorts(1024) SipiContainer.withEnv("KNORA_WEBAPI_KNORA_API_EXTERNAL_HOST", "0.0.0.0") SipiContainer.withEnv("KNORA_WEBAPI_KNORA_API_EXTERNAL_PORT", "3333") @@ -57,7 +57,7 @@ object TestContainersAll { // Container needs to be started to get the random IP val sipiIp: String = SipiContainer.getHost - val sipiPort: Int = SipiContainer.getFirstMappedPort + val sipiPort: Int = SipiContainer.getFirstMappedPort // The new default is the inmem cache implementation, so no need // for a container @@ -69,8 +69,8 @@ object TestContainersAll { private val portMap = Map( "app.triplestore.fuseki.port" -> FusekiContainer.getFirstMappedPort, - "app.sipi.internal-host" -> sipiIp, - "app.sipi.internal-port" -> sipiPort + "app.sipi.internal-host" -> sipiIp, + "app.sipi.internal-port" -> sipiPort // "app.cache-service.redis.port" -> RedisContainer.getFirstMappedPort ).asJava diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/CORSSupportE2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/CORSSupportE2ESpec.scala index 94f2798a92..e2fe807bb4 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/CORSSupportE2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/CORSSupportE2ESpec.scala @@ -73,7 +73,7 @@ class CORSSupportE2ESpec extends E2ESpec(CORSSupportE2ESpec.config) { } "send `Access-Control-Allow-Origin` header when the api endpoint route is NOT found " in { - val request = Get(baseApiUrl + "/NotFound") ~> Origin(exampleOrigin) + val request = Get(baseApiUrl + "/NotFound") ~> Origin(exampleOrigin) val response = singleAwaitingRequest(request) response.status should equal(StatusCodes.NotFound) response.headers should contain allElementsOf Seq( diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/HealthRouteE2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/HealthRouteE2ESpec.scala index 7d8c40216f..f41ca13a71 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/HealthRouteE2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/HealthRouteE2ESpec.scala @@ -36,9 +36,9 @@ class HealthRouteE2ESpec extends E2ESpec(HealthRouteE2ESpec.config) { "return 'OK' for state 'Running'" in { - val request = Get(baseApiUrl + s"/health") - val response: HttpResponse = singleAwaitingRequest(request) - val responseStr: String = responseToString(response) + val request = Get(baseApiUrl + s"/health") + val response: HttpResponse = singleAwaitingRequest(request) + val responseStr: String = responseToString(response) val responseHeadersStr: String = response.headers.map(_.toString).mkString("\n") response.status should be(StatusCodes.OK) @@ -70,9 +70,9 @@ class HealthRouteE2ESpec extends E2ESpec(HealthRouteE2ESpec.config) { appActor ! SetAppState(AppStates.Stopped) - val request = Get(baseApiUrl + s"/health") + val request = Get(baseApiUrl + s"/health") val response: HttpResponse = singleAwaitingRequest(request) - val responseStr: String = responseToString(response) + val responseStr: String = responseToString(response) logger.debug(response.toString()) @@ -93,9 +93,9 @@ class HealthRouteE2ESpec extends E2ESpec(HealthRouteE2ESpec.config) { "return 'ServiceUnavailable' for state 'MaintenanceMode'" in { appActor ! SetAppState(AppStates.MaintenanceMode) - val request = Get(baseApiUrl + s"/health") + val request = Get(baseApiUrl + s"/health") val response: HttpResponse = singleAwaitingRequest(request) - val responseStr: String = responseToString(response) + val responseStr: String = responseToString(response) logger.debug(response.toString()) diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/InstanceChecker.scala b/webapi/src/test/scala/org/knora/webapi/e2e/InstanceChecker.scala index 3de09733f7..e1325626ff 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/InstanceChecker.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/InstanceChecker.scala @@ -54,7 +54,7 @@ class InstanceChecker(instanceInspector: InstanceInspector) extends LazyLogging */ def check(instanceResponse: String, expectedClassIri: SmartIri, knoraRouteGet: String => String): Unit = { val instanceElement: InstanceElement = instanceInspector.toElement(instanceResponse) - val definitions: Definitions = getDefinitions(classIri = expectedClassIri, knoraRouteGet = knoraRouteGet) + val definitions: Definitions = getDefinitions(classIri = expectedClassIri, knoraRouteGet = knoraRouteGet) // A map of class IRIs to their immediate base classes. val directSubClassOfRelations: Map[SmartIri, Set[SmartIri]] = definitions.classDefs.map { @@ -116,7 +116,7 @@ class InstanceChecker(instanceInspector: InstanceInspector) extends LazyLogging // Check that there are no extra properties. val allowedInstancePropertyNames: Set[String] = propertyIrisToInstancePropertyNames.values.toSet - val extraInstancePropertyNames = instanceElement.propertyObjects.keySet -- allowedInstancePropertyNames + val extraInstancePropertyNames = instanceElement.propertyObjects.keySet -- allowedInstancePropertyNames if (extraInstancePropertyNames.nonEmpty) { throwAndLogAssertionException( @@ -154,7 +154,7 @@ class InstanceChecker(instanceInspector: InstanceInspector) extends LazyLogging OntologyConstants.Xsd.String.toSmartIri } - val objectTypeStr = objectType.toString + val objectTypeStr = objectType.toString val objectTypeIsKnoraDefinedClass: Boolean = isKnoraDefinedClass(objectType) val objectTypeIsKnoraDatatype: Boolean = OntologyConstants.KnoraApiV2Simple.KnoraDatatypes.contains(objectTypeStr) @@ -335,8 +335,8 @@ class InstanceChecker(instanceInspector: InstanceInspector) extends LazyLogging case Some(classDef) => classDef case None => - val urlPath = s"/v2/ontologies/classes/${URLEncoder.encode(classIri.toString, "UTF-8")}" - val classDefStr: String = knoraRouteGet(urlPath) + val urlPath = s"/v2/ontologies/classes/${URLEncoder.encode(classIri.toString, "UTF-8")}" + val classDefStr: String = knoraRouteGet(urlPath) val jsonLDDocument: JsonLDDocument = JsonLDUtil.parseJsonLD(classDefStr) // If Knora returned an error, get the error message and throw an exception. @@ -363,8 +363,8 @@ class InstanceChecker(instanceInspector: InstanceInspector) extends LazyLogging case Some(propertyDef) => propertyDef case None => - val urlPath = s"/v2/ontologies/properties/${URLEncoder.encode(propertyIri.toString, "UTF-8")}" - val propertyDefStr: String = knoraRouteGet(urlPath) + val urlPath = s"/v2/ontologies/properties/${URLEncoder.encode(propertyIri.toString, "UTF-8")}" + val propertyDefStr: String = knoraRouteGet(urlPath) val jsonLDDocument: JsonLDDocument = JsonLDUtil.parseJsonLD(propertyDefStr) // If Knora returned an error, get the error message and throw an exception. @@ -450,7 +450,7 @@ class JsonLDInstanceInspector extends InstanceInspector { Vector(InstanceElement(elementType = OntologyConstants.Xsd.String, literalContent = Some(literalContent))) } else if (jsonLDObject.isDatatypeValue) { // This object represents a JSON-LD datatype value. - val datatype = jsonLDObject.requireString(JsonLDKeywords.TYPE) + val datatype = jsonLDObject.requireString(JsonLDKeywords.TYPE) val literalContent = jsonLDObject.requireString(JsonLDKeywords.VALUE) Vector(InstanceElement(elementType = datatype, literalContent = Some(literalContent))) } else if (jsonLDObject.isIri) { diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/RejectingRouteE2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/RejectingRouteE2ESpec.scala index 19a424f5d2..9089fc8cc5 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/RejectingRouteE2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/RejectingRouteE2ESpec.scala @@ -27,28 +27,28 @@ class RejectingRouteE2ESpec extends E2ESpec(RejectingRouteE2ESpec.config) { "The Rejecting Route" should { "reject the 'v1/test' path" in { - val request = Get(baseApiUrl + s"/v1/testRouteToReject") + val request = Get(baseApiUrl + s"/v1/testRouteToReject") val response: HttpResponse = singleAwaitingRequest(request) response.status should be(StatusCodes.NotFound) } "reject the 'v2/test' path" in { - val request = Get(baseApiUrl + s"/v2/testRouteToReject") + val request = Get(baseApiUrl + s"/v2/testRouteToReject") val response: HttpResponse = singleAwaitingRequest(request) response.status should be(StatusCodes.NotFound) } "not reject the 'admin/groups' path" in { - val request = Get(baseApiUrl + s"/admin/groups") + val request = Get(baseApiUrl + s"/admin/groups") val response: HttpResponse = singleAwaitingRequest(request) response.status should be(StatusCodes.OK) } "not reject the 'admin/projects' path, as it is not listed" in { - val request = Get(baseApiUrl + s"/admin/projects") + val request = Get(baseApiUrl + s"/admin/projects") val response: HttpResponse = singleAwaitingRequest(request) response.status should be(StatusCodes.OK) diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/admin/GroupsADME2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/admin/GroupsADME2ESpec.scala index b63bdc6758..af73bc2496 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/admin/GroupsADME2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/admin/GroupsADME2ESpec.scala @@ -42,9 +42,9 @@ class GroupsADME2ESpec extends E2ESpec(GroupsADME2ESpec.config) with GroupsADMJs private val clientTestDataCollector = new ClientTestDataCollector(settings) private val imagesUser01Email = SharedTestDataADM.imagesUser01.email - private val testPass = SharedTestDataADM.testPass + private val testPass = SharedTestDataADM.testPass - private val groupIri = SharedTestDataADM.imagesReviewerGroup.id + private val groupIri = SharedTestDataADM.imagesReviewerGroup.id private val groupIriEnc = java.net.URLEncoder.encode(groupIri, "utf-8") "The Groups Route ('admin/groups')" when { @@ -152,7 +152,7 @@ class GroupsADME2ESpec extends E2ESpec(GroupsADME2ESpec.config) with GroupsADMJs response.status should be(StatusCodes.BadRequest) val errorMessage: String = Await.result(Unmarshal(response.entity).to[String], 1.second) - val invalidIri: Boolean = errorMessage.contains(s"IRI: '$customGroupIri' already exists, try another one.") + val invalidIri: Boolean = errorMessage.contains(s"IRI: '$customGroupIri' already exists, try another one.") invalidIri should be(true) } } diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/admin/PermissionsADME2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/admin/PermissionsADME2ESpec.scala index 7b1caf2d4d..41c9d4e1ee 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/admin/PermissionsADME2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/admin/PermissionsADME2ESpec.scala @@ -37,13 +37,13 @@ class PermissionsADME2ESpec extends E2ESpec(PermissionsADME2ESpec.config) with T // Collects client test data private val clientTestDataCollector = new ClientTestDataCollector(settings) - private val customDOAPIri = "http://rdfh.ch/permissions/00FF/zTOK3HlWTLGgTO8ZWVnotg" + private val customDOAPIri = "http://rdfh.ch/permissions/00FF/zTOK3HlWTLGgTO8ZWVnotg" "The Permissions Route ('admin/permissions')" when { "getting permissions" should { "return a group's administrative permission" in { val projectIri = java.net.URLEncoder.encode(SharedTestDataV1.imagesProjectInfo.id, "utf-8") - val groupIri = java.net.URLEncoder.encode(OntologyConstants.KnoraAdmin.ProjectMember, "utf-8") + val groupIri = java.net.URLEncoder.encode(OntologyConstants.KnoraAdmin.ProjectMember, "utf-8") val request = Get(baseApiUrl + s"/admin/permissions/ap/$projectIri/$groupIri") ~> addCredentials( BasicHttpCredentials(SharedTestDataADM.rootUser.email, SharedTestDataADM.testPass) ) @@ -423,9 +423,9 @@ class PermissionsADME2ESpec extends E2ESpec(PermissionsADME2ESpec.config) with T "updating permissions" should { "change the group of an administrative permission" in { - val permissionIri = "http://rdfh.ch/permissions/00FF/a2" + val permissionIri = "http://rdfh.ch/permissions/00FF/a2" val encodedPermissionIri = java.net.URLEncoder.encode(permissionIri, "utf-8") - val newGroupIri = "http://rdfh.ch/groups/00FF/images-reviewer" + val newGroupIri = "http://rdfh.ch/groups/00FF/images-reviewer" val updatePermissionGroup = s"""{ | "forGroup": "$newGroupIri" @@ -465,9 +465,9 @@ class PermissionsADME2ESpec extends E2ESpec(PermissionsADME2ESpec.config) with T } "change the group of a default object access permission" in { - val permissionIri = "http://rdfh.ch/permissions/0803/003-d2" + val permissionIri = "http://rdfh.ch/permissions/0803/003-d2" val encodedPermissionIri = java.net.URLEncoder.encode(permissionIri, "utf-8") - val newGroupIri = "http://rdfh.ch/groups/00FF/images-reviewer" + val newGroupIri = "http://rdfh.ch/groups/00FF/images-reviewer" val updatePermissionGroup = s"""{ | "forGroup": "$newGroupIri" @@ -508,7 +508,7 @@ class PermissionsADME2ESpec extends E2ESpec(PermissionsADME2ESpec.config) with T } "change the set of hasPermissions of an administrative permission" in { - val permissionIri = "http://rdfh.ch/permissions/00FF/a2" + val permissionIri = "http://rdfh.ch/permissions/00FF/a2" val encodedPermissionIri = java.net.URLEncoder.encode(permissionIri, "utf-8") val updateHasPermissions = s"""{ @@ -553,7 +553,7 @@ class PermissionsADME2ESpec extends E2ESpec(PermissionsADME2ESpec.config) with T } "change the set of hasPermissions of a default object access permission" in { - val permissionIri = "http://rdfh.ch/permissions/0803/003-d1" + val permissionIri = "http://rdfh.ch/permissions/0803/003-d1" val encodedPermissionIri = java.net.URLEncoder.encode(permissionIri, "utf-8") val updateHasPermissions = s"""{ @@ -604,9 +604,9 @@ class PermissionsADME2ESpec extends E2ESpec(PermissionsADME2ESpec.config) with T } "change the resource class of a default object access permission" in { - val permissionIri = "http://rdfh.ch/permissions/0803/003-d1" + val permissionIri = "http://rdfh.ch/permissions/0803/003-d1" val encodedPermissionIri = java.net.URLEncoder.encode(permissionIri, "utf-8") - val resourceClassIri = SharedOntologyTestDataADM.INCUNABULA_BOOK_RESOURCE_CLASS + val resourceClassIri = SharedOntologyTestDataADM.INCUNABULA_BOOK_RESOURCE_CLASS val updateResourceClass = s"""{ | "forResourceClass":"$resourceClassIri" @@ -650,9 +650,9 @@ class PermissionsADME2ESpec extends E2ESpec(PermissionsADME2ESpec.config) with T } "change the property of a default object access permission" in { - val permissionIri = "http://rdfh.ch/permissions/00FF/d1" + val permissionIri = "http://rdfh.ch/permissions/00FF/d1" val encodedPermissionIri = java.net.URLEncoder.encode(permissionIri, "utf-8") - val propertyClassIri = SharedOntologyTestDataADM.IMAGES_TITEL_PROPERTY + val propertyClassIri = SharedOntologyTestDataADM.IMAGES_TITEL_PROPERTY val updateResourceClass = s"""{ | "forProperty":"$propertyClassIri" @@ -695,7 +695,7 @@ class PermissionsADME2ESpec extends E2ESpec(PermissionsADME2ESpec.config) with T "delete request" should { "erase a defaultObjectAccess permission" in { - val permissionIri = customDOAPIri + val permissionIri = customDOAPIri val encodedPermissionIri = java.net.URLEncoder.encode(permissionIri, "utf-8") val request = Delete(baseApiUrl + s"/admin/permissions/" + encodedPermissionIri) ~> addCredentials( BasicHttpCredentials(SharedTestDataADM.rootUser.email, SharedTestDataADM.testPass) @@ -716,7 +716,7 @@ class PermissionsADME2ESpec extends E2ESpec(PermissionsADME2ESpec.config) with T ) } "erase an administrative permission" in { - val permissionIri = "http://rdfh.ch/permissions/00FF/a2" + val permissionIri = "http://rdfh.ch/permissions/00FF/a2" val encodedPermissionIri = java.net.URLEncoder.encode(permissionIri, "utf-8") val request = Delete(baseApiUrl + s"/admin/permissions/" + encodedPermissionIri) ~> addCredentials( BasicHttpCredentials(SharedTestDataADM.rootUser.email, SharedTestDataADM.testPass) diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/admin/ProjectsADME2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/admin/ProjectsADME2ESpec.scala index 9eb18f9e1c..4071862afe 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/admin/ProjectsADME2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/admin/ProjectsADME2ESpec.scala @@ -46,10 +46,10 @@ class ProjectsADME2ESpec private implicit def default(implicit system: ActorSystem): RouteTestTimeout = RouteTestTimeout(30.seconds) - private val rootEmail = SharedTestDataADM.rootUser.email - private val testPass = SharedTestDataADM.testPass - private val projectIri = SharedTestDataADM.imagesProject.id - private val projectIriEnc = URLEncoder.encode(projectIri, "utf-8") + private val rootEmail = SharedTestDataADM.rootUser.email + private val testPass = SharedTestDataADM.testPass + private val projectIri = SharedTestDataADM.imagesProject.id + private val projectIriEnc = URLEncoder.encode(projectIri, "utf-8") private val projectShortname = SharedTestDataADM.imagesProject.shortname private val projectShortcode = SharedTestDataADM.imagesProject.shortcode @@ -66,7 +66,7 @@ class ProjectsADME2ESpec "The Projects Route ('admin/projects')" when { "used to query for project information" should { "return all projects" in { - val request = Get(baseApiUrl + s"/admin/projects") ~> addCredentials(BasicHttpCredentials(rootEmail, testPass)) + val request = Get(baseApiUrl + s"/admin/projects") ~> addCredentials(BasicHttpCredentials(rootEmail, testPass)) val response: HttpResponse = singleAwaitingRequest(request) // log.debug(s"response: {}", response) assert(response.status === StatusCodes.OK) @@ -764,9 +764,9 @@ class ProjectsADME2ESpec val response: HttpResponse = singleAwaitingRequest(request) assert(response.status === StatusCodes.OK) val trigStrFuture: Future[String] = Unmarshal(response.entity).to[String] - val trigStr: String = Await.result(trigStrFuture, Timeout(5.seconds).duration) - val parsedTrig: RdfModel = parseTrig(trigStr) - val contextIris: Set[IRI] = parsedTrig.getContexts + val trigStr: String = Await.result(trigStrFuture, Timeout(5.seconds).duration) + val parsedTrig: RdfModel = parseTrig(trigStr) + val contextIris: Set[IRI] = parsedTrig.getContexts assert( contextIris == Set( diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/admin/SipiADME2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/admin/SipiADME2ESpec.scala index a1ba088358..d93c4c6d74 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/admin/SipiADME2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/admin/SipiADME2ESpec.scala @@ -38,11 +38,11 @@ class SipiADME2ESpec extends E2ESpec(SipiADME2ESpec.config) with SessionJsonProt private implicit def default(implicit system: ActorSystem) = RouteTestTimeout(30.seconds) - private val anythingAdminEmail = SharedTestDataV1.anythingAdminUser.userData.email.get + private val anythingAdminEmail = SharedTestDataV1.anythingAdminUser.userData.email.get private val anythingAdminEmailEnc = java.net.URLEncoder.encode(anythingAdminEmail, "utf-8") - private val normalUserEmail = SharedTestDataV1.normalUser.userData.email.get - private val normalUserEmailEnc = java.net.URLEncoder.encode(normalUserEmail, "utf-8") - private val testPass = java.net.URLEncoder.encode("test", "utf-8") + private val normalUserEmail = SharedTestDataV1.normalUser.userData.email.get + private val normalUserEmailEnc = java.net.URLEncoder.encode(normalUserEmail, "utf-8") + private val testPass = java.net.URLEncoder.encode("test", "utf-8") override lazy val rdfDataObjects = List( RdfDataObject(path = "test_data/all_data/anything-data.ttl", name = "http://www.knora.org/data/0001/anything") @@ -50,7 +50,7 @@ class SipiADME2ESpec extends E2ESpec(SipiADME2ESpec.config) with SessionJsonProt def sessionLogin(email: String, password: String): String = { - val request = Get(baseApiUrl + s"/v1/session?login&email=$email&password=$password") + val request = Get(baseApiUrl + s"/v1/session?login&email=$email&password=$password") val response: HttpResponse = singleAwaitingRequest(request) assert(response.status == StatusCodes.OK) diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/admin/UsersADME2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/admin/UsersADME2ESpec.scala index 44e4981c67..ccdb580f1b 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/admin/UsersADME2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/admin/UsersADME2ESpec.scala @@ -64,22 +64,22 @@ class UsersADME2ESpec "test" ) - private val normalUserIri = SharedTestDataV1.normalUser.userData.user_id.get + private val normalUserIri = SharedTestDataV1.normalUser.userData.user_id.get private val normalUserIriEnc = java.net.URLEncoder.encode(normalUserIri, "utf-8") - private val multiUserIri = SharedTestDataV1.multiuserUser.userData.user_id.get + private val multiUserIri = SharedTestDataV1.multiuserUser.userData.user_id.get private val multiUserIriEnc = java.net.URLEncoder.encode(multiUserIri, "utf-8") - private val imagesProjectIri = SharedTestDataADM.imagesProject.id + private val imagesProjectIri = SharedTestDataADM.imagesProject.id private val imagesProjectIriEnc = java.net.URLEncoder.encode(imagesProjectIri, "utf-8") - private val imagesReviewerGroupIri = SharedTestDataADM.imagesReviewerGroup.id + private val imagesReviewerGroupIri = SharedTestDataADM.imagesReviewerGroup.id private val imagesReviewerGroupIriEnc = java.net.URLEncoder.encode(imagesReviewerGroupIri, "utf-8") - private val customUserIri = "http://rdfh.ch/users/14pxW-LAQIaGcCRiNCPJcQ" + private val customUserIri = "http://rdfh.ch/users/14pxW-LAQIaGcCRiNCPJcQ" private val otherCustomUserIri = "http://rdfh.ch/users/v8_12VcJRlGNFCjYzqJ5cA" - private val donaldIri = new MutableTestIri + private val donaldIri = new MutableTestIri private val systemUserIriEncoded = java.net.URLEncoder.encode(KnoraSystemInstances.Users.SystemUser.id, "utf-8") // Directory path for generated client test data @@ -257,7 +257,7 @@ class UsersADME2ESpec } "return only public information for single user with anonymous access" in { - val request = Get(baseApiUrl + s"/admin/users/iri/$normalUserIriEnc") + val request = Get(baseApiUrl + s"/admin/users/iri/$normalUserIriEnc") val response: HttpResponse = singleAwaitingRequest(request) response.status should be(StatusCodes.OK) val result: UserADM = AkkaHttpUtils.httpResponseToJson(response).fields("user").convertTo[UserADM] @@ -387,7 +387,7 @@ class UsersADME2ESpec | "systemAdmin": false |}""".stripMargin - val request = Post(baseApiUrl + s"/admin/users", HttpEntity(ContentTypes.`application/json`, params)) + val request = Post(baseApiUrl + s"/admin/users", HttpEntity(ContentTypes.`application/json`, params)) val response: HttpResponse = singleAwaitingRequest(request) response.status should be(StatusCodes.BadRequest) @@ -493,7 +493,7 @@ class UsersADME2ESpec text = createUserRequest ) ) - val request = Post(baseApiUrl + s"/admin/users", HttpEntity(ContentTypes.`application/json`, createUserRequest)) + val request = Post(baseApiUrl + s"/admin/users", HttpEntity(ContentTypes.`application/json`, createUserRequest)) val response: HttpResponse = singleAwaitingRequest(request) response.status should be(StatusCodes.OK) @@ -543,7 +543,7 @@ class UsersADME2ESpec text = createUserRequest ) ) - val request = Post(baseApiUrl + s"/admin/users", HttpEntity(ContentTypes.`application/json`, createUserRequest)) + val request = Post(baseApiUrl + s"/admin/users", HttpEntity(ContentTypes.`application/json`, createUserRequest)) val response: HttpResponse = singleAwaitingRequest(request) response.status should be(StatusCodes.BadRequest) @@ -583,7 +583,7 @@ class UsersADME2ESpec text = createUserRequest ) ) - val request = Post(baseApiUrl + s"/admin/users", HttpEntity(ContentTypes.`application/json`, createUserRequest)) + val request = Post(baseApiUrl + s"/admin/users", HttpEntity(ContentTypes.`application/json`, createUserRequest)) val response: HttpResponse = singleAwaitingRequest(request) response.status should be(StatusCodes.BadRequest) @@ -618,7 +618,7 @@ class UsersADME2ESpec } """.stripMargin - val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) + val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) val response: HttpResponse = singleAwaitingRequest(request) response.status should be(StatusCodes.OK) diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/admin/lists/DeleteListItemsRouteADME2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/admin/lists/DeleteListItemsRouteADME2ESpec.scala index 63544c0091..3381dc48b8 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/admin/lists/DeleteListItemsRouteADME2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/admin/lists/DeleteListItemsRouteADME2ESpec.scala @@ -70,7 +70,7 @@ class DeleteListItemsRouteADME2ESpec "test" ) - private val treeListInfo: ListRootNodeInfoADM = SharedListsTestDataADM.treeListInfo + private val treeListInfo: ListRootNodeInfoADM = SharedListsTestDataADM.treeListInfo private val treeListNodes: Seq[ListChildNodeADM] = SharedListsTestDataADM.treeListChildNodes "The List Items Route (/admin/lists)" when { @@ -107,7 +107,7 @@ class DeleteListItemsRouteADME2ESpec ) val response: HttpResponse = singleAwaitingRequest(request) response.status should be(StatusCodes.OK) - val node = AkkaHttpUtils.httpResponseToJson(response).fields("node").convertTo[ListNodeADM] + val node = AkkaHttpUtils.httpResponseToJson(response).fields("node").convertTo[ListNodeADM] val children = node.getChildren children.size should be(2) // last child must be shifted one place to left @@ -171,7 +171,7 @@ class DeleteListItemsRouteADME2ESpec "Candeletelist route (/admin/lists/candelete)" when { "used to query if list can be deleted" should { "return TRUE for unused list" in { - val unusedList = "http://rdfh.ch/lists/0001/notUsedList" + val unusedList = "http://rdfh.ch/lists/0001/notUsedList" val unusedListEncoded = java.net.URLEncoder.encode(unusedList, "utf-8") val request = Get(baseApiUrl + s"/admin/lists/candelete/" + unusedListEncoded) ~> addCredentials( BasicHttpCredentials(rootCreds.email, rootCreds.password) @@ -187,7 +187,7 @@ class DeleteListItemsRouteADME2ESpec } "return FALSE for used list" in { - val usedList = "http://rdfh.ch/lists/0001/treeList01" + val usedList = "http://rdfh.ch/lists/0001/treeList01" val usedListEncoded = java.net.URLEncoder.encode(usedList, "utf-8") val request = Get(baseApiUrl + s"/admin/lists/candelete/" + usedListEncoded) ~> addCredentials( BasicHttpCredentials(rootCreds.email, rootCreds.password) @@ -203,7 +203,7 @@ class DeleteListItemsRouteADME2ESpec } "return exception for bad list iri" in { - val badlistIri = "bad list Iri" + val badlistIri = "bad list Iri" val badListIriEncoded = java.net.URLEncoder.encode(badlistIri, "utf-8") val request = Get(baseApiUrl + s"/admin/lists/candelete/" + badListIriEncoded) ~> addCredentials( BasicHttpCredentials(rootCreds.email, rootCreds.password) diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/admin/lists/OldListsRouteADMFeatureE2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/admin/lists/OldListsRouteADMFeatureE2ESpec.scala index bfad70b522..393b728882 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/admin/lists/OldListsRouteADMFeatureE2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/admin/lists/OldListsRouteADMFeatureE2ESpec.scala @@ -72,9 +72,9 @@ class OldListsRouteADMFeatureE2ESpec "test" ) - private val treeListInfo: ListRootNodeInfoADM = SharedListsTestDataADM.treeListInfo + private val treeListInfo: ListRootNodeInfoADM = SharedListsTestDataADM.treeListInfo private val treeListNodes: Seq[ListChildNodeADM] = SharedListsTestDataADM.treeListChildNodes - private val customChildNodeIRI = "http://rdfh.ch/lists/0001/vQgijJZKSqawFooJPyhYkw" + private val customChildNodeIRI = "http://rdfh.ch/lists/0001/vQgijJZKSqawFooJPyhYkw" def addChildListNodeRequest(parentNodeIri: IRI, name: String, label: String, comment: String): String = s"""{ | "parentNodeIri": "$parentNodeIri", @@ -431,10 +431,10 @@ class OldListsRouteADMFeatureE2ESpec } "used to modify list information" should { - val newListIri = new MutableTestIri - val firstChildIri = new MutableTestIri + val newListIri = new MutableTestIri + val firstChildIri = new MutableTestIri val secondChildIri = new MutableTestIri - val thirdChildIri = new MutableTestIri + val thirdChildIri = new MutableTestIri "create a list" in { val createListRequest: String = @@ -521,7 +521,7 @@ class OldListsRouteADMFeatureE2ESpec |} """.stripMargin - val request01 = Post(baseApiUrl + s"/admin/lists", HttpEntity(ContentTypes.`application/json`, params01)) + val request01 = Post(baseApiUrl + s"/admin/lists", HttpEntity(ContentTypes.`application/json`, params01)) val response01: HttpResponse = singleAwaitingRequest(request01) // println(s"response: ${response01.toString}") response01.status should be(StatusCodes.BadRequest) @@ -536,7 +536,7 @@ class OldListsRouteADMFeatureE2ESpec |} """.stripMargin - val request02 = Post(baseApiUrl + s"/admin/lists", HttpEntity(ContentTypes.`application/json`, params02)) + val request02 = Post(baseApiUrl + s"/admin/lists", HttpEntity(ContentTypes.`application/json`, params02)) val response02: HttpResponse = singleAwaitingRequest(request02) // println(s"response: ${response02.toString}") response02.status should be(StatusCodes.BadRequest) @@ -551,7 +551,7 @@ class OldListsRouteADMFeatureE2ESpec |} """.stripMargin - val request03 = Post(baseApiUrl + s"/admin/lists", HttpEntity(ContentTypes.`application/json`, params03)) + val request03 = Post(baseApiUrl + s"/admin/lists", HttpEntity(ContentTypes.`application/json`, params03)) val response03: HttpResponse = singleAwaitingRequest(request03) // println(s"response: ${response03.toString}") response03.status should be(StatusCodes.BadRequest) @@ -804,8 +804,8 @@ class OldListsRouteADMFeatureE2ESpec "add child to list - to the root node" in { val encodedListUrl = java.net.URLEncoder.encode(newListIri.get, "utf-8") - val name = "first" - val label = "New First Child List Node Value" + val name = "first" + val label = "New First Child List Node Value" val comment = "New First Child List Node Comment" val addChildToRoot = addChildListNodeRequest( @@ -876,8 +876,8 @@ class OldListsRouteADMFeatureE2ESpec "add second child to list - to the root node" in { val encodedListUrl = java.net.URLEncoder.encode(newListIri.get, "utf-8") - val name = "second" - val label = "New Second Child List Node Value" + val name = "second" + val label = "New Second Child List Node Value" val comment = "New Second Child List Node Comment" val addSecondChildToRoot = addChildListNodeRequest( @@ -948,8 +948,8 @@ class OldListsRouteADMFeatureE2ESpec "insert new child in a specific position" in { val encodedListUrl = java.net.URLEncoder.encode(newListIri.get, "utf-8") - val name = "child with position" - val label = "Inserted List Node Label" + val name = "child with position" + val label = "Inserted List Node Label" val comment = "Inserted List Node Comment" val insertChild = @@ -1024,8 +1024,8 @@ class OldListsRouteADMFeatureE2ESpec "add child to second child node" in { val encodedListUrl = java.net.URLEncoder.encode(secondChildIri.get, "utf-8") - val name = "third" - val label = "New Third Child List Node Value" + val name = "third" + val label = "New Third Child List Node Value" val comment = "New Third Child List Node Comment" val addChildToSecondChild = addChildListNodeRequest( diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/admin/lists/UpdateListItemsRouteADME2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/admin/lists/UpdateListItemsRouteADME2ESpec.scala index 5bb4bb075e..d681f665f1 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/admin/lists/UpdateListItemsRouteADME2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/admin/lists/UpdateListItemsRouteADME2ESpec.scala @@ -69,9 +69,9 @@ class UpdateListItemsRouteADME2ESpec "test" ) - private val treeListInfo: ListRootNodeInfoADM = SharedListsTestDataADM.treeListInfo + private val treeListInfo: ListRootNodeInfoADM = SharedListsTestDataADM.treeListInfo private val treeListNodes: Seq[ListChildNodeADM] = SharedListsTestDataADM.treeListChildNodes - private val treeChildNode = treeListNodes.head + private val treeChildNode = treeListNodes.head "The List Items Route (/admin/lists)" when { "update list root" should { @@ -389,9 +389,9 @@ class UpdateListItemsRouteADME2ESpec } "not update the position of a node if given IRI is invalid" in { - val parentIri = "http://rdfh.ch/lists/0001/notUsedList01" + val parentIri = "http://rdfh.ch/lists/0001/notUsedList01" val newPosition = 1 - val nodeIri = "invalid-iri" + val nodeIri = "invalid-iri" val updateNodeName = s"""{ | "parentNodeIri": "$parentIri", @@ -410,9 +410,9 @@ class UpdateListItemsRouteADME2ESpec } "update only the position of the child node within same parent" in { - val parentIri = "http://rdfh.ch/lists/0001/notUsedList01" + val parentIri = "http://rdfh.ch/lists/0001/notUsedList01" val newPosition = 1 - val nodeIri = "http://rdfh.ch/lists/0001/notUsedList014" + val nodeIri = "http://rdfh.ch/lists/0001/notUsedList014" val updateNodeName = s"""{ | "parentNodeIri": "$parentIri", @@ -456,9 +456,9 @@ class UpdateListItemsRouteADME2ESpec } "reposition child node to the end of its parent's children" in { - val parentIri = "http://rdfh.ch/lists/0001/notUsedList01" + val parentIri = "http://rdfh.ch/lists/0001/notUsedList01" val newPosition = -1 - val nodeIri = "http://rdfh.ch/lists/0001/notUsedList012" + val nodeIri = "http://rdfh.ch/lists/0001/notUsedList012" val updateNodeName = s"""{ | "parentNodeIri": "$parentIri", @@ -502,9 +502,9 @@ class UpdateListItemsRouteADME2ESpec } "update parent and position of the child node" in { - val parentIri = "http://rdfh.ch/lists/0001/notUsedList" + val parentIri = "http://rdfh.ch/lists/0001/notUsedList" val newPosition = 2 - val nodeIri = "http://rdfh.ch/lists/0001/notUsedList015" + val nodeIri = "http://rdfh.ch/lists/0001/notUsedList015" val updateNodeName = s"""{ | "parentNodeIri": "$parentIri", @@ -548,9 +548,9 @@ class UpdateListItemsRouteADME2ESpec } "reposition child node to end of another parent's children" in { - val parentIri = "http://rdfh.ch/lists/0001/notUsedList" + val parentIri = "http://rdfh.ch/lists/0001/notUsedList" val newPosition = -1 - val nodeIri = "http://rdfh.ch/lists/0001/notUsedList015" + val nodeIri = "http://rdfh.ch/lists/0001/notUsedList015" val updateNodeName = s"""{ | "parentNodeIri": "$parentIri", diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/http/ServerVersionE2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/http/ServerVersionE2ESpec.scala index 670652d58c..ffd10b8a9a 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/http/ServerVersionE2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/http/ServerVersionE2ESpec.scala @@ -27,7 +27,7 @@ class ServerVersionE2ESpec extends E2ESpec(ServerVersionE2ESpec.config) { "The Server" should { "return the custom 'Server' header with every response" in { - val request = Get(baseApiUrl + s"/admin/projects") + val request = Get(baseApiUrl + s"/admin/projects") val response: HttpResponse = singleAwaitingRequest(request) response.headers should contain(ServerVersion.serverVersionHeader) response.headers.find(_.name == "Server") match { diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v1/AuthenticationV1E2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v1/AuthenticationV1E2ESpec.scala index 6e3957d47d..16b5478619 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v1/AuthenticationV1E2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v1/AuthenticationV1E2ESpec.scala @@ -39,22 +39,22 @@ class AuthenticationV1E2ESpec private implicit def default(implicit system: ActorSystem) = RouteTestTimeout(30.seconds) - private val rootIri = SharedTestDataV1.rootUser.userData.user_id.get - private val rootIriEnc = java.net.URLEncoder.encode(rootIri, "utf-8") - private val rootEmail = SharedTestDataV1.rootUser.userData.email.get + private val rootIri = SharedTestDataV1.rootUser.userData.user_id.get + private val rootIriEnc = java.net.URLEncoder.encode(rootIri, "utf-8") + private val rootEmail = SharedTestDataV1.rootUser.userData.email.get private val rootEmailEnc = java.net.URLEncoder.encode(rootEmail, "utf-8") private val inactiveUserEmailEnc = java.net.URLEncoder.encode(SharedTestDataV1.inactiveUser.userData.email.get, "utf-8") - private val wrongEmail = "wrong@example.com" + private val wrongEmail = "wrong@example.com" private val wrongEmailEnc = java.net.URLEncoder.encode(wrongEmail, "utf-8") - private val testPass = java.net.URLEncoder.encode("test", "utf-8") - private val wrongPass = java.net.URLEncoder.encode("wrong", "utf-8") + private val testPass = java.net.URLEncoder.encode("test", "utf-8") + private val wrongPass = java.net.URLEncoder.encode("wrong", "utf-8") "The Authentication Route ('v1/authenticate') with credentials supplied via URL parameters" should { "succeed authentication with correct email and correct password" in { /* Correct username and password */ - val request = Get(baseApiUrl + s"/v1/authenticate?email=$rootEmailEnc&password=$testPass") + val request = Get(baseApiUrl + s"/v1/authenticate?email=$rootEmailEnc&password=$testPass") val response: HttpResponse = singleAwaitingRequest(request) logger.debug(s"response: ${response.toString}") assert(response.status === StatusCodes.OK) @@ -62,14 +62,14 @@ class AuthenticationV1E2ESpec "fail authentication with correct email and wrong password" in { /* Correct email / wrong password */ - val request = Get(baseApiUrl + s"/v1/authenticate?email=$rootEmail&password=$wrongPass") + val request = Get(baseApiUrl + s"/v1/authenticate?email=$rootEmail&password=$wrongPass") val response: HttpResponse = singleAwaitingRequest(request) logger.debug(s"response: ${response.toString}") assert(response.status === StatusCodes.Unauthorized) } "fail authentication if the user is set as 'not active' " in { /* User not active */ - val request = Get(baseApiUrl + s"/v1/authenticate?email=$inactiveUserEmailEnc&password=$testPass") + val request = Get(baseApiUrl + s"/v1/authenticate?email=$inactiveUserEmailEnc&password=$testPass") val response: HttpResponse = singleAwaitingRequest(request) logger.debug(s"response: ${response.toString}") assert(response.status === StatusCodes.Unauthorized) @@ -80,14 +80,14 @@ class AuthenticationV1E2ESpec "succeed authentication with correct email and correct password" in { /* Correct email / correct password */ - val request = Get(baseApiUrl + "/v1/authenticate") ~> addCredentials(BasicHttpCredentials(rootEmail, testPass)) + val request = Get(baseApiUrl + "/v1/authenticate") ~> addCredentials(BasicHttpCredentials(rootEmail, testPass)) val response = singleAwaitingRequest(request) assert(response.status == StatusCodes.OK) } "fail authentication with correct email and wrong password" in { /* Correct username / wrong password */ - val request = Get(baseApiUrl + "/v1/authenticate") ~> addCredentials(BasicHttpCredentials(rootEmail, wrongPass)) + val request = Get(baseApiUrl + "/v1/authenticate") ~> addCredentials(BasicHttpCredentials(rootEmail, wrongPass)) val response = singleAwaitingRequest(request) assert(response.status == StatusCodes.Unauthorized) } @@ -97,7 +97,7 @@ class AuthenticationV1E2ESpec var sid = "" "succeed 'login' with correct email and correct password" in { /* Correct username and correct password */ - val request = Get(baseApiUrl + s"/v1/session?login&email=$rootEmailEnc&password=$testPass") + val request = Get(baseApiUrl + s"/v1/session?login&email=$rootEmailEnc&password=$testPass") val response: HttpResponse = singleAwaitingRequest(request) assert(response.status == StatusCodes.OK) @@ -127,7 +127,7 @@ class AuthenticationV1E2ESpec } "not return sensitive information (token, password) in the response when checking session" in { - val request = Get(baseApiUrl + s"/v1/session") ~> Cookie(KNORA_AUTHENTICATION_COOKIE_NAME, value = sid) + val request = Get(baseApiUrl + s"/v1/session") ~> Cookie(KNORA_AUTHENTICATION_COOKIE_NAME, value = sid) val response = singleAwaitingRequest(request) assert(response.status === StatusCodes.OK) @@ -140,7 +140,7 @@ class AuthenticationV1E2ESpec "succeed authentication with correct session id in cookie" in { // authenticate by calling '/v1/session' without parameters but by providing session id in cookie from earlier login - val request = Get(baseApiUrl + "/v1/session") ~> Cookie(KNORA_AUTHENTICATION_COOKIE_NAME, sid) + val request = Get(baseApiUrl + "/v1/session") ~> Cookie(KNORA_AUTHENTICATION_COOKIE_NAME, sid) val response = singleAwaitingRequest(request) //log.debug("==>> " + responseAs[String]) assert(response.status === StatusCodes.OK) @@ -149,7 +149,7 @@ class AuthenticationV1E2ESpec "succeed 'logout' with provided session cookie" in { // do logout with stored session id - val request = Get(baseApiUrl + "/v1/session?logout") ~> Cookie(KNORA_AUTHENTICATION_COOKIE_NAME, sid) + val request = Get(baseApiUrl + "/v1/session?logout") ~> Cookie(KNORA_AUTHENTICATION_COOKIE_NAME, sid) val response = singleAwaitingRequest(request) //log.debug("==>> " + responseAs[String]) assert(response.status === StatusCodes.OK) @@ -171,7 +171,7 @@ class AuthenticationV1E2ESpec } "fail authentication with provided session cookie after logout" in { - val request = Get(baseApiUrl + "/v1/session") ~> Cookie(KNORA_AUTHENTICATION_COOKIE_NAME, sid) + val request = Get(baseApiUrl + "/v1/session") ~> Cookie(KNORA_AUTHENTICATION_COOKIE_NAME, sid) val response = singleAwaitingRequest(request) //log.debug("==>> " + responseAs[String]) assert(response.status === StatusCodes.Unauthorized) @@ -179,7 +179,7 @@ class AuthenticationV1E2ESpec "fail 'login' with correct email and wrong password" in { /* Correct username and wrong password */ - val request = Get(baseApiUrl + s"/v1/session?login&email=$rootEmailEnc&password=$wrongPass") + val request = Get(baseApiUrl + s"/v1/session?login&email=$rootEmailEnc&password=$wrongPass") val response = singleAwaitingRequest(request) //log.debug("==>> " + responseAs[String]) assert(response.status === StatusCodes.Unauthorized) @@ -187,14 +187,14 @@ class AuthenticationV1E2ESpec "fail 'login' with wrong username" in { /* wrong username */ - val request = Get(baseApiUrl + s"/v1/session?login&email=$wrongEmailEnc&password=$testPass") + val request = Get(baseApiUrl + s"/v1/session?login&email=$wrongEmailEnc&password=$testPass") val response = singleAwaitingRequest(request) //log.debug("==>> " + responseAs[String]) assert(response.status === StatusCodes.Unauthorized) } "fail authentication with wrong session id in cookie" in { - val request = Get(baseApiUrl + "/v1/session") ~> Cookie(KNORA_AUTHENTICATION_COOKIE_NAME, "123456") + val request = Get(baseApiUrl + "/v1/session") ~> Cookie(KNORA_AUTHENTICATION_COOKIE_NAME, "123456") val response = singleAwaitingRequest(request) //log.debug("==>> " + responseAs[String]) assert(response.status === StatusCodes.Unauthorized) @@ -205,7 +205,7 @@ class AuthenticationV1E2ESpec var sid = "" "succeed 'login' with correct email and correct password" in { /* Correct username and correct password */ - val request = Get(baseApiUrl + "/v1/session?login") ~> addCredentials(BasicHttpCredentials(rootEmail, testPass)) + val request = Get(baseApiUrl + "/v1/session?login") ~> addCredentials(BasicHttpCredentials(rootEmail, testPass)) val response = singleAwaitingRequest(request) //log.debug("==>> " + responseAs[String]) assert(response.status === StatusCodes.OK) @@ -234,7 +234,7 @@ class AuthenticationV1E2ESpec } "not return sensitive information (token, password) in the response when checking session" in { - val request = Get(baseApiUrl + s"/v1/session") ~> Cookie(KNORA_AUTHENTICATION_COOKIE_NAME, sid) + val request = Get(baseApiUrl + s"/v1/session") ~> Cookie(KNORA_AUTHENTICATION_COOKIE_NAME, sid) val response = singleAwaitingRequest(request) assert(response.status === StatusCodes.OK) @@ -247,7 +247,7 @@ class AuthenticationV1E2ESpec "fail 'login' with correct email and wrong password " in { /* Correct username and wrong password */ - val request = Get(baseApiUrl + "/v1/session?login") ~> addCredentials(BasicHttpCredentials(rootEmail, wrongPass)) + val request = Get(baseApiUrl + "/v1/session?login") ~> addCredentials(BasicHttpCredentials(rootEmail, wrongPass)) val response = singleAwaitingRequest(request) //log.debug("==>> " + responseAs[String]) assert(response.status === StatusCodes.Unauthorized) @@ -255,7 +255,7 @@ class AuthenticationV1E2ESpec "fail 'login' with wrong email " in { /* wrong username */ - val request = Get(baseApiUrl + "/v1/session?login") ~> addCredentials(BasicHttpCredentials(wrongEmail, testPass)) + val request = Get(baseApiUrl + "/v1/session?login") ~> addCredentials(BasicHttpCredentials(wrongEmail, testPass)) val response = singleAwaitingRequest(request) //log.debug("==>> " + responseAs[String]) assert(response.status === StatusCodes.Unauthorized) @@ -265,7 +265,7 @@ class AuthenticationV1E2ESpec "The Users Route using the Authenticator trait " should { "succeed authentication using URL parameters with correct email and correct password " in { /* Correct email / correct password */ - val request = Get(baseApiUrl + s"/v1/users/$rootIriEnc?email=$rootEmailEnc&password=$testPass") + val request = Get(baseApiUrl + s"/v1/users/$rootIriEnc?email=$rootEmailEnc&password=$testPass") val response = singleAwaitingRequest(request) //log.debug("==>> " + responseAs[String]) assert(response.status === StatusCodes.OK) @@ -299,7 +299,7 @@ class AuthenticationV1E2ESpec } "not return sensitive information (token, password) in the response " in { - val request = Get(baseApiUrl + s"/v1/users/$rootIriEnc?email=$rootEmailEnc&password=$testPass") + val request = Get(baseApiUrl + s"/v1/users/$rootIriEnc?email=$rootEmailEnc&password=$testPass") val response = singleAwaitingRequest(request) //log.debug("==>> " + responseAs[String]) // assert(status === StatusCodes.OK) diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v1/ErrorV1E2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v1/ErrorV1E2ESpec.scala index 78557d1575..2115bc8c09 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v1/ErrorV1E2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v1/ErrorV1E2ESpec.scala @@ -12,14 +12,14 @@ import scala.concurrent.duration._ class ErrorV1E2ESpec extends E2ESpec with TriplestoreJsonProtocol { "Make a request that causes an internal server error (unit type message)" in { - val request = Get(baseApiUrl + "/v1/error/unitMsg") + val request = Get(baseApiUrl + "/v1/error/unitMsg") val response = singleAwaitingRequest(request, 1.second) println(response.toString()) assert(response.status == StatusCodes.InternalServerError) } "Make a request that causes an internal server error (ise type message)" in { - val request = Get(baseApiUrl + "/v1/error/iseMsg") + val request = Get(baseApiUrl + "/v1/error/iseMsg") val response = singleAwaitingRequest(request, 1.second) println(response.toString()) assert(response.status == StatusCodes.Conflict) diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v1/ListsV1E2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v1/ListsV1E2ESpec.scala index 5f8bab6901..1b2f297d74 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v1/ListsV1E2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v1/ListsV1E2ESpec.scala @@ -55,19 +55,19 @@ class ListsV1E2ESpec private val inactiveUserEmailEnc = java.net.URLEncoder.encode(SharedTestDataV1.inactiveUser.userData.email.get, "utf-8") - private val normalUserIri = SharedTestDataV1.normalUser.userData.user_id.get + private val normalUserIri = SharedTestDataV1.normalUser.userData.user_id.get private val normalUserIriEnc = java.net.URLEncoder.encode(normalUserIri, "utf-8") - private val multiUserIri = SharedTestDataV1.multiuserUser.userData.user_id.get + private val multiUserIri = SharedTestDataV1.multiuserUser.userData.user_id.get private val multiUserIriEnc = java.net.URLEncoder.encode(multiUserIri, "utf-8") private val wrongEmail = "wrong@example.com" - val wrongEmailEnc = java.net.URLEncoder.encode(wrongEmail, "utf-8") + val wrongEmailEnc = java.net.URLEncoder.encode(wrongEmail, "utf-8") private val testPass = java.net.URLEncoder.encode("test", "utf-8") - val wrongPass = java.net.URLEncoder.encode("wrong", "utf-8") + val wrongPass = java.net.URLEncoder.encode("wrong", "utf-8") - private val imagesProjectIri = SharedTestDataV1.imagesProjectInfo.id + private val imagesProjectIri = SharedTestDataV1.imagesProjectInfo.id private val imagesProjectIriEnc = java.net.URLEncoder.encode(imagesProjectIri, "utf-8") "The HList Route ('v1/hlists')" when { diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v1/PermissionsHandlingV1E2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v1/PermissionsHandlingV1E2ESpec.scala index 37e50c636a..6eca277e7f 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v1/PermissionsHandlingV1E2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v1/PermissionsHandlingV1E2ESpec.scala @@ -24,13 +24,13 @@ object PermissionsHandlingV1E2ESpec { */ class PermissionsHandlingV1E2ESpec extends E2ESpec(PermissionsHandlingV1E2ESpec.config) with TriplestoreJsonProtocol { - private val rootUser = SharedTestDataV1.rootUser + private val rootUser = SharedTestDataV1.rootUser private val rootUserEmail = rootUser.userData.email.get - private val imagesUser = SharedTestDataV1.imagesUser01 + private val imagesUser = SharedTestDataV1.imagesUser01 private val imagesUserEmail = imagesUser.userData.email.get - private val incunabulaUser = SharedTestDataV1.incunabulaProjectAdminUser + private val incunabulaUser = SharedTestDataV1.incunabulaProjectAdminUser private val incunabulaUserEmail = incunabulaUser.userData.email.get private val password = SharedTestDataADM.testPass diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v1/ProjectsV1E2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v1/ProjectsV1E2ESpec.scala index 3ce26dc7a1..144966eb2f 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v1/ProjectsV1E2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v1/ProjectsV1E2ESpec.scala @@ -37,12 +37,12 @@ class ProjectsV1E2ESpec implicit def default(implicit system: ActorSystem) = RouteTestTimeout(30.seconds) - private val rootEmail = SharedTestDataV1.rootUser.userData.email.get - private val rootEmailEnc = java.net.URLEncoder.encode(rootEmail, "utf-8") - private val testPass = java.net.URLEncoder.encode("test", "utf-8") - private val projectIri = SharedTestDataV1.imagesProjectInfo.id - private val projectIriEnc = java.net.URLEncoder.encode(projectIri, "utf-8") - private val projectShortName = SharedTestDataV1.imagesProjectInfo.shortname + private val rootEmail = SharedTestDataV1.rootUser.userData.email.get + private val rootEmailEnc = java.net.URLEncoder.encode(rootEmail, "utf-8") + private val testPass = java.net.URLEncoder.encode("test", "utf-8") + private val projectIri = SharedTestDataV1.imagesProjectInfo.id + private val projectIriEnc = java.net.URLEncoder.encode(projectIri, "utf-8") + private val projectShortName = SharedTestDataV1.imagesProjectInfo.shortname private val projectShortnameEnc = java.net.URLEncoder.encode(projectShortName, "utf-8") "The Projects Route ('v1/projects')" when { @@ -50,7 +50,7 @@ class ProjectsV1E2ESpec "used to query for project information" should { "return all projects" in { - val request = Get(baseApiUrl + s"/v1/projects") ~> addCredentials(BasicHttpCredentials(rootEmail, testPass)) + val request = Get(baseApiUrl + s"/v1/projects") ~> addCredentials(BasicHttpCredentials(rootEmail, testPass)) val response: HttpResponse = singleAwaitingRequest(request) // logger.debug(s"response: {}", response) assert(response.status === StatusCodes.OK) diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v1/ResourcesV1R2RSpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v1/ResourcesV1R2RSpec.scala index 51e4464d38..860f3b6346 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v1/ResourcesV1R2RSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v1/ResourcesV1R2RSpec.scala @@ -56,27 +56,27 @@ class ResourcesV1R2RSpec extends R2RSpec { private val resourcesPathV1 = DSPApiDirectives.handleErrors(system)(new ResourcesRouteV1(routeData).knoraApiPath) private val resourcesPathV2 = DSPApiDirectives.handleErrors(system)(new ResourcesRouteV2(routeData).knoraApiPath) - private val valuesPathV1 = DSPApiDirectives.handleErrors(system)(new ValuesRouteV1(routeData).knoraApiPath) + private val valuesPathV1 = DSPApiDirectives.handleErrors(system)(new ValuesRouteV1(routeData).knoraApiPath) - private val superUser = SharedTestDataADM.superUser + private val superUser = SharedTestDataADM.superUser private val superUserEmail = superUser.email - private val imagesUser = SharedTestDataADM.imagesUser01 + private val imagesUser = SharedTestDataADM.imagesUser01 private val imagesUserEmail = imagesUser.email - private val incunabulaUser = SharedTestDataADM.incunabulaProjectAdminUser + private val incunabulaUser = SharedTestDataADM.incunabulaProjectAdminUser private val incunabulaUserEmail = incunabulaUser.email - private val incunabulaUser2 = SharedTestDataADM.incunabulaCreatorUser + private val incunabulaUser2 = SharedTestDataADM.incunabulaCreatorUser private val incunabulaUserEmail2 = incunabulaUser2.email - private val anythingUser = SharedTestDataADM.anythingUser1 + private val anythingUser = SharedTestDataADM.anythingUser1 private val anythingUserEmail = anythingUser.email - private val anythingAdmin = SharedTestDataADM.anythingAdminUser + private val anythingAdmin = SharedTestDataADM.anythingAdminUser private val anythingAdminEmail = anythingAdmin.email - private val beolUser = SharedTestDataADM.beolUser + private val beolUser = SharedTestDataADM.beolUser private val beolUserEmail = beolUser.email private val password = SharedTestDataADM.testPass @@ -103,20 +103,20 @@ class ResourcesV1R2RSpec extends R2RSpec { RdfDataObject(path = "test_data/all_data/incunabula-data.ttl", name = "http://www.knora.org/data/0803/incunabula") ) - private val firstThingIri = new MutableTestIri - private val firstTextValueIRI = new MutableTestIri - private val secondThingIri = new MutableTestIri - private val thirdThingIri = new MutableTestIri - private val fourthThingIri = new MutableTestIri - private val fifthThingIri = new MutableTestIri - private val sixthThingIri = new MutableTestIri - private val seventhThingIri = new MutableTestIri - private val eighthThingIri = new MutableTestIri - private val abelAuthorIri = new MutableTestIri - private val mathIntelligencerIri = new MutableTestIri - private val deutschesDingIri = new MutableTestIri - private val standoffLangDingIri = new MutableTestIri - private val thingWithString = new MutableTestIri + private val firstThingIri = new MutableTestIri + private val firstTextValueIRI = new MutableTestIri + private val secondThingIri = new MutableTestIri + private val thirdThingIri = new MutableTestIri + private val fourthThingIri = new MutableTestIri + private val fifthThingIri = new MutableTestIri + private val sixthThingIri = new MutableTestIri + private val seventhThingIri = new MutableTestIri + private val eighthThingIri = new MutableTestIri + private val abelAuthorIri = new MutableTestIri + private val mathIntelligencerIri = new MutableTestIri + private val deutschesDingIri = new MutableTestIri + private val standoffLangDingIri = new MutableTestIri + private val thingWithString = new MutableTestIri private val thingWithCreationDate = new MutableTestIri // incunabula book with title "Eyn biechlin ..." @@ -310,9 +310,9 @@ class ResourcesV1R2RSpec extends R2RSpec { assert(status == StatusCodes.OK, response.toString) - val responseJson: Map[String, JsValue] = responseAs[String].parseJson.asJsObject.fields + val responseJson: Map[String, JsValue] = responseAs[String].parseJson.asJsObject.fields val resourceContext: Map[String, JsValue] = responseJson("resource_context").asJsObject.fields - val resinfo: Map[String, JsValue] = resourceContext("resinfo").asJsObject.fields + val resinfo: Map[String, JsValue] = resourceContext("resinfo").asJsObject.fields resinfo.get("regions") match { case Some(JsArray(regionsVector)) => @@ -1422,7 +1422,7 @@ class ResourcesV1R2RSpec extends R2RSpec { assert(status == StatusCodes.OK, responseStr) responseStr should include("createdResources") - val responseJson: JsObject = AkkaHttpUtils.httpResponseToJson(response) + val responseJson: JsObject = AkkaHttpUtils.httpResponseToJson(response) val createdResources: Seq[JsValue] = responseJson.fields("createdResources").asInstanceOf[JsArray].elements abelAuthorIri.set(createdResources.head.asJsObject.fields("resourceIri").asInstanceOf[JsString].value) mathIntelligencerIri.set(createdResources(2).asJsObject.fields("resourceIri").asInstanceOf[JsString].value) @@ -1677,10 +1677,10 @@ class ResourcesV1R2RSpec extends R2RSpec { BasicHttpCredentials(beolUserEmail, password) ) ~> resourcesPathV1 ~> check { val responseBodyFuture: Future[Array[Byte]] = response.entity.toStrict(5.seconds).map(_.data.toArray) - val responseBytes: Array[Byte] = Await.result(responseBodyFuture, 5.seconds) - val zippedFilenames = collection.mutable.Set.empty[String] - val zipInputStream = new ZipInputStream(new ByteArrayInputStream(responseBytes)) - var zipEntry: ZipEntry = null + val responseBytes: Array[Byte] = Await.result(responseBodyFuture, 5.seconds) + val zippedFilenames = collection.mutable.Set.empty[String] + val zipInputStream = new ZipInputStream(new ByteArrayInputStream(responseBytes)) + var zipEntry: ZipEntry = null while ({ zipEntry = zipInputStream.getNextEntry @@ -1701,10 +1701,10 @@ class ResourcesV1R2RSpec extends R2RSpec { BasicHttpCredentials(beolUserEmail, password) ) ~> resourcesPathV1 ~> check { val responseBodyFuture: Future[Array[Byte]] = response.entity.toStrict(5.seconds).map(_.data.toArray) - val responseBytes: Array[Byte] = Await.result(responseBodyFuture, 5.seconds) - val zippedFilenames = collection.mutable.Set.empty[String] + val responseBytes: Array[Byte] = Await.result(responseBodyFuture, 5.seconds) + val zippedFilenames = collection.mutable.Set.empty[String] - val zipInputStream = new ZipInputStream(new ByteArrayInputStream(responseBytes)) + val zipInputStream = new ZipInputStream(new ByteArrayInputStream(responseBytes)) var zipEntry: ZipEntry = null while ({ @@ -1726,10 +1726,10 @@ class ResourcesV1R2RSpec extends R2RSpec { BasicHttpCredentials(beolUserEmail, password) ) ~> resourcesPathV1 ~> check { val responseBodyFuture: Future[Array[Byte]] = response.entity.toStrict(5.seconds).map(_.data.toArray) - val responseBytes: Array[Byte] = Await.result(responseBodyFuture, 5.seconds) - val zippedFilenames = collection.mutable.Set.empty[String] - val zipInputStream = new ZipInputStream(new ByteArrayInputStream(responseBytes)) - var zipEntry: ZipEntry = null + val responseBytes: Array[Byte] = Await.result(responseBodyFuture, 5.seconds) + val zippedFilenames = collection.mutable.Set.empty[String] + val zipInputStream = new ZipInputStream(new ByteArrayInputStream(responseBytes)) + var zipEntry: ZipEntry = null while ({ zipEntry = zipInputStream.getNextEntry @@ -1750,7 +1750,7 @@ class ResourcesV1R2RSpec extends R2RSpec { } val xmlStringBuilder = new StringBuilder - val random = new Random + val random = new Random xmlStringBuilder.append( """ @@ -2046,7 +2046,7 @@ class ResourcesV1R2RSpec extends R2RSpec { assert(status == StatusCodes.OK, responseStr) responseStr should include("createdResources") - val responseJson: JsObject = AkkaHttpUtils.httpResponseToJson(response) + val responseJson: JsObject = AkkaHttpUtils.httpResponseToJson(response) val createdResources: Seq[JsValue] = responseJson.fields("createdResources").asInstanceOf[JsArray].elements thingWithString.set(createdResources.head.asJsObject.fields("resourceIri").asInstanceOf[JsString].value) @@ -2117,7 +2117,7 @@ class ResourcesV1R2RSpec extends R2RSpec { assert(status == StatusCodes.OK, responseStr) responseStr should include("createdResources") - val responseJson: JsObject = AkkaHttpUtils.httpResponseToJson(response) + val responseJson: JsObject = AkkaHttpUtils.httpResponseToJson(response) val createdResources: Seq[JsValue] = responseJson.fields("createdResources").asInstanceOf[JsArray].elements thingWithString.set(createdResources.head.asJsObject.fields("resourceIri").asInstanceOf[JsString].value) @@ -2178,7 +2178,7 @@ class ResourcesV1R2RSpec extends R2RSpec { assert(status == StatusCodes.OK, responseStr) responseStr should include("createdResources") - val responseJson: JsObject = AkkaHttpUtils.httpResponseToJson(response) + val responseJson: JsObject = AkkaHttpUtils.httpResponseToJson(response) val createdResources: Seq[JsValue] = responseJson.fields("createdResources").asInstanceOf[JsArray].elements thingWithString.set(createdResources.head.asJsObject.fields("resourceIri").asInstanceOf[JsString].value) @@ -2210,7 +2210,7 @@ class ResourcesV1R2RSpec extends R2RSpec { assert(status == StatusCodes.OK, response.toString) val responseStr = responseAs[String] responseStr should include("createdResources") - val responseJson: JsObject = AkkaHttpUtils.httpResponseToJson(response) + val responseJson: JsObject = AkkaHttpUtils.httpResponseToJson(response) val createdResources: Seq[JsValue] = responseJson.fields("createdResources").asInstanceOf[JsArray].elements thingWithCreationDate.set(createdResources.head.asJsObject.fields("resourceIri").asInstanceOf[JsString].value) } diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v1/SipiV1R2RSpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v1/SipiV1R2RSpec.scala index b49d0c4b25..e0052abbca 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v1/SipiV1R2RSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v1/SipiV1R2RSpec.scala @@ -35,12 +35,12 @@ class SipiV1R2RSpec extends R2RSpec { """.stripMargin private val resourcesPath = new ResourcesRouteV1(routeData).knoraApiPath - private val valuesPath = new ValuesRouteV1(routeData).knoraApiPath + private val valuesPath = new ValuesRouteV1(routeData).knoraApiPath implicit def default(implicit system: ActorSystem): RouteTestTimeout = RouteTestTimeout(settings.defaultTimeout) private val incunabulaProjectAdminEmail = SharedTestDataV1.incunabulaProjectAdminUser.userData.email.get - private val testPass = "test" + private val testPass = "test" override lazy val rdfDataObjects = List( RdfDataObject(path = "test_data/all_data/incunabula-data.ttl", name = "http://www.knora.org/data/0803/incunabula"), diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v1/StandoffV1R2RSpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v1/StandoffV1R2RSpec.scala index cbc75e7f09..aee6f5468c 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v1/StandoffV1R2RSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v1/StandoffV1R2RSpec.scala @@ -41,9 +41,9 @@ class StandoffV1R2RSpec extends R2RSpec { """.stripMargin private val standoffPath = DSPApiDirectives.handleErrors(system)(new StandoffRouteV1(routeData).knoraApiPath) - private val valuesPath = DSPApiDirectives.handleErrors(system)(new ValuesRouteV1(routeData).knoraApiPath) + private val valuesPath = DSPApiDirectives.handleErrors(system)(new ValuesRouteV1(routeData).knoraApiPath) - private val anythingUser = SharedTestDataV1.anythingUser1 + private val anythingUser = SharedTestDataV1.anythingUser1 private val anythingUserEmail = anythingUser.userData.email.get private val password = SharedTestDataADM.testPass @@ -59,9 +59,9 @@ class StandoffV1R2RSpec extends R2RSpec { RdfDataObject(path = "test_data/all_data/incunabula-data.ttl", name = "http://www.knora.org/data/0803/incunabula") ) - private val firstTextValueIri = new MutableTestIri + private val firstTextValueIri = new MutableTestIri private val secondTextValueIri = new MutableTestIri - private val thirdTextValueIri = new MutableTestIri + private val thirdTextValueIri = new MutableTestIri private val fourthTextValueIri = new MutableTestIri object ResponseUtils { @@ -708,7 +708,7 @@ class StandoffV1R2RSpec extends R2RSpec { "read the XML TextValue back to XML and compare it to the XML that was originally sent" in { val xmlFile = Paths.get("..", RequestParams.pathToLetterXML) - val xmlStr = FileUtil.readTextFile(xmlFile) + val xmlStr = FileUtil.readTextFile(xmlFile) Get("/v1/values/" + URLEncoder.encode(firstTextValueIri.get, "UTF-8")) ~> addCredentials( BasicHttpCredentials(anythingUserEmail, password) @@ -737,7 +737,7 @@ class StandoffV1R2RSpec extends R2RSpec { "change a text value from XML representing a letter" in { val xmlFileToSend = Paths.get("..", RequestParams.pathToLetter2XML) - val xmlStrToSend = FileUtil.readTextFile(xmlFileToSend) + val xmlStrToSend = FileUtil.readTextFile(xmlFileToSend) val newValueParams = s""" @@ -770,7 +770,7 @@ class StandoffV1R2RSpec extends R2RSpec { "read the changed TextValue back to XML and compare it to the XML that was originally sent" in { val xmlFile = Paths.get("..", RequestParams.pathToLetter2XML) - val xmlStr = FileUtil.readTextFile(xmlFile) + val xmlStr = FileUtil.readTextFile(xmlFile) Get("/v1/values/" + URLEncoder.encode(firstTextValueIri.get, "UTF-8")) ~> addCredentials( BasicHttpCredentials(anythingUserEmail, password) @@ -799,7 +799,7 @@ class StandoffV1R2RSpec extends R2RSpec { "create a TextValue from complex XML representing a letter" in { val xmlFileToSend = Paths.get("..", RequestParams.pathToLetter3XML) - val xmlStrToSend = FileUtil.readTextFile(xmlFileToSend) + val xmlStrToSend = FileUtil.readTextFile(xmlFileToSend) val newValueParams = s""" @@ -833,7 +833,7 @@ class StandoffV1R2RSpec extends R2RSpec { "read the complex TextValue back to XML and compare it to the XML that was originally sent" in { val xmlFile = Paths.get("..", RequestParams.pathToLetter3XML) - val xmlStr = FileUtil.readTextFile(xmlFile) + val xmlStr = FileUtil.readTextFile(xmlFile) Get("/v1/values/" + URLEncoder.encode(secondTextValueIri.get, "UTF-8")) ~> addCredentials( BasicHttpCredentials(anythingUserEmail, password) @@ -897,7 +897,7 @@ class StandoffV1R2RSpec extends R2RSpec { "create a TextValue from StandardXML representing HTML (in strict XML notation)" in { val xmlFileToSend = Paths.get("..", RequestParams.pathToStandardHTML) - val xmlStrToSend = FileUtil.readTextFile(xmlFileToSend) + val xmlStrToSend = FileUtil.readTextFile(xmlFileToSend) val newValueParams = s""" @@ -931,7 +931,7 @@ class StandoffV1R2RSpec extends R2RSpec { "read the TextValue back to XML and compare it to the (Standard) HTML that was originally sent" in { val htmlFile = Paths.get("..", RequestParams.pathToStandardHTML) - val htmlStr = FileUtil.readTextFile(htmlFile) + val htmlStr = FileUtil.readTextFile(htmlFile) Get("/v1/values/" + URLEncoder.encode(thirdTextValueIri.get, "UTF-8")) ~> addCredentials( BasicHttpCredentials(anythingUserEmail, password) @@ -960,7 +960,7 @@ class StandoffV1R2RSpec extends R2RSpec { "create a TextValue from StandardXML representing HTML with internal anchor link" in { val xmlFileToSend = Paths.get("..", RequestParams.pathToStandardHTMLInternalLink) - val xmlStrToSend = FileUtil.readTextFile(xmlFileToSend) + val xmlStrToSend = FileUtil.readTextFile(xmlFileToSend) val newValueParams = s""" @@ -994,7 +994,7 @@ class StandoffV1R2RSpec extends R2RSpec { "read the TextValue back to XML and compare it to the (Standard) HTML with internal anchor link that was originally sent" in { val htmlFile = Paths.get("..", RequestParams.pathToStandardHTMLInternalLink) - val htmlStr = FileUtil.readTextFile(htmlFile) + val htmlStr = FileUtil.readTextFile(htmlFile) Get("/v1/values/" + URLEncoder.encode(fourthTextValueIri.get, "UTF-8")) ~> addCredentials( BasicHttpCredentials(anythingUserEmail, password) @@ -1023,7 +1023,7 @@ class StandoffV1R2RSpec extends R2RSpec { "create a TextValue from XML representing HTML (in strict XML notation)" in { val xmlFileToSend = Paths.get("..", RequestParams.pathToHTML) - val xmlStrToSend = FileUtil.readTextFile(xmlFileToSend) + val xmlStrToSend = FileUtil.readTextFile(xmlFileToSend) val newValueParams = s""" @@ -1057,7 +1057,7 @@ class StandoffV1R2RSpec extends R2RSpec { "read the TextValue back to XML and compare it to the HTML that was originally sent" in { val htmlFile = Paths.get("..", RequestParams.pathToHTML) - val htmlStr = FileUtil.readTextFile(htmlFile) + val htmlStr = FileUtil.readTextFile(htmlFile) Get("/v1/values/" + URLEncoder.encode(thirdTextValueIri.get, "UTF-8")) ~> addCredentials( BasicHttpCredentials(anythingUserEmail, password) diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v1/UsersV1E2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v1/UsersV1E2ESpec.scala index 09dc2e07fc..0a2557ffaf 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v1/UsersV1E2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v1/UsersV1E2ESpec.scala @@ -48,19 +48,19 @@ class UsersV1E2ESpec extends E2ESpec(UsersV1E2ESpec.config) with SessionJsonProt private val inactiveUserEmailEnc = java.net.URLEncoder.encode(SharedTestDataV1.inactiveUser.userData.email.get, "utf-8") - private val normalUserIri = SharedTestDataV1.normalUser.userData.user_id.get + private val normalUserIri = SharedTestDataV1.normalUser.userData.user_id.get private val normalUserIriEnc = java.net.URLEncoder.encode(normalUserIri, "utf-8") - private val multiUserIri = SharedTestDataV1.multiuserUser.userData.user_id.get + private val multiUserIri = SharedTestDataV1.multiuserUser.userData.user_id.get private val multiUserIriEnc = java.net.URLEncoder.encode(multiUserIri, "utf-8") - private val wrongEmail = "wrong@example.com" + private val wrongEmail = "wrong@example.com" private val wrongEmailEnc = java.net.URLEncoder.encode(wrongEmail, "utf-8") - private val testPass = java.net.URLEncoder.encode("test", "utf-8") + private val testPass = java.net.URLEncoder.encode("test", "utf-8") private val wrongPass = java.net.URLEncoder.encode("wrong", "utf-8") - private val imagesProjectIri = SharedTestDataV1.imagesProjectInfo.id + private val imagesProjectIri = SharedTestDataV1.imagesProjectInfo.id private val imagesProjectIriEnc = java.net.URLEncoder.encode(imagesProjectIri, "utf-8") /** diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v1/ValuesV1R2RSpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v1/ValuesV1R2RSpec.scala index bdee731d81..8b320ba147 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v1/ValuesV1R2RSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v1/ValuesV1R2RSpec.scala @@ -35,20 +35,20 @@ class ValuesV1R2RSpec extends R2RSpec { implicit def default(implicit system: ActorSystem): RouteTestTimeout = RouteTestTimeout(settings.defaultTimeout) - private val integerValueIri = new MutableTestIri - private val timeValueIri = new MutableTestIri - private val textValueIri = new MutableTestIri - private val linkValueIri = new MutableTestIri + private val integerValueIri = new MutableTestIri + private val timeValueIri = new MutableTestIri + private val textValueIri = new MutableTestIri + private val linkValueIri = new MutableTestIri private val textValueWithLangIri = new MutableTestIri - private val boringComment = "This is a boring comment." + private val boringComment = "This is a boring comment." override lazy val rdfDataObjects = List( RdfDataObject(path = "test_data/all_data/anything-data.ttl", name = "http://www.knora.org/data/0001/anything") ) - private val anythingUser = SharedTestDataV1.anythingUser1 + private val anythingUser = SharedTestDataV1.anythingUser1 private val anythingUserEmail = anythingUser.userData.email.get - private val testPass = "test" + private val testPass = "test" private val mappingIri = "http://rdfh.ch/standoff/mappings/StandardMapping" @@ -68,7 +68,7 @@ class ValuesV1R2RSpec extends R2RSpec { ) ~> valuesPath ~> check { assert(status == StatusCodes.OK, response.toString) val responseJson: Map[String, JsValue] = responseAs[String].parseJson.asJsObject.fields - val valueIri: IRI = responseJson("id").asInstanceOf[JsString].value + val valueIri: IRI = responseJson("id").asInstanceOf[JsString].value integerValueIri.set(valueIri) } } @@ -89,7 +89,7 @@ class ValuesV1R2RSpec extends R2RSpec { ) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, testPass)) ~> valuesPath ~> check { assert(status == StatusCodes.OK, response.toString) val responseJson: Map[String, JsValue] = responseAs[String].parseJson.asJsObject.fields - val valueIri: IRI = responseJson("id").asInstanceOf[JsString].value + val valueIri: IRI = responseJson("id").asInstanceOf[JsString].value integerValueIri.set(valueIri) } } @@ -117,7 +117,7 @@ class ValuesV1R2RSpec extends R2RSpec { ) ~> valuesPath ~> check { assert(status == StatusCodes.OK, response.toString) val responseJson: Map[String, JsValue] = responseAs[String].parseJson.asJsObject.fields - val valueIri: IRI = responseJson("id").asInstanceOf[JsString].value + val valueIri: IRI = responseJson("id").asInstanceOf[JsString].value timeValueIri.set(valueIri) } } @@ -138,7 +138,7 @@ class ValuesV1R2RSpec extends R2RSpec { ) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, testPass)) ~> valuesPath ~> check { assert(status == StatusCodes.OK, response.toString) val responseJson: Map[String, JsValue] = responseAs[String].parseJson.asJsObject.fields - val valueIri: IRI = responseJson("id").asInstanceOf[JsString].value + val valueIri: IRI = responseJson("id").asInstanceOf[JsString].value timeValueIri.set(valueIri) } } @@ -303,7 +303,7 @@ class ValuesV1R2RSpec extends R2RSpec { ) ~> valuesPath ~> check { assert(status == StatusCodes.OK, response.toString) val responseJson: Map[String, JsValue] = responseAs[String].parseJson.asJsObject.fields - val valueIri: IRI = responseJson("id").asInstanceOf[JsString].value + val valueIri: IRI = responseJson("id").asInstanceOf[JsString].value linkValueIri.set(valueIri) } } @@ -332,7 +332,7 @@ class ValuesV1R2RSpec extends R2RSpec { ) ~> valuesPath ~> check { assert(status == StatusCodes.OK, response.toString) val responseJson: Map[String, JsValue] = responseAs[String].parseJson.asJsObject.fields - val valueIri: IRI = responseJson("id").asInstanceOf[JsString].value + val valueIri: IRI = responseJson("id").asInstanceOf[JsString].value linkValueIri.set(valueIri) } } @@ -345,8 +345,8 @@ class ValuesV1R2RSpec extends R2RSpec { assert(status == StatusCodes.OK, response.toString) val responseObj = AkkaHttpUtils.httpResponseToJson(response).fields - val comment = responseObj("comment").asInstanceOf[JsString].value - val linkValue = responseObj("value").asJsObject.fields + val comment = responseObj("comment").asInstanceOf[JsString].value + val linkValue = responseObj("value").asJsObject.fields assert( linkValue("subjectIri").asInstanceOf[JsString].value == "http://rdfh.ch/0001/a-thing" && diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v2/AuthenticationV2E2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v2/AuthenticationV2E2ESpec.scala index 318683eaca..f1ab16e168 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v2/AuthenticationV2E2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v2/AuthenticationV2E2ESpec.scala @@ -40,24 +40,24 @@ class AuthenticationV2E2ESpec private implicit def default(implicit system: ActorSystem): RouteTestTimeout = RouteTestTimeout(settings.defaultTimeout) - private val rootIri = SharedTestDataADM.rootUser.id - private val rootIriEnc = java.net.URLEncoder.encode(rootIri, "utf-8") - private val rootUsername = SharedTestDataADM.rootUser.username - private val rootUsernameEnc = java.net.URLEncoder.encode(rootUsername, "utf-8") - private val rootEmail = SharedTestDataADM.rootUser.email - private val rootEmailEnc = java.net.URLEncoder.encode(rootEmail, "utf-8") - private val inactiveUserEmail = SharedTestDataADM.inactiveUser.email + private val rootIri = SharedTestDataADM.rootUser.id + private val rootIriEnc = java.net.URLEncoder.encode(rootIri, "utf-8") + private val rootUsername = SharedTestDataADM.rootUser.username + private val rootUsernameEnc = java.net.URLEncoder.encode(rootUsername, "utf-8") + private val rootEmail = SharedTestDataADM.rootUser.email + private val rootEmailEnc = java.net.URLEncoder.encode(rootEmail, "utf-8") + private val inactiveUserEmail = SharedTestDataADM.inactiveUser.email private val inactiveUserEmailEnc = java.net.URLEncoder.encode(inactiveUserEmail, "utf-8") - private val wrongEmail = "wrong@example.com" - private val wrongEmailEnc = java.net.URLEncoder.encode(wrongEmail, "utf-8") - private val testPass = java.net.URLEncoder.encode("test", "utf-8") - private val wrongPass = java.net.URLEncoder.encode("wrong", "utf-8") + private val wrongEmail = "wrong@example.com" + private val wrongEmailEnc = java.net.URLEncoder.encode(wrongEmail, "utf-8") + private val testPass = java.net.URLEncoder.encode("test", "utf-8") + private val wrongPass = java.net.URLEncoder.encode("wrong", "utf-8") "The Authentication Route ('v2/authentication') with credentials supplied via URL parameters" should { "authenticate with correct user IRI and password" in { /* Correct username and password */ - val request = Get(baseApiUrl + s"/v2/authentication?iri=$rootIriEnc&password=$testPass") + val request = Get(baseApiUrl + s"/v2/authentication?iri=$rootIriEnc&password=$testPass") val response: HttpResponse = singleAwaitingRequest(request) logger.debug(s"response: ${response.toString}") assert(response.status === StatusCodes.OK) @@ -65,7 +65,7 @@ class AuthenticationV2E2ESpec "authenticate with correct email and password" in { /* Correct username and password */ - val request = Get(baseApiUrl + s"/v2/authentication?email=$rootEmailEnc&password=$testPass") + val request = Get(baseApiUrl + s"/v2/authentication?email=$rootEmailEnc&password=$testPass") val response: HttpResponse = singleAwaitingRequest(request) logger.debug(s"response: ${response.toString}") assert(response.status === StatusCodes.OK) @@ -73,7 +73,7 @@ class AuthenticationV2E2ESpec "authenticate with correct username and password" in { /* Correct username and password */ - val request = Get(baseApiUrl + s"/v2/authentication?username=$rootUsernameEnc&password=$testPass") + val request = Get(baseApiUrl + s"/v2/authentication?username=$rootUsernameEnc&password=$testPass") val response: HttpResponse = singleAwaitingRequest(request) logger.debug(s"response: ${response.toString}") assert(response.status === StatusCodes.OK) @@ -81,14 +81,14 @@ class AuthenticationV2E2ESpec "fail authentication with correct email and wrong password" in { /* Correct email / wrong password */ - val request = Get(baseApiUrl + s"/v2/authentication?email=$rootEmail&password=$wrongPass") + val request = Get(baseApiUrl + s"/v2/authentication?email=$rootEmail&password=$wrongPass") val response: HttpResponse = singleAwaitingRequest(request) logger.debug(s"response: ${response.toString}") assert(response.status === StatusCodes.Unauthorized) } "fail authentication with the user set as 'not active' " in { /* User not active */ - val request = Get(baseApiUrl + s"/v2/authentication?email=$inactiveUserEmailEnc&password=$testPass") + val request = Get(baseApiUrl + s"/v2/authentication?email=$inactiveUserEmailEnc&password=$testPass") val response: HttpResponse = singleAwaitingRequest(request) logger.debug(s"response: ${response.toString}") assert(response.status === StatusCodes.Unauthorized) @@ -99,14 +99,14 @@ class AuthenticationV2E2ESpec "authenticate with correct email and password" in { /* Correct email / correct password */ - val request = Get(baseApiUrl + "/v2/authentication") ~> addCredentials(BasicHttpCredentials(rootEmail, testPass)) + val request = Get(baseApiUrl + "/v2/authentication") ~> addCredentials(BasicHttpCredentials(rootEmail, testPass)) val response = singleAwaitingRequest(request) assert(response.status == StatusCodes.OK) } "fail authentication with correct email and wrong password" in { /* Correct username / wrong password */ - val request = Get(baseApiUrl + "/v2/authentication") ~> addCredentials(BasicHttpCredentials(rootEmail, wrongPass)) + val request = Get(baseApiUrl + "/v2/authentication") ~> addCredentials(BasicHttpCredentials(rootEmail, wrongPass)) val response = singleAwaitingRequest(request) assert(response.status == StatusCodes.Unauthorized) } @@ -135,7 +135,7 @@ class AuthenticationV2E2ESpec |} """.stripMargin - val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) + val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) val response: HttpResponse = singleAwaitingRequest(request) assert(response.status == StatusCodes.OK) @@ -159,7 +159,7 @@ class AuthenticationV2E2ESpec |} """.stripMargin - val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) + val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) val response: HttpResponse = singleAwaitingRequest(request) assert(response.status == StatusCodes.OK) @@ -181,7 +181,7 @@ class AuthenticationV2E2ESpec |} """.stripMargin - val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) + val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) val response: HttpResponse = singleAwaitingRequest(request) assert(response.status == StatusCodes.OK) @@ -204,7 +204,7 @@ class AuthenticationV2E2ESpec "authenticate with token in request parameter" in { // authenticate by calling '/v2/authenticate' with parameters providing the token (from earlier login) - val request = Get(baseApiUrl + s"/v2/authentication?token=${token.get}") + val request = Get(baseApiUrl + s"/v2/authentication?token=${token.get}") val response = singleAwaitingRequest(request) // logger.debug("==>> " + responseAs[String]) assert(response.status === StatusCodes.OK) @@ -229,12 +229,12 @@ class AuthenticationV2E2ESpec |} """.stripMargin - val request1 = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) + val request1 = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) val response1: HttpResponse = singleAwaitingRequest(request1) assert(response1.status == StatusCodes.OK) val token = Await.result(Unmarshal(response1.entity).to[LoginResponse], 1.seconds).token - val request2 = Delete(baseApiUrl + s"/v2/authentication?token=$token") + val request2 = Delete(baseApiUrl + s"/v2/authentication?token=$token") val response2 = singleAwaitingRequest(request2) // logger.debug("==>> " + responseAs[String]) assert(response2.status === StatusCodes.OK) @@ -259,7 +259,7 @@ class AuthenticationV2E2ESpec |} """.stripMargin - val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) + val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) val response = singleAwaitingRequest(request) //log.debug("==>> " + responseAs[String]) assert(response.status === StatusCodes.Unauthorized) @@ -275,21 +275,21 @@ class AuthenticationV2E2ESpec |} """.stripMargin - val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) + val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) val response = singleAwaitingRequest(request) //log.debug("==>> " + responseAs[String]) assert(response.status === StatusCodes.Unauthorized) } "fail authentication with wrong token in header" in { - val request = Get(baseApiUrl + "/v2/authentication") ~> addCredentials(GenericHttpCredentials("Bearer", "123456")) + val request = Get(baseApiUrl + "/v2/authentication") ~> addCredentials(GenericHttpCredentials("Bearer", "123456")) val response = singleAwaitingRequest(request) //log.debug("==>> " + responseAs[String]) assert(response.status === StatusCodes.Unauthorized) } "fail authentication with wrong token as parameter" in { - val request = Get(baseApiUrl + "/v2/authentication?token=123456") + val request = Get(baseApiUrl + "/v2/authentication?token=123456") val response = singleAwaitingRequest(request) //log.debug("==>> " + responseAs[String]) assert(response.status === StatusCodes.Unauthorized) @@ -311,7 +311,7 @@ class AuthenticationV2E2ESpec |} """.stripMargin - val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) + val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) val response: HttpResponse = singleAwaitingRequest(request) assert(response.status == StatusCodes.OK) @@ -327,7 +327,7 @@ class AuthenticationV2E2ESpec "allow access using URL parameters and token from v2" in { /* Correct email / correct password */ - val request = Get(baseApiUrl + s"/v1/users/$rootIriEnc?token=${token.get}") + val request = Get(baseApiUrl + s"/v1/users/$rootIriEnc?token=${token.get}") val response = singleAwaitingRequest(request) // logger.debug("==>> " + responseAs[String]) assert(response.status === StatusCodes.OK) @@ -361,7 +361,7 @@ class AuthenticationV2E2ESpec } "not return sensitive information (token, password) in the response " in { - val request = Get(baseApiUrl + s"/v1/users/$rootIriEnc?token=${token.get}") + val request = Get(baseApiUrl + s"/v1/users/$rootIriEnc?token=${token.get}") val response = singleAwaitingRequest(request) // logger.debug("==>> " + responseAs[String]) // assert(status === StatusCodes.OK) @@ -388,7 +388,7 @@ class AuthenticationV2E2ESpec |} """.stripMargin - val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) + val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) val response: HttpResponse = singleAwaitingRequest(request) assert(response.status == StatusCodes.OK) @@ -404,7 +404,7 @@ class AuthenticationV2E2ESpec "allow access using URL parameters with token from v2" in { /* Correct token */ - val request = Get(baseApiUrl + s"/admin/users/iri/$rootIriEnc?token=${token.get}") + val request = Get(baseApiUrl + s"/admin/users/iri/$rootIriEnc?token=${token.get}") val response = singleAwaitingRequest(request) // logger.debug(response.toString()) assert(response.status === StatusCodes.OK) @@ -438,7 +438,7 @@ class AuthenticationV2E2ESpec } "not return sensitive information (token, password) in the response " in { - val request = Get(baseApiUrl + s"/admin/users/iri/$rootIriEnc?token=${token.get}") + val request = Get(baseApiUrl + s"/admin/users/iri/$rootIriEnc?token=${token.get}") val response = singleAwaitingRequest(request) // logger.debug("==>> " + responseAs[String]) // assert(status === StatusCodes.OK) diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v2/MarkupHeader.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v2/MarkupHeader.scala index 6576ce81bb..38c7898f0e 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v2/MarkupHeader.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v2/MarkupHeader.scala @@ -17,13 +17,13 @@ import scala.util.Try * The definition follows [[https://doc.akka.io/docs/akka-http/current/common/http-model.html#custom-headers]]. */ final class MarkupHeader(token: String) extends ModeledCustomHeader[MarkupHeader] { - override def renderInRequests = true - override def renderInResponses = true + override def renderInRequests = true + override def renderInResponses = true override val companion: MarkupHeader.type = MarkupHeader - override def value: String = token + override def value: String = token } object MarkupHeader extends ModeledCustomHeaderCompanion[MarkupHeader] { - override val name: String = RouteUtilV2.MARKUP_HEADER + override val name: String = RouteUtilV2.MARKUP_HEADER override def parse(value: String) = Try(new MarkupHeader(value)) } diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v2/OntologyV2R2RSpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v2/OntologyV2R2RSpec.scala index c9f46f4336..b499d5be82 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v2/OntologyV2R2RSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v2/OntologyV2R2RSpec.scala @@ -26,10 +26,10 @@ import scala.concurrent.ExecutionContextExecutor object OntologyV2R2RSpec { private val anythingUserProfile = SharedTestDataADM.anythingAdminUser - private val anythingUsername = anythingUserProfile.email + private val anythingUsername = anythingUserProfile.email private val superUserProfile = SharedTestDataADM.superUser - private val superUsername = superUserProfile.email + private val superUsername = superUserProfile.email private val password = SharedTestDataADM.testPass } @@ -50,7 +50,7 @@ class OntologyV2R2RSpec extends R2RSpec { private implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance private val ontologiesPath = DSPApiDirectives.handleErrors(system)(new OntologiesRouteV2(routeData).knoraApiPath) - private val resourcesPath = DSPApiDirectives.handleErrors(system)(new ResourcesRouteV2(routeData).knoraApiPath) + private val resourcesPath = DSPApiDirectives.handleErrors(system)(new ResourcesRouteV2(routeData).knoraApiPath) implicit def default(implicit system: ActorSystem): RouteTestTimeout = RouteTestTimeout(settings.defaultTimeout) @@ -129,7 +129,7 @@ class OntologyV2R2RSpec extends R2RSpec { */ def writeFile(responseStr: String, mediaType: MediaType.NonBinary): Unit = if (!disableWrite) { - val fileSuffix = mediaType.fileExtensions.head + val fileSuffix = mediaType.fileExtensions.head val newOutputFile = Paths.get("..", "test_data", "ontologyR2RV2", s"$fileBasename.$fileSuffix") Files.createDirectories(newOutputFile.getParent) @@ -158,9 +158,9 @@ class OntologyV2R2RSpec extends R2RSpec { } // URL-encoded IRIs for use as URL segments in HTTP GET tests. - private val anythingProjectSegment = URLEncoder.encode(SharedTestDataADM.ANYTHING_PROJECT_IRI, "UTF-8") + private val anythingProjectSegment = URLEncoder.encode(SharedTestDataADM.ANYTHING_PROJECT_IRI, "UTF-8") private val incunabulaProjectSegment = URLEncoder.encode(SharedTestDataADM.INCUNABULA_PROJECT_IRI, "UTF-8") - private val beolProjectSegment = URLEncoder.encode(SharedTestDataADM.BEOL_PROJECT_IRI, "UTF-8") + private val beolProjectSegment = URLEncoder.encode(SharedTestDataADM.BEOL_PROJECT_IRI, "UTF-8") private val knoraApiSimpleOntologySegment = URLEncoder.encode(OntologyConstants.KnoraApiV2Simple.KnoraApiOntologyIri, "UTF-8") private val knoraApiWithValueObjectsOntologySegment = @@ -342,15 +342,15 @@ class OntologyV2R2RSpec extends R2RSpec { RdfMediaTypes.`application/rdf+xml` ) - private val fooIri = new MutableTestIri - private val barIri = new MutableTestIri + private val fooIri = new MutableTestIri + private val barIri = new MutableTestIri private var fooLastModDate: Instant = Instant.now private var barLastModDate: Instant = Instant.now private var anythingLastModDate: Instant = Instant.parse("2017-12-19T15:23:42.166Z") private var freetestLastModDate: Instant = Instant.parse("2012-12-12T12:12:12.12Z") - private val uselessIri = new MutableTestIri + private val uselessIri = new MutableTestIri private var uselessLastModDate: Instant = Instant.now private def getPropertyIrisFromResourceClassResponse(responseJsonDoc: JsonLDDocument): Set[SmartIri] = { @@ -390,7 +390,7 @@ class OntologyV2R2RSpec extends R2RSpec { val existingFile: Path = httpGetTest.makeFile(mediaType) if (Files.exists(existingFile)) { - val parsedResponse: RdfModel = parseRdfXml(responseStr) + val parsedResponse: RdfModel = parseRdfXml(responseStr) val parsedExistingFile: RdfModel = parseRdfXml(httpGetTest.readFile(mediaType)) if (parsedResponse != parsedExistingFile) { @@ -470,8 +470,8 @@ class OntologyV2R2RSpec extends R2RSpec { val responseStr = responseAs[String] assert(status == StatusCodes.OK, responseStr) val responseJsonDoc = JsonLDUtil.parseJsonLD(responseStr) - val metadata = responseJsonDoc.body - val ontologyIri = metadata.value("@id").asInstanceOf[JsonLDString].value + val metadata = responseJsonDoc.body + val ontologyIri = metadata.value("@id").asInstanceOf[JsonLDString].value assert(ontologyIri == "http://0.0.0.0:3333/ontology/0001/foo/v2") fooIri.set(ontologyIri) assert(metadata.value(OntologyConstants.Rdfs.Label) == JsonLDString(label)) @@ -489,7 +489,7 @@ class OntologyV2R2RSpec extends R2RSpec { } "create an empty ontology called 'bar' with a comment" in { - val label = "The bar ontology" + val label = "The bar ontology" val comment = "some comment" val params = @@ -514,8 +514,8 @@ class OntologyV2R2RSpec extends R2RSpec { val responseStr = responseAs[String] assert(status == StatusCodes.OK, responseStr) val responseJsonDoc = JsonLDUtil.parseJsonLD(responseStr) - val metadata = responseJsonDoc.body - val ontologyIri = metadata.value("@id").asInstanceOf[JsonLDString].value + val metadata = responseJsonDoc.body + val ontologyIri = metadata.value("@id").asInstanceOf[JsonLDString].value assert(ontologyIri == "http://0.0.0.0:3333/ontology/0001/bar/v2") assert( metadata.value(OntologyConstants.Rdfs.Comment) == JsonLDString( @@ -535,7 +535,7 @@ class OntologyV2R2RSpec extends R2RSpec { } "create an empty ontology called 'test' with a comment that has a special character" in { - val label = "The test ontology" + val label = "The test ontology" val comment = "some \\\"test\\\" comment" val params = @@ -558,8 +558,8 @@ class OntologyV2R2RSpec extends R2RSpec { val responseStr = responseAs[String] assert(status == StatusCodes.OK, responseStr) val responseJsonDoc = JsonLDUtil.parseJsonLD(responseStr) - val metadata = responseJsonDoc.body - val ontologyIri = metadata.value("@id").asInstanceOf[JsonLDString].value + val metadata = responseJsonDoc.body + val ontologyIri = metadata.value("@id").asInstanceOf[JsonLDString].value assert(ontologyIri == "http://0.0.0.0:3333/ontology/0001/test/v2") assert( metadata.value(OntologyConstants.Rdfs.Comment) == JsonLDString( @@ -570,7 +570,7 @@ class OntologyV2R2RSpec extends R2RSpec { } "change the metadata of 'foo'" in { - val newLabel = "The modified foo ontology" + val newLabel = "The modified foo ontology" val newComment = "new comment" val params = @@ -596,8 +596,8 @@ class OntologyV2R2RSpec extends R2RSpec { ) ~> ontologiesPath ~> check { assert(status == StatusCodes.OK, response.toString) val responseJsonDoc = responseToJsonLDDocument(response) - val metadata = responseJsonDoc.body - val ontologyIri = metadata.value("@id").asInstanceOf[JsonLDString].value + val metadata = responseJsonDoc.body + val ontologyIri = metadata.value("@id").asInstanceOf[JsonLDString].value assert(ontologyIri == fooIri.get) assert(metadata.value(OntologyConstants.Rdfs.Label) == JsonLDString(newLabel)) assert(metadata.value(OntologyConstants.Rdfs.Comment) == JsonLDString(newComment)) @@ -636,8 +636,8 @@ class OntologyV2R2RSpec extends R2RSpec { ) ~> ontologiesPath ~> check { assert(status == StatusCodes.OK, response.toString) val responseJsonDoc = responseToJsonLDDocument(response) - val metadata = responseJsonDoc.body - val ontologyIri = metadata.value("@id").asInstanceOf[JsonLDString].value + val metadata = responseJsonDoc.body + val ontologyIri = metadata.value("@id").asInstanceOf[JsonLDString].value assert(ontologyIri == barIri.get) assert( metadata.value(OntologyConstants.Rdfs.Comment) == JsonLDString( @@ -657,7 +657,7 @@ class OntologyV2R2RSpec extends R2RSpec { } "delete the comment from 'foo'" in { - val fooIriEncoded = URLEncoder.encode(fooIri.get, "UTF-8") + val fooIriEncoded = URLEncoder.encode(fooIri.get, "UTF-8") val lastModificationDate = URLEncoder.encode(fooLastModDate.toString, "UTF-8") Delete(s"/v2/ontologies/comment/$fooIriEncoded?lastModificationDate=$lastModificationDate") ~> addCredentials( @@ -665,8 +665,8 @@ class OntologyV2R2RSpec extends R2RSpec { ) ~> ontologiesPath ~> check { assert(status == StatusCodes.OK, response.toString) val responseJsonDoc = responseToJsonLDDocument(response) - val metadata = responseJsonDoc.body - val ontologyIri = metadata.value("@id").asInstanceOf[JsonLDString].value + val metadata = responseJsonDoc.body + val ontologyIri = metadata.value("@id").asInstanceOf[JsonLDString].value assert(ontologyIri == fooIri.get) assert(metadata.value(OntologyConstants.Rdfs.Label) == JsonLDString("The modified foo ontology")) assert(!metadata.value.contains(OntologyConstants.Rdfs.Comment)) @@ -699,7 +699,7 @@ class OntologyV2R2RSpec extends R2RSpec { } "delete the 'foo' ontology" in { - val fooIriEncoded = URLEncoder.encode(fooIri.get, "UTF-8") + val fooIriEncoded = URLEncoder.encode(fooIri.get, "UTF-8") val lastModificationDate = URLEncoder.encode(fooLastModDate.toString, "UTF-8") Delete(s"/v2/ontologies/$fooIriEncoded?lastModificationDate=$lastModificationDate") ~> addCredentials( @@ -1745,7 +1745,7 @@ class OntologyV2R2RSpec extends R2RSpec { } "delete the property anything:hasOtherNothing" in { - val propertySegment = URLEncoder.encode("http://0.0.0.0:3333/ontology/0001/anything/v2#hasOtherNothing", "UTF-8") + val propertySegment = URLEncoder.encode("http://0.0.0.0:3333/ontology/0001/anything/v2#hasOtherNothing", "UTF-8") val lastModificationDate = URLEncoder.encode(anythingLastModDate.toString, "UTF-8") Delete( @@ -2079,7 +2079,7 @@ class OntologyV2R2RSpec extends R2RSpec { } "delete the property anything:hasNothingness" in { - val propertySegment = URLEncoder.encode("http://0.0.0.0:3333/ontology/0001/anything/v2#hasNothingness", "UTF-8") + val propertySegment = URLEncoder.encode("http://0.0.0.0:3333/ontology/0001/anything/v2#hasNothingness", "UTF-8") val lastModificationDate = URLEncoder.encode(anythingLastModDate.toString, "UTF-8") Delete( @@ -2151,7 +2151,7 @@ class OntologyV2R2RSpec extends R2RSpec { } "delete the property anything:hasEmptiness" in { - val propertySegment = URLEncoder.encode("http://0.0.0.0:3333/ontology/0001/anything/v2#hasEmptiness", "UTF-8") + val propertySegment = URLEncoder.encode("http://0.0.0.0:3333/ontology/0001/anything/v2#hasEmptiness", "UTF-8") val lastModificationDate = URLEncoder.encode(anythingLastModDate.toString, "UTF-8") Delete( @@ -2188,7 +2188,7 @@ class OntologyV2R2RSpec extends R2RSpec { } "delete the class anything:Nothing" in { - val classSegment = URLEncoder.encode("http://0.0.0.0:3333/ontology/0001/anything/v2#Nothing", "UTF-8") + val classSegment = URLEncoder.encode("http://0.0.0.0:3333/ontology/0001/anything/v2#Nothing", "UTF-8") val lastModificationDate = URLEncoder.encode(anythingLastModDate.toString, "UTF-8") Delete(s"/v2/ontologies/classes/$classSegment?lastModificationDate=$lastModificationDate") ~> addCredentials( @@ -2235,8 +2235,8 @@ class OntologyV2R2RSpec extends R2RSpec { ) ~> ontologiesPath ~> check { assert(status == StatusCodes.OK, response.toString) val responseJsonDoc = responseToJsonLDDocument(response) - val metadata = responseJsonDoc.body - val ontologyIri = metadata.value("@id").asInstanceOf[JsonLDString].value + val metadata = responseJsonDoc.body + val ontologyIri = metadata.value("@id").asInstanceOf[JsonLDString].value assert(ontologyIri == "http://api.knora.org/ontology/shared/useless/v2") uselessIri.set(ontologyIri) assert(metadata.value(OntologyConstants.Rdfs.Label) == JsonLDString(label)) diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v2/ProjectHeader.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v2/ProjectHeader.scala index aed2b15cb8..4648e4c6a0 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v2/ProjectHeader.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v2/ProjectHeader.scala @@ -17,13 +17,13 @@ import scala.util.Try * The definition follows [[https://doc.akka.io/docs/akka-http/current/common/http-model.html#custom-headers]]. */ class ProjectHeader(token: String) extends ModeledCustomHeader[ProjectHeader] { - override def renderInRequests = true - override def renderInResponses = true + override def renderInRequests = true + override def renderInResponses = true override val companion: ProjectHeader.type = ProjectHeader - override def value: String = token + override def value: String = token } object ProjectHeader extends ModeledCustomHeaderCompanion[ProjectHeader] { - override val name: String = RouteUtilV2.PROJECT_HEADER + override val name: String = RouteUtilV2.PROJECT_HEADER override def parse(value: String) = Try(new ProjectHeader(value)) } diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v2/ResourcesRouteV2E2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v2/ResourcesRouteV2E2ESpec.scala index 1eee6f0290..ff358e1245 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v2/ResourcesRouteV2E2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v2/ResourcesRouteV2E2ESpec.scala @@ -45,14 +45,14 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { implicit val ec: ExecutionContextExecutor = system.dispatcher - private val anythingUserEmail = SharedTestDataADM.anythingUser1.email - private val password = SharedTestDataADM.testPass - private var aThingLastModificationDate = Instant.now - private val hamletResourceIri = new MutableTestIri - private val aThingIri = "http://rdfh.ch/0001/a-thing" - private val aThingIriEncoded = URLEncoder.encode(aThingIri, "UTF-8") - private val aThingWithHistoryIri = "http://rdfh.ch/0001/thing-with-history" - private val aThingWithHistoryIriEncoded = URLEncoder.encode(aThingWithHistoryIri, "UTF-8") + private val anythingUserEmail = SharedTestDataADM.anythingUser1.email + private val password = SharedTestDataADM.testPass + private var aThingLastModificationDate = Instant.now + private val hamletResourceIri = new MutableTestIri + private val aThingIri = "http://rdfh.ch/0001/a-thing" + private val aThingIriEncoded = URLEncoder.encode(aThingIri, "UTF-8") + private val aThingWithHistoryIri = "http://rdfh.ch/0001/thing-with-history" + private val aThingWithHistoryIriEncoded = URLEncoder.encode(aThingWithHistoryIri, "UTF-8") private val reiseInsHeiligeLandIriEncoded = URLEncoder.encode("http://rdfh.ch/0803/2a6221216701", "UTF-8") // If true, writes all API responses to test data files. If false, compares the API responses to the existing test data files. @@ -109,9 +109,9 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { "The resources v2 endpoint" should { "perform a resource request for the book 'Reise ins Heilige Land' using the complex schema in JSON-LD" in { - val request = Get(s"$baseApiUrl/v2/resources/$reiseInsHeiligeLandIriEncoded") + val request = Get(s"$baseApiUrl/v2/resources/$reiseInsHeiligeLandIriEncoded") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = @@ -141,7 +141,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { val request = Get(s"$baseApiUrl/v2/resources/$reiseInsHeiligeLandIriEncoded") .addHeader(acceptHeader) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerTurtle = readOrWriteTextFile( responseAsString, @@ -155,7 +155,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { val request = Get(s"$baseApiUrl/v2/resources/$reiseInsHeiligeLandIriEncoded") .addHeader(Accept(RdfMediaTypes.`application/rdf+xml`)) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerRdfXml = readOrWriteTextFile( responseAsString, @@ -166,9 +166,9 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "perform a resource preview request for the book 'Reise ins Heilige Land' using the complex schema" in { - val request = Get(s"$baseApiUrl/v2/resourcespreview/$reiseInsHeiligeLandIriEncoded") + val request = Get(s"$baseApiUrl/v2/resourcespreview/$reiseInsHeiligeLandIriEncoded") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( @@ -180,9 +180,9 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "perform a resource preview request for a Thing resource using the complex schema" in { - val request = Get(s"$baseApiUrl/v2/resourcespreview/$aThingIriEncoded") + val request = Get(s"$baseApiUrl/v2/resourcespreview/$aThingIriEncoded") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( @@ -208,7 +208,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { val request = Get(s"$baseApiUrl/v2/resources/$reiseInsHeiligeLandIriEncoded") .addHeader(new SchemaHeader(RouteUtilV2.SIMPLE_SCHEMA_NAME)) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( @@ -231,7 +231,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { .addHeader(new SchemaHeader(RouteUtilV2.SIMPLE_SCHEMA_NAME)) .addHeader(Accept(RdfMediaTypes.`text/turtle`)) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerTurtle = readOrWriteTextFile( @@ -247,7 +247,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { .addHeader(new SchemaHeader(RouteUtilV2.SIMPLE_SCHEMA_NAME)) .addHeader(Accept(RdfMediaTypes.`application/rdf+xml`)) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerRdfXml = readOrWriteTextFile( @@ -262,7 +262,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { val request = Get(s"$baseApiUrl/v2/resourcespreview/$reiseInsHeiligeLandIriEncoded") .addHeader(new SchemaHeader(RouteUtilV2.SIMPLE_SCHEMA_NAME)) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( @@ -278,7 +278,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { s"$baseApiUrl/v2/resources/$reiseInsHeiligeLandIriEncoded?${RouteUtilV2.SCHEMA_PARAM}=${RouteUtilV2.SIMPLE_SCHEMA_NAME}" ) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( @@ -290,10 +290,10 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "perform a resource request for the first page of the book '[Das] Narrenschiff (lat.)' using the complex schema" in { - val iri = URLEncoder.encode("http://rdfh.ch/0803/7bbb8e59b703", "UTF-8") - val request = Get(s"$baseApiUrl/v2/resources/$iri") + val iri = URLEncoder.encode("http://rdfh.ch/0803/7bbb8e59b703", "UTF-8") + val request = Get(s"$baseApiUrl/v2/resources/$iri") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( responseAsString, @@ -304,10 +304,10 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "perform a full resource request for a resource with a BCE date property" in { - val iri = URLEncoder.encode("http://rdfh.ch/0001/thing_with_BCE_date", "UTF-8") - val request = Get(s"$baseApiUrl/v2/resources/$iri") + val iri = URLEncoder.encode("http://rdfh.ch/0001/thing_with_BCE_date", "UTF-8") + val request = Get(s"$baseApiUrl/v2/resources/$iri") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( responseAsString, @@ -325,10 +325,10 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "perform a full resource request for a resource with a date property that represents a period going from BCE to CE" in { - val iri = URLEncoder.encode("http://rdfh.ch/0001/thing_with_BCE_date2", "UTF-8") - val request = Get(s"$baseApiUrl/v2/resources/$iri") + val iri = URLEncoder.encode("http://rdfh.ch/0001/thing_with_BCE_date2", "UTF-8") + val request = Get(s"$baseApiUrl/v2/resources/$iri") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( responseAsString, @@ -346,10 +346,10 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "perform a full resource request for a resource with a list value" in { - val iri = URLEncoder.encode("http://rdfh.ch/0001/thing_with_list_value", "UTF-8") - val request = Get(s"$baseApiUrl/v2/resources/$iri") + val iri = URLEncoder.encode("http://rdfh.ch/0001/thing_with_list_value", "UTF-8") + val request = Get(s"$baseApiUrl/v2/resources/$iri") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( responseAsString, @@ -371,7 +371,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { val request = Get(s"$baseApiUrl/v2/resources/$iri") .addHeader(new SchemaHeader(RouteUtilV2.SIMPLE_SCHEMA_NAME)) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( @@ -390,10 +390,10 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "perform a full resource request for a resource with a link (in the complex schema)" in { - val iri = URLEncoder.encode("http://rdfh.ch/0001/0C-0L1kORryKzJAJxxRyRQ", "UTF-8") - val request = Get(s"$baseApiUrl/v2/resources/$iri") + val iri = URLEncoder.encode("http://rdfh.ch/0001/0C-0L1kORryKzJAJxxRyRQ", "UTF-8") + val request = Get(s"$baseApiUrl/v2/resources/$iri") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( responseAsString, @@ -415,7 +415,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { val request = Get(s"$baseApiUrl/v2/resources/$iri") .addHeader(new SchemaHeader(RouteUtilV2.SIMPLE_SCHEMA_NAME)) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( responseAsString, @@ -433,10 +433,10 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "perform a full resource request for a resource with a Text language (in the complex schema)" in { - val iri = URLEncoder.encode("http://rdfh.ch/0001/a-thing-with-text-valuesLanguage", "UTF-8") - val request = Get(s"$baseApiUrl/v2/resources/$iri") + val iri = URLEncoder.encode("http://rdfh.ch/0001/a-thing-with-text-valuesLanguage", "UTF-8") + val request = Get(s"$baseApiUrl/v2/resources/$iri") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( @@ -459,7 +459,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { val request = Get(s"$baseApiUrl/v2/resources/$iri") .addHeader(new SchemaHeader(RouteUtilV2.SIMPLE_SCHEMA_NAME)) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( @@ -478,10 +478,10 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "perform a full resource request for a resource with values of different types" in { - val iri = URLEncoder.encode("http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw", "UTF-8") - val request = Get(s"$baseApiUrl/v2/resources/$iri") + val iri = URLEncoder.encode("http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw", "UTF-8") + val request = Get(s"$baseApiUrl/v2/resources/$iri") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( @@ -511,10 +511,10 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "perform a full resource request for a Thing resource with a link to a ThingPicture resource" in { - val iri = URLEncoder.encode("http://rdfh.ch/0001/a-thing-with-picture", "UTF-8") - val request = Get(s"$baseApiUrl/v2/resources/$iri") + val iri = URLEncoder.encode("http://rdfh.ch/0001/a-thing-with-picture", "UTF-8") + val request = Get(s"$baseApiUrl/v2/resources/$iri") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( responseAsString, @@ -543,10 +543,10 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "perform a full resource request with a link to a resource that the user doesn't have permission to see" in { - val iri = URLEncoder.encode("http://rdfh.ch/0001/0JhgKcqoRIeRRG6ownArSw", "UTF-8") - val request = Get(s"$baseApiUrl/v2/resources/$iri") + val iri = URLEncoder.encode("http://rdfh.ch/0001/0JhgKcqoRIeRRG6ownArSw", "UTF-8") + val request = Get(s"$baseApiUrl/v2/resources/$iri") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( @@ -565,10 +565,10 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "perform a full resource request with a link to a resource that is marked as deleted" in { - val iri = URLEncoder.encode("http://rdfh.ch/0001/l8f8FVEiSCeq9A1p8gBR-A", "UTF-8") - val request = Get(s"$baseApiUrl/v2/resources/$iri") + val iri = URLEncoder.encode("http://rdfh.ch/0001/l8f8FVEiSCeq9A1p8gBR-A", "UTF-8") + val request = Get(s"$baseApiUrl/v2/resources/$iri") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( @@ -587,10 +587,10 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "perform a full resource request for a past version of a resource, using a URL-encoded xsd:dateTimeStamp" in { - val timestamp = URLEncoder.encode("2019-02-12T08:05:10.351Z", "UTF-8") - val request = Get(s"$baseApiUrl/v2/resources/$aThingWithHistoryIriEncoded?version=$timestamp") + val timestamp = URLEncoder.encode("2019-02-12T08:05:10.351Z", "UTF-8") + val request = Get(s"$baseApiUrl/v2/resources/$aThingWithHistoryIriEncoded?version=$timestamp") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( @@ -602,10 +602,10 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "perform a full resource request for a past version of a resource, using a Knora ARK timestamp" in { - val timestamp = URLEncoder.encode("20190212T080510351Z", "UTF-8") - val request = Get(s"$baseApiUrl/v2/resources/$aThingWithHistoryIriEncoded?version=$timestamp") + val timestamp = URLEncoder.encode("20190212T080510351Z", "UTF-8") + val request = Get(s"$baseApiUrl/v2/resources/$aThingWithHistoryIriEncoded?version=$timestamp") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( @@ -617,9 +617,9 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "return the complete version history of a resource" in { - val request = Get(s"$baseApiUrl/v2/resources/history/$aThingWithHistoryIriEncoded") + val request = Get(s"$baseApiUrl/v2/resources/history/$aThingWithHistoryIriEncoded") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( @@ -632,11 +632,11 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { "return the version history of a resource within a date range" in { val startDate = URLEncoder.encode(Instant.parse("2019-02-08T15:05:11Z").toString, "UTF-8") - val endDate = URLEncoder.encode(Instant.parse("2019-02-13T09:05:10Z").toString, "UTF-8") + val endDate = URLEncoder.encode(Instant.parse("2019-02-13T09:05:10Z").toString, "UTF-8") val request = Get(s"$baseApiUrl/v2/resources/history/$aThingWithHistoryIriEncoded?startDate=$startDate&endDate=$endDate") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( responseAsString, @@ -647,12 +647,12 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "return each of the versions of a resource listed in its version history" in { - val historyRequest = Get(s"$baseApiUrl/v2/resources/history/$aThingWithHistoryIriEncoded") + val historyRequest = Get(s"$baseApiUrl/v2/resources/history/$aThingWithHistoryIriEncoded") val historyResponse: HttpResponse = singleAwaitingRequest(historyRequest) - val historyResponseAsString = responseToString(historyResponse) + val historyResponseAsString = responseToString(historyResponse) assert(historyResponse.status == StatusCodes.OK, historyResponseAsString) val jsonLDDocument: JsonLDDocument = JsonLDUtil.parseJsonLD(historyResponseAsString) - val entries: JsonLDArray = jsonLDDocument.requireArray("@graph") + val entries: JsonLDArray = jsonLDDocument.requireArray("@graph") for (entry: JsonLDValue <- entries.value) { entry match { @@ -663,10 +663,10 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { validationFun = stringFormatter.xsdDateTimeStampToInstant ) - val arkTimestamp = stringFormatter.formatArkTimestamp(versionDate) - val versionRequest = Get(s"$baseApiUrl/v2/resources/$aThingWithHistoryIriEncoded?version=$arkTimestamp") + val arkTimestamp = stringFormatter.formatArkTimestamp(versionDate) + val versionRequest = Get(s"$baseApiUrl/v2/resources/$aThingWithHistoryIriEncoded?version=$arkTimestamp") val versionResponse: HttpResponse = singleAwaitingRequest(versionRequest) - val versionResponseAsString = responseToString(versionResponse) + val versionResponseAsString = responseToString(versionResponse) assert(versionResponse.status == StatusCodes.OK, versionResponseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( @@ -689,7 +689,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { val resourceHistoryRequest = Get(s"$baseApiUrl/v2/resources/resourceHistoryEvents/$resourceIri") .addCredentials(BasicHttpCredentials(SharedTestDataADM.anythingAdminUser.email, password)) val resourceHistoryResponse: HttpResponse = singleAwaitingRequest(resourceHistoryRequest) - val historyResponseAsString = responseToString(resourceHistoryResponse) + val historyResponseAsString = responseToString(resourceHistoryResponse) assert(resourceHistoryResponse.status == StatusCodes.OK, historyResponseAsString) } @@ -698,7 +698,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { val projectHistoryRequest = Get(s"$baseApiUrl/v2/resources/projectHistoryEvents/$projectIri") .addCredentials(BasicHttpCredentials(SharedTestDataADM.anythingAdminUser.email, password)) val projectHistoryResponse: HttpResponse = singleAwaitingRequest(projectHistoryRequest) - val historyResponseAsString = responseToString(projectHistoryResponse) + val historyResponseAsString = responseToString(projectHistoryResponse) assert(projectHistoryResponse.status == StatusCodes.OK, historyResponseAsString) } @@ -706,7 +706,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { val request = Get(s"$baseApiUrl/v2/graph/${URLEncoder.encode("http://rdfh.ch/0001/start", "UTF-8")}?direction=both") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) clientTestDataCollector.addFile( TestDataFileContent( @@ -736,7 +736,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { val request = Get(s"$baseApiUrl/v2/graph/${URLEncoder.encode("http://rdfh.ch/0001/start", "UTF-8")}?direction=outbound") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val parsedReceivedJsonLD = JsonLDUtil.parseJsonLD(responseAsString) @@ -754,7 +754,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { val request = Get(s"$baseApiUrl/v2/graph/${URLEncoder.encode("http://rdfh.ch/0001/start", "UTF-8")}?direction=inbound") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val parsedReceivedJsonLD = JsonLDUtil.parseJsonLD(responseAsString) @@ -774,7 +774,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { .encode("http://0.0.0.0:3333/ontology/0001/anything/v2#isPartOfOtherThing", "UTF-8")}" ) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val parsedReceivedJsonLD = JsonLDUtil.parseJsonLD(responseAsString) @@ -793,7 +793,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { val request = Get(s"$baseApiUrl/v2/graph/${URLEncoder.encode("http://rdfh.ch/0001/start", "UTF-8")}?direction=both&depth=2") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val parsedReceivedJsonLD = JsonLDUtil.parseJsonLD(responseAsString) @@ -812,14 +812,14 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { val request = Get(s"$baseApiUrl/v2/graph/${URLEncoder.encode("http://rdfh.ch/0001/start", "UTF-8")}?direction=foo") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.BadRequest, responseAsString) } "not accept a graph request with an invalid depth (< 1)" in { - val request = Get(s"$baseApiUrl/v2/graph/${URLEncoder.encode("http://rdfh.ch/0001/start", "UTF-8")}?depth=0") + val request = Get(s"$baseApiUrl/v2/graph/${URLEncoder.encode("http://rdfh.ch/0001/start", "UTF-8")}?depth=0") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.BadRequest, responseAsString) } @@ -828,7 +828,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { s"$baseApiUrl/v2/graph/${URLEncoder.encode("http://rdfh.ch/0001/start", "UTF-8")}?depth=${settings.maxGraphBreadth + 1}" ) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.BadRequest, responseAsString) } @@ -836,12 +836,12 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { val request = Get(s"$baseApiUrl/v2/graph/${URLEncoder.encode("http://rdfh.ch/0001/start", "UTF-8")}?excludeProperty=foo") val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.BadRequest, responseAsString) } "return resources from a project" in { - val resourceClass = URLEncoder.encode("http://0.0.0.0:3333/ontology/0803/incunabula/v2#book", "UTF-8") + val resourceClass = URLEncoder.encode("http://0.0.0.0:3333/ontology/0803/incunabula/v2#book", "UTF-8") val orderByProperty = URLEncoder.encode("http://0.0.0.0:3333/ontology/0803/incunabula/v2#title", "UTF-8") val request = Get(s"$baseApiUrl/v2/resources?resourceClass=$resourceClass&orderByProperty=$orderByProperty&page=0") @@ -849,7 +849,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { BasicHttpCredentials(SharedTestDataADM.incunabulaProjectAdminUser.email, password) ) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.OK, responseAsString) val expectedAnswerJSONLD = readOrWriteTextFile( responseAsString, @@ -991,7 +991,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { s"$baseApiUrl/v2/resources/${URLEncoder.encode(resourceIri, "UTF-8")}" ) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password)) val resourceComplexGetResponse: HttpResponse = singleAwaitingRequest(resourceComplexGetRequest) - val resourceComplexGetResponseAsString = responseToString(resourceComplexGetResponse) + val resourceComplexGetResponseAsString = responseToString(resourceComplexGetResponse) instanceChecker.check( instanceResponse = resourceComplexGetResponseAsString, @@ -1005,7 +1005,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { BasicHttpCredentials(anythingUserEmail, password) ) val resourceSimpleGetResponse: HttpResponse = singleAwaitingRequest(resourceSimpleGetRequest) - val resourceSimpleGetResponseAsString = responseToString(resourceSimpleGetResponse) + val resourceSimpleGetResponseAsString = responseToString(resourceSimpleGetResponse) instanceChecker.check( instanceResponse = resourceSimpleGetResponseAsString, @@ -1057,7 +1057,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { s"$baseApiUrl/v2/resources/${URLEncoder.encode(resourceIri, "UTF-8")}" ) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password)) val resourceComplexGetResponse: HttpResponse = singleAwaitingRequest(resourceComplexGetRequest) - val resourceComplexGetResponseAsString = responseToString(resourceComplexGetResponse) + val resourceComplexGetResponseAsString = responseToString(resourceComplexGetResponse) instanceChecker.check( instanceResponse = resourceComplexGetResponseAsString, @@ -1071,7 +1071,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { BasicHttpCredentials(anythingUserEmail, password) ) val resourceSimpleGetResponse: HttpResponse = singleAwaitingRequest(resourceSimpleGetRequest) - val resourceSimpleGetResponseAsString = responseToString(resourceSimpleGetResponse) + val resourceSimpleGetResponseAsString = responseToString(resourceSimpleGetResponse) instanceChecker.check( instanceResponse = resourceSimpleGetResponseAsString, @@ -1184,7 +1184,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { "create a resource with a custom IRI" in { val customIRI: IRI = SharedTestDataADM.customResourceIRI - val jsonLDEntity = createResourceWithCustomIRI(customIRI) + val jsonLDEntity = createResourceWithCustomIRI(customIRI) clientTestDataCollector.addFile( TestDataFileContent( @@ -1211,7 +1211,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { "not create a resource with an invalid custom IRI" in { val customIRI: IRI = "http://rdfh.ch/invalid-resource-IRI" - val jsonLDEntity = createResourceWithCustomIRI(customIRI) + val jsonLDEntity = createResourceWithCustomIRI(customIRI) val request = Post( s"$baseApiUrl/v2/resources", HttpEntity(RdfMediaTypes.`application/ld+json`, jsonLDEntity) @@ -1223,7 +1223,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { "not create a resource with a custom IRI containing the wrong project code" in { val customIRI: IRI = "http://rdfh.ch/0803/a-thing-with-IRI" - val jsonLDEntity = createResourceWithCustomIRI(customIRI) + val jsonLDEntity = createResourceWithCustomIRI(customIRI) val request = Post( s"$baseApiUrl/v2/resources", HttpEntity(RdfMediaTypes.`application/ld+json`, jsonLDEntity) @@ -1293,7 +1293,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { "create a resource with random IRI and a custom value IRI" in { val customValueIRI: IRI = SharedTestDataADM.customValueIRI - val jsonLDEntity = createResourceWithCustomValueIRI(customValueIRI) + val jsonLDEntity = createResourceWithCustomValueIRI(customValueIRI) clientTestDataCollector.addFile( TestDataFileContent( @@ -1464,10 +1464,10 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "create a resource with custom resource IRI, creation date, and a value with custom value IRI and UUID" in { - val customResourceIRI: IRI = SharedTestDataADM.customResourceIRI_resourceWithValues + val customResourceIRI: IRI = SharedTestDataADM.customResourceIRI_resourceWithValues val customCreationDate: Instant = Instant.parse("2019-01-09T15:45:54.502951Z") - val customValueIRI: IRI = SharedTestDataADM.customValueIRI_withResourceIriAndValueIRIAndValueUUID - val customValueUUID = SharedTestDataADM.customValueUUID + val customValueIRI: IRI = SharedTestDataADM.customValueIRI_withResourceIriAndValueIRIAndValueUUID + val customValueUUID = SharedTestDataADM.customValueUUID val jsonLDEntity = s"""{ @@ -1641,7 +1641,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { HttpEntity(RdfMediaTypes.`application/ld+json`, jsonLDEntity) ) ~> addCredentials(BasicHttpCredentials(SharedTestDataADM.anythingUser2.email, password)) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.Forbidden, responseAsString) } @@ -1661,8 +1661,8 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "update the metadata of a resource" in { - val newLabel = "test thing with modified label" - val newPermissions = "CR knora-admin:Creator|M knora-admin:ProjectMember|V knora-admin:ProjectMember" + val newLabel = "test thing with modified label" + val newPermissions = "CR knora-admin:Creator|M knora-admin:ProjectMember|V knora-admin:ProjectMember" val newModificationDate = Instant.now.plus(java.time.Duration.ofDays(1)) val jsonLDEntity = @@ -1699,7 +1699,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { s"$baseApiUrl/v2/resources", HttpEntity(RdfMediaTypes.`application/ld+json`, jsonLDEntity) ) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password)) - val updateResponse: HttpResponse = singleAwaitingRequest(updateRequest) + val updateResponse: HttpResponse = singleAwaitingRequest(updateRequest) val updateResponseAsString: String = responseToString(updateResponse) assert(updateResponse.status == StatusCodes.OK, updateResponseAsString) assert( @@ -1728,10 +1728,10 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { s"$baseApiUrl/v2/resourcespreview/$aThingIriEncoded" ) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password)) val previewResponse: HttpResponse = singleAwaitingRequest(previewRequest) - val previewResponseAsString = responseToString(previewResponse) + val previewResponseAsString = responseToString(previewResponse) assert(previewResponse.status == StatusCodes.OK, previewResponseAsString) - val previewJsonLD = JsonLDUtil.parseJsonLD(previewResponseAsString) + val previewJsonLD = JsonLDUtil.parseJsonLD(previewResponseAsString) val updatedLabel: String = previewJsonLD.requireString(OntologyConstants.Rdfs.Label) assert(updatedLabel == newLabel) val updatedPermissions: String = previewJsonLD.requireString(OntologyConstants.KnoraApiV2Complex.HasPermissions) @@ -1750,8 +1750,8 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "update the metadata of a resource that has a last modification date" in { - val newLabel = "test thing with modified label again" - val newPermissions = "CR knora-admin:ProjectMember|V knora-admin:ProjectMember" + val newLabel = "test thing with modified label again" + val newPermissions = "CR knora-admin:ProjectMember|V knora-admin:ProjectMember" val newModificationDate = Instant.now.plus(java.time.Duration.ofDays(1)) val jsonLDEntity = @@ -1792,7 +1792,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { s"$baseApiUrl/v2/resources", HttpEntity(RdfMediaTypes.`application/ld+json`, jsonLDEntity) ) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password)) - val updateResponse: HttpResponse = singleAwaitingRequest(updateRequest) + val updateResponse: HttpResponse = singleAwaitingRequest(updateRequest) val updateResponseAsString: String = responseToString(updateResponse) assert(updateResponse.status == StatusCodes.OK, updateResponseAsString) assert( @@ -1821,10 +1821,10 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { s"$baseApiUrl/v2/resourcespreview/$aThingIriEncoded" ) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password)) val previewResponse: HttpResponse = singleAwaitingRequest(previewRequest) - val previewResponseAsString = responseToString(previewResponse) + val previewResponseAsString = responseToString(previewResponse) assert(previewResponse.status == StatusCodes.OK, previewResponseAsString) - val previewJsonLD = JsonLDUtil.parseJsonLD(previewResponseAsString) + val previewJsonLD = JsonLDUtil.parseJsonLD(previewResponseAsString) val updatedLabel: String = previewJsonLD.requireString(OntologyConstants.Rdfs.Label) assert(updatedLabel == newLabel) val updatedPermissions: String = previewJsonLD.requireString(OntologyConstants.KnoraApiV2Complex.HasPermissions) @@ -1876,7 +1876,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { s"$baseApiUrl/v2/resources/delete", HttpEntity(RdfMediaTypes.`application/ld+json`, jsonLDEntity) ) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password)) - val updateResponse: HttpResponse = singleAwaitingRequest(updateRequest) + val updateResponse: HttpResponse = singleAwaitingRequest(updateRequest) val updateResponseAsString: String = responseToString(updateResponse) assert(updateResponse.status == StatusCodes.OK, updateResponseAsString) assert(JsonParser(updateResponseAsString) == JsonParser(successResponse("Resource marked as deleted"))) @@ -1899,8 +1899,8 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { previewResponse.status should equal(StatusCodes.OK) val previewResponseAsString = responseToString(previewResponse) - val previewJsonLD = JsonLDUtil.parseJsonLD(previewResponseAsString) - val responseIsDeleted = previewJsonLD.requireBoolean(OntologyConstants.KnoraApiV2Complex.IsDeleted) + val previewJsonLD = JsonLDUtil.parseJsonLD(previewResponseAsString) + val responseIsDeleted = previewJsonLD.requireBoolean(OntologyConstants.KnoraApiV2Complex.IsDeleted) responseIsDeleted should equal(true) val responseType = previewJsonLD.requireString("@type") responseType should equal(OntologyConstants.KnoraApiV2Complex.DeletedResource) @@ -1919,7 +1919,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { "mark a resource as deleted, supplying a custom delete date" in { val resourceIri = "http://rdfh.ch/0001/5IEswyQFQp2bxXDrOyEfEA" - val deleteDate = Instant.now + val deleteDate = Instant.now val jsonLDEntity = s"""|{ @@ -1954,7 +1954,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { s"$baseApiUrl/v2/resources/delete", HttpEntity(RdfMediaTypes.`application/ld+json`, jsonLDEntity) ) ~> addCredentials(BasicHttpCredentials(SharedTestDataADM.superUser.email, password)) - val updateResponse: HttpResponse = singleAwaitingRequest(updateRequest) + val updateResponse: HttpResponse = singleAwaitingRequest(updateRequest) val updateResponseAsString: String = responseToString(updateResponse) assert(updateResponse.status == StatusCodes.OK, updateResponseAsString) assert(JsonParser(updateResponseAsString) == JsonParser(successResponse("Resource marked as deleted"))) @@ -1963,10 +1963,10 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { s"$baseApiUrl/v2/resourcespreview/${URLEncoder.encode(resourceIri, "UTF-8")}" ) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password)) val previewResponse: HttpResponse = singleAwaitingRequest(previewRequest) - val previewResponseAsString = responseToString(previewResponse) + val previewResponseAsString = responseToString(previewResponse) previewResponse.status should equal(StatusCodes.OK) - val previewJsonLD = JsonLDUtil.parseJsonLD(previewResponseAsString) + val previewJsonLD = JsonLDUtil.parseJsonLD(previewResponseAsString) val responseIsDeleted = previewJsonLD.requireBoolean(OntologyConstants.KnoraApiV2Complex.IsDeleted) responseIsDeleted should equal(true) val responseType = previewJsonLD.requireString("@type") @@ -2060,7 +2060,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { BasicHttpCredentials(anythingUserEmail, password) ) val resourceGetResponse: HttpResponse = singleAwaitingRequest(resourceGetRequest) - val resourceGetResponseAsString = responseToString(resourceGetResponse) + val resourceGetResponseAsString = responseToString(resourceGetResponse) // Check that the response matches the ontology. instanceChecker.check( @@ -2079,12 +2079,12 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { val textValueIri: IRI = textValue.requireStringWithValidation(JsonLDKeywords.ID, stringFormatter.validateAndEscapeIri) - val resourceIriEncoded: IRI = URLEncoder.encode(hamletResourceIri.get, "UTF-8") + val resourceIriEncoded: IRI = URLEncoder.encode(hamletResourceIri.get, "UTF-8") val textValueIriEncoded: IRI = URLEncoder.encode(textValueIri, "UTF-8") val standoffBuffer: ArrayBuffer[JsonLDObject] = ArrayBuffer.empty - var offset: Int = 0 - var hasMoreStandoff: Boolean = true + var offset: Int = 0 + var hasMoreStandoff: Boolean = true while (hasMoreStandoff) { // Get a page of standoff. @@ -2092,7 +2092,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { val standoffGetRequest = Get( s"$baseApiUrl/v2/standoff/$resourceIriEncoded/$textValueIriEncoded/$offset" ) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password)) - val standoffGetResponse: HttpResponse = singleAwaitingRequest(standoffGetRequest) + val standoffGetResponse: HttpResponse = singleAwaitingRequest(standoffGetRequest) val standoffGetResponseAsJsonLD: JsonLDObject = responseToJsonLDDocument(standoffGetResponse).body val standoff: Seq[JsonLDValue] = @@ -2163,14 +2163,14 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { HttpEntity(RdfMediaTypes.`application/ld+json`, jsonLDEntity) ) ~> addCredentials(BasicHttpCredentials(SharedTestDataADM.anythingAdminUser.email, password)) val updateResponse: HttpResponse = singleAwaitingRequest(updateRequest) - val updateResponseAsString = responseToString(updateResponse) + val updateResponseAsString = responseToString(updateResponse) assert(updateResponse.status == StatusCodes.OK, updateResponseAsString) val previewRequest = Get( s"$baseApiUrl/v2/resourcespreview/$aThingWithHistoryIriEncoded" ) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password)) val previewResponse: HttpResponse = singleAwaitingRequest(previewRequest) - val previewResponseAsString = responseToString(previewResponse) + val previewResponseAsString = responseToString(previewResponse) assert(previewResponse.status == StatusCodes.NotFound, previewResponseAsString) } @@ -2213,7 +2213,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { s"$baseApiUrl/v2/resources/${URLEncoder.encode(resourceIri, "UTF-8")}" ) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password)) val resourceComplexGetResponse: HttpResponse = singleAwaitingRequest(resourceComplexGetRequest) - val resourceComplexGetResponseAsString = responseToString(resourceComplexGetResponse) + val resourceComplexGetResponseAsString = responseToString(resourceComplexGetResponse) instanceChecker.check( instanceResponse = resourceComplexGetResponseAsString, @@ -2265,7 +2265,7 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { s"$baseApiUrl/v2/resources/${URLEncoder.encode(resourceIri, "UTF-8")}" ) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password)) val resourceComplexGetResponse: HttpResponse = singleAwaitingRequest(resourceComplexGetRequest) - val resourceComplexGetResponseAsString = responseToString(resourceComplexGetResponse) + val resourceComplexGetResponseAsString = responseToString(resourceComplexGetResponse) // Check that it has multiple property knora-api:hasStandoffLinkToValue. val resourceJsonLDDoc: JsonLDDocument = JsonLDUtil.parseJsonLD(resourceComplexGetResponseAsString) @@ -2278,10 +2278,10 @@ class ResourcesRouteV2E2ESpec extends E2ESpec(ResourcesRouteV2E2ESpec.config) { } "return a IIIF manifest for the pages of a book" in { - val resourceIri = "http://rdfh.ch/0001/thing-with-pages" - val request = Get(s"$baseApiUrl/v2/resources/iiifmanifest/${URLEncoder.encode(resourceIri, "UTF-8")}") + val resourceIri = "http://rdfh.ch/0001/thing-with-pages" + val request = Get(s"$baseApiUrl/v2/resources/iiifmanifest/${URLEncoder.encode(resourceIri, "UTF-8")}") val response: HttpResponse = singleAwaitingRequest(request) - val responseStr: String = responseToString(response) + val responseStr: String = responseToString(response) assert(response.status == StatusCodes.OK, responseStr) val responseJson: JsValue = JsonParser(responseStr) diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v2/ResponseCheckerV2Spec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v2/ResponseCheckerV2Spec.scala index 46e07f2f4e..cd1d4ea05b 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v2/ResponseCheckerV2Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v2/ResponseCheckerV2Spec.scala @@ -39,7 +39,8 @@ class ResponseCheckerV2Spec extends CoreSpec() { "throw an exception if received and expected resource responses are different" in { val expectedAnswerJSONLD = FileUtil.readTextFile(Paths.get("..", "test_data/resourcesR2RV2/ThingWithLinkComplex.jsonld")) - val receivedAnswerJSONLD = FileUtil.readTextFile(Paths.get("..", "test_data/resourcesR2RV2/ThingWithListValue.jsonld")) + val receivedAnswerJSONLD = + FileUtil.readTextFile(Paths.get("..", "test_data/resourcesR2RV2/ThingWithListValue.jsonld")) assertThrows[AssertionError] { ResponseCheckerV2.compareJSONLDForResourcesResponse( @@ -82,7 +83,9 @@ class ResponseCheckerV2Spec extends CoreSpec() { val expectedAnswerJSONLD = FileUtil.readTextFile(Paths.get("..", "test_data/standoffR2RV2/mappingCreationResponse.jsonld")) val receivedAnswerJSONLD = - FileUtil.readTextFile(Paths.get("..", "test_data/standoffR2RV2/mappingCreationResponseWithDifferentLabel.jsonld")) + FileUtil.readTextFile( + Paths.get("..", "test_data/standoffR2RV2/mappingCreationResponseWithDifferentLabel.jsonld") + ) assertThrows[AssertionError] { ResponseCheckerV2.compareJSONLDForMappingCreationResponse( diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v2/SchemaHeader.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v2/SchemaHeader.scala index 3ee5c5b893..ea9160a4b5 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v2/SchemaHeader.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v2/SchemaHeader.scala @@ -17,13 +17,13 @@ import scala.util.Try * The definition follows [[https://doc.akka.io/docs/akka-http/current/common/http-model.html#custom-headers]]. */ final class SchemaHeader(token: String) extends ModeledCustomHeader[SchemaHeader] { - override def renderInRequests = true - override def renderInResponses = true + override def renderInRequests = true + override def renderInResponses = true override val companion: SchemaHeader.type = SchemaHeader - override def value: String = token + override def value: String = token } object SchemaHeader extends ModeledCustomHeaderCompanion[SchemaHeader] { - override val name: String = RouteUtilV2.SCHEMA_HEADER + override val name: String = RouteUtilV2.SCHEMA_HEADER override def parse(value: String) = Try(new SchemaHeader(value)) } diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v2/SearchRouteV2R2RSpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v2/SearchRouteV2R2RSpec.scala index db02973a28..b061de6d78 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v2/SearchRouteV2R2RSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v2/SearchRouteV2R2RSpec.scala @@ -46,25 +46,25 @@ class SearchRouteV2R2RSpec extends R2RSpec { |# akka.stdout-loglevel = "DEBUG" """.stripMargin - private val searchPath = DSPApiDirectives.handleErrors(system)(new SearchRouteV2(routeData).knoraApiPath) + private val searchPath = DSPApiDirectives.handleErrors(system)(new SearchRouteV2(routeData).knoraApiPath) private val resourcePath = DSPApiDirectives.handleErrors(system)(new ResourcesRouteV2(routeData).knoraApiPath) private val standoffPath = DSPApiDirectives.handleErrors(system)(new StandoffRouteV2(routeData).knoraApiPath) - private val valuesPath = DSPApiDirectives.handleErrors(system)(new ValuesRouteV1(routeData).knoraApiPath) + private val valuesPath = DSPApiDirectives.handleErrors(system)(new ValuesRouteV1(routeData).knoraApiPath) implicit def default(implicit system: ActorSystem): RouteTestTimeout = RouteTestTimeout(settings.defaultTimeout) implicit val ec: ExecutionContextExecutor = system.dispatcher - private val anythingUser = SharedTestDataADM.anythingUser1 - private val anythingUserEmail = anythingUser.email + private val anythingUser = SharedTestDataADM.anythingUser1 + private val anythingUserEmail = anythingUser.email private val anythingProjectIri = SharedTestDataADM.ANYTHING_PROJECT_IRI - private val incunabulaUser = SharedTestDataADM.incunabulaMemberUser + private val incunabulaUser = SharedTestDataADM.incunabulaMemberUser private val incunabulaUserEmail = incunabulaUser.email private val password = SharedTestDataADM.testPass - private val hamletResourceIri = new MutableTestIri + private val hamletResourceIri = new MutableTestIri private val timeTagResourceIri = new MutableTestIri // If true, writes all API responses to test data files. If false, compares the API responses to the existing test data files. diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v2/StandoffRouteV2E2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v2/StandoffRouteV2E2ESpec.scala index 6e17f4d9a5..2801565764 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v2/StandoffRouteV2E2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v2/StandoffRouteV2E2ESpec.scala @@ -38,9 +38,9 @@ import scala.concurrent.duration._ class StandoffRouteV2E2ESpec extends E2ESpec with AuthenticationV2JsonProtocol { private implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - private val anythingUser = SharedTestDataADM.anythingUser1 + private val anythingUser = SharedTestDataADM.anythingUser1 private val anythingUserEmail = anythingUser.email - private val password = SharedTestDataADM.testPass + private val password = SharedTestDataADM.testPass private val pathToXMLWithStandardMapping = "../test_data/test_route/texts/StandardHTML.xml" @@ -50,14 +50,14 @@ class StandoffRouteV2E2ESpec extends E2ESpec with AuthenticationV2JsonProtocol { private val pathToFreetestCustomMappingWithTransformation = "../test_data/test_route/texts/freetestCustomMappingWithTransformation.xml" private val pathToFreetestXMLTextValue = "../test_data/test_route/texts/freetestXMLTextValue.xml" - private val freetestXSLTFile = "freetestCustomMappingTransformation.xsl" - private val pathToFreetestXSLTFile = s"../test_data/test_route/texts/$freetestXSLTFile" - private val freetestCustomMappingIRI = "http://rdfh.ch/projects/0001/mappings/FreetestCustomMapping" + private val freetestXSLTFile = "freetestCustomMappingTransformation.xsl" + private val pathToFreetestXSLTFile = s"../test_data/test_route/texts/$freetestXSLTFile" + private val freetestCustomMappingIRI = "http://rdfh.ch/projects/0001/mappings/FreetestCustomMapping" private val freetestCustomMappingWithTranformationIRI = "http://rdfh.ch/projects/0001/mappings/FreetestCustomMappingWithTransformation" - private val freetestOntologyIRI = "http://0.0.0.0:3333/ontology/0001/freetest/v2#" + private val freetestOntologyIRI = "http://0.0.0.0:3333/ontology/0001/freetest/v2#" private val freetestTextValueIRI = new MutableTestIri - private val freetestXSLTIRI = "http://rdfh.ch/0001/xYSnl8dmTw2RM6KQGVqNDA" + private val freetestXSLTIRI = "http://rdfh.ch/0001/xYSnl8dmTw2RM6KQGVqNDA" override lazy val rdfDataObjects: List[RdfDataObject] = List( RdfDataObject(path = "test_data/all_data/incunabula-data.ttl", name = "http://www.knora.org/data/incunabula"), @@ -71,7 +71,7 @@ class StandoffRouteV2E2ESpec extends E2ESpec with AuthenticationV2JsonProtocol { ) def createMapping(mappingPath: String, mappingName: String): HttpResponse = { - val mappingFile = Paths.get(mappingPath) + val mappingFile = Paths.get(mappingPath) val mappingParams = DefineStandoffMapping.make(mappingName = mappingName).toJSONLD() val formDataMapping = Multipart.FormData( @@ -98,17 +98,17 @@ class StandoffRouteV2E2ESpec extends E2ESpec with AuthenticationV2JsonProtocol { ).toJson, "rdfs:label" -> "obj_inst1".toJson, "freetest:hasText" -> Map( - "@type" -> "knora-api:TextValue".toJson, + "@type" -> "knora-api:TextValue".toJson, "knora-api:textValueAsXml" -> xmlContent.toJson, "knora-api:textValueHasMapping" -> Map( "@id" -> mappingIRI.toJson ).toJson ).toJson, "@context" -> Map( - "anything" -> "http://0.0.0.0:3333/ontology/0001/anything/v2#".toJson, - "freetest" -> freetestOntologyIRI.toJson, - "rdf" -> "http://www.w3.org/1999/02/22-rdf-syntax-ns#".toJson, - "rdfs" -> "http://www.w3.org/2000/01/rdf-schema#".toJson, + "anything" -> "http://0.0.0.0:3333/ontology/0001/anything/v2#".toJson, + "freetest" -> freetestOntologyIRI.toJson, + "rdf" -> "http://www.w3.org/1999/02/22-rdf-syntax-ns#".toJson, + "rdfs" -> "http://www.w3.org/2000/01/rdf-schema#".toJson, "knora-api" -> "http://api.knora.org/ontology/knora-api/v2#".toJson ).toJson ).toJson.prettyPrint @@ -131,7 +131,7 @@ class StandoffRouteV2E2ESpec extends E2ESpec with AuthenticationV2JsonProtocol { "The Standoff v2 Endpoint" should { "check if SIPI is available" in { val request = Get(s"${settings.internalSipiBaseUrl}/server/test.html") - val res = singleAwaitingRequest(request) + val res = singleAwaitingRequest(request) assert(res.status == StatusCodes.OK) } @@ -152,11 +152,11 @@ class StandoffRouteV2E2ESpec extends E2ESpec with AuthenticationV2JsonProtocol { } "return XML but no HTML for a resource with standard mapping" in { - val valueIRI = URLEncoder.encode(freetestTextValueIRI.get, "UTF-8") + val valueIRI = URLEncoder.encode(freetestTextValueIRI.get, "UTF-8") val xmlContent = FileUtil.readTextFile(Paths.get(pathToXMLWithStandardMapping)) val responseDocument = getTextValueAsDocument(valueIRI) - val textValueObject = responseDocument.body.requireObject(s"${freetestOntologyIRI}hasText") + val textValueObject = responseDocument.body.requireObject(s"${freetestOntologyIRI}hasText") textValueObject.requireString(JsonLDKeywords.TYPE) should equal(OntologyConstants.KnoraApiV2Complex.TextValue) textValueObject .requireObject(OntologyConstants.KnoraApiV2Complex.TextValueHasMapping) @@ -207,8 +207,8 @@ class StandoffRouteV2E2ESpec extends E2ESpec with AuthenticationV2JsonProtocol { BasicHttpCredentials(anythingUserEmail, password) ) val response = singleAwaitingRequest(request) - val status = response.status - val text = responseToString(response) + val status = response.status + val text = responseToString(response) assert( status == StatusCodes.OK, @@ -226,7 +226,7 @@ class StandoffRouteV2E2ESpec extends E2ESpec with AuthenticationV2JsonProtocol { "create a custom mapping for XML in freetest" in { // define custom XML to standoff mapping - val mappingResponse = createMapping(pathToFreetestCustomMapping, "FreetestCustomMapping") + val mappingResponse = createMapping(pathToFreetestCustomMapping, "FreetestCustomMapping") val mappingResponseDocument = responseToJsonLDDocument(mappingResponse) mappingResponse.status should equal(StatusCodes.OK) val mappingIRI = mappingResponseDocument.body.requireString("@id") @@ -251,11 +251,11 @@ class StandoffRouteV2E2ESpec extends E2ESpec with AuthenticationV2JsonProtocol { } "return XML but no HTML, as there is no transformation provided" in { - val valueIRI = URLEncoder.encode(freetestTextValueIRI.get, "UTF-8") + val valueIRI = URLEncoder.encode(freetestTextValueIRI.get, "UTF-8") val xmlContent = FileUtil.readTextFile(Paths.get(pathToFreetestXMLTextValue)) val responseDocument = getTextValueAsDocument(valueIRI) - val textValueObject = responseDocument.body.requireObject(s"${freetestOntologyIRI}hasText") + val textValueObject = responseDocument.body.requireObject(s"${freetestOntologyIRI}hasText") textValueObject.requireString(JsonLDKeywords.TYPE) should equal(OntologyConstants.KnoraApiV2Complex.TextValue) textValueObject .requireObject(OntologyConstants.KnoraApiV2Complex.TextValueHasMapping) @@ -268,10 +268,10 @@ class StandoffRouteV2E2ESpec extends E2ESpec with AuthenticationV2JsonProtocol { "create a custom mapping with an XSL transformation" in { // get authentication token val params = Map( - "email" -> "root@example.com", + "email" -> "root@example.com", "password" -> "test" ).toJson.compactPrint - val loginRequest = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) + val loginRequest = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) val loginResponse: HttpResponse = singleAwaitingRequest(loginRequest) assert(loginResponse.status == StatusCodes.OK, responseToString(loginResponse)) val loginToken = Await.result(Unmarshal(loginResponse.entity).to[LoginResponse], 1.seconds).token @@ -284,7 +284,7 @@ class StandoffRouteV2E2ESpec extends E2ESpec with AuthenticationV2JsonProtocol { Map("filename" -> freetestXSLTFile) ) ) - val sipiRequest = Post(s"${settings.internalSipiBaseUrl}/upload?token=$loginToken", sipiFormData) + val sipiRequest = Post(s"${settings.internalSipiBaseUrl}/upload?token=$loginToken", sipiFormData) val sipiResponse = singleAwaitingRequest(sipiRequest) val uploadedFile = responseToString(sipiResponse).parseJson.asJsObject .convertTo[SipiUploadResponse] @@ -337,12 +337,12 @@ class StandoffRouteV2E2ESpec extends E2ESpec with AuthenticationV2JsonProtocol { } "return XML and HTML rendering of the standoff" in { - val valueIRI = URLEncoder.encode(freetestTextValueIRI.get, "UTF-8") - val xmlContent = FileUtil.readTextFile(Paths.get(pathToFreetestXMLTextValue)) + val valueIRI = URLEncoder.encode(freetestTextValueIRI.get, "UTF-8") + val xmlContent = FileUtil.readTextFile(Paths.get(pathToFreetestXMLTextValue)) val expectedHTML = Some("
\n

This is a sample of standoff text.

\n
") val responseDocument = getTextValueAsDocument(valueIRI) - val textValueObject = responseDocument.body.requireObject(s"${freetestOntologyIRI}hasText") + val textValueObject = responseDocument.body.requireObject(s"${freetestOntologyIRI}hasText") textValueObject.requireString(JsonLDKeywords.TYPE) should equal(OntologyConstants.KnoraApiV2Complex.TextValue) textValueObject .requireObject(OntologyConstants.KnoraApiV2Complex.TextValueHasMapping) diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v2/ValuesRouteV2E2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v2/ValuesRouteV2E2ESpec.scala index 8953361643..8d7b8623ae 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v2/ValuesRouteV2E2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v2/ValuesRouteV2E2ESpec.scala @@ -40,28 +40,28 @@ class ValuesRouteV2E2ESpec extends E2ESpec { private implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance private val anythingUserEmail = SharedTestDataADM.anythingUser1.email - private val password = SharedTestDataADM.testPass + private val password = SharedTestDataADM.testPass - private val intValueIri = new MutableTestIri + private val intValueIri = new MutableTestIri private val intValueWithCustomPermissionsIri = new MutableTestIri - private val intValueForRsyncIri = new MutableTestIri - private val textValueWithoutStandoffIri = new MutableTestIri - private val textValueWithStandoffIri = new MutableTestIri - private val textValueWithEscapeIri = new MutableTestIri - private val decimalValueIri = new MutableTestIri - private val dateValueIri = new MutableTestIri - private val booleanValueIri = new MutableTestIri - private val geometryValueIri = new MutableTestIri - private val intervalValueIri = new MutableTestIri - private val timeValueIri = new MutableTestIri - private val listValueIri = new MutableTestIri - private val colorValueIri = new MutableTestIri - private val uriValueIri = new MutableTestIri - private val geonameValueIri = new MutableTestIri - private val linkValueIri = new MutableTestIri + private val intValueForRsyncIri = new MutableTestIri + private val textValueWithoutStandoffIri = new MutableTestIri + private val textValueWithStandoffIri = new MutableTestIri + private val textValueWithEscapeIri = new MutableTestIri + private val decimalValueIri = new MutableTestIri + private val dateValueIri = new MutableTestIri + private val booleanValueIri = new MutableTestIri + private val geometryValueIri = new MutableTestIri + private val intervalValueIri = new MutableTestIri + private val timeValueIri = new MutableTestIri + private val listValueIri = new MutableTestIri + private val colorValueIri = new MutableTestIri + private val uriValueIri = new MutableTestIri + private val geonameValueIri = new MutableTestIri + private val linkValueIri = new MutableTestIri private var integerValueUUID = UUID.randomUUID - private var linkValueUUID = UUID.randomUUID + private var linkValueUUID = UUID.randomUUID override lazy val rdfDataObjects = List( RdfDataObject(path = "test_data/all_data/anything-data.ttl", name = "http://www.knora.org/data/0001/anything") @@ -77,49 +77,49 @@ class ValuesRouteV2E2ESpec extends E2ESpec { private val clientTestDataCollector = new ClientTestDataCollector(settings) object AThing { - val iri: IRI = "http://rdfh.ch/0001/a-thing" + val iri: IRI = "http://rdfh.ch/0001/a-thing" val iriEncoded: String = URLEncoder.encode(iri, "UTF-8") } object TestDing { - val iri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw" + val iri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw" val iriEncoded: String = URLEncoder.encode(iri, "UTF-8") - val intValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/dJ1ES8QTQNepFKF5-EAqdg" - val decimalValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/bXMwnrHvQH2DMjOFrGmNzg" - val dateValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/-rG4F5FTTu2iB5mTBPVn5Q" - val booleanValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/IN4R19yYR0ygi3K2VEHpUQ" - val uriValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/uBAmWuRhR-eo1u1eP7qqNg" + val intValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/dJ1ES8QTQNepFKF5-EAqdg" + val decimalValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/bXMwnrHvQH2DMjOFrGmNzg" + val dateValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/-rG4F5FTTu2iB5mTBPVn5Q" + val booleanValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/IN4R19yYR0ygi3K2VEHpUQ" + val uriValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/uBAmWuRhR-eo1u1eP7qqNg" val intervalValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/RbDKPKHWTC-0lkRKae-E6A" - val timeValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/l6DhS5SCT9WhXSoYEZRTRw" - val colorValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/TAziKNP8QxuyhC4Qf9-b6w" + val timeValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/l6DhS5SCT9WhXSoYEZRTRw" + val colorValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/TAziKNP8QxuyhC4Qf9-b6w" val geomValueIri: IRI = "http://rdfh.ch/0001/http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/we-ybmj-SRen-91n4RaDOQ" - val geonameValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/hty-ONF8SwKN2RKU7rLKDg" - val textValueWithStandoffIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/rvB4eQ5MTF-Qxq0YgkwaDg" + val geonameValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/hty-ONF8SwKN2RKU7rLKDg" + val textValueWithStandoffIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/rvB4eQ5MTF-Qxq0YgkwaDg" val textValueWithoutStandoffIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/SZyeLLmOTcCCuS3B0VksHQ" - val listValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/XAhEeE3kSVqM4JPGdLt4Ew" - val linkValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/uvRVxzL1RD-t9VIQ1TpfUw" - - val intValueUuid = "dJ1ES8QTQNepFKF5-EAqdg" - val decimalValueUuid = "bXMwnrHvQH2DMjOFrGmNzg" - val dateValueUuid = "-rG4F5FTTu2iB5mTBPVn5Q" - val booleanValueUuid = "IN4R19yYR0ygi3K2VEHpUQ" - val uriValueUuid = "uBAmWuRhR-eo1u1eP7qqNg" - val intervalValueUuid = "RbDKPKHWTC-0lkRKae-E6A" - val timeValueUuid = "l6DhS5SCT9WhXSoYEZRTRw" - val colorValueUuid = "TAziKNP8QxuyhC4Qf9-b6w" - val geomValueUuid = "we-ybmj-SRen-91n4RaDOQ" - val geonameValueUuid = "hty-ONF8SwKN2RKU7rLKDg" - val textValueWithStandoffUuid = "rvB4eQ5MTF-Qxq0YgkwaDg" + val listValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/XAhEeE3kSVqM4JPGdLt4Ew" + val linkValueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/uvRVxzL1RD-t9VIQ1TpfUw" + + val intValueUuid = "dJ1ES8QTQNepFKF5-EAqdg" + val decimalValueUuid = "bXMwnrHvQH2DMjOFrGmNzg" + val dateValueUuid = "-rG4F5FTTu2iB5mTBPVn5Q" + val booleanValueUuid = "IN4R19yYR0ygi3K2VEHpUQ" + val uriValueUuid = "uBAmWuRhR-eo1u1eP7qqNg" + val intervalValueUuid = "RbDKPKHWTC-0lkRKae-E6A" + val timeValueUuid = "l6DhS5SCT9WhXSoYEZRTRw" + val colorValueUuid = "TAziKNP8QxuyhC4Qf9-b6w" + val geomValueUuid = "we-ybmj-SRen-91n4RaDOQ" + val geonameValueUuid = "hty-ONF8SwKN2RKU7rLKDg" + val textValueWithStandoffUuid = "rvB4eQ5MTF-Qxq0YgkwaDg" val textValueWithoutStandoffUuid = "SZyeLLmOTcCCuS3B0VksHQ" - val listValueUuid = "XAhEeE3kSVqM4JPGdLt4Ew" - val linkValueUuid = "uvRVxzL1RD-t9VIQ1TpfUw" + val listValueUuid = "XAhEeE3kSVqM4JPGdLt4Ew" + val linkValueUuid = "uvRVxzL1RD-t9VIQ1TpfUw" } object AThingPicture { - val iri: IRI = "http://rdfh.ch/0001/a-thing-picture" - val iriEncoded: String = URLEncoder.encode(iri, "UTF-8") + val iri: IRI = "http://rdfh.ch/0001/a-thing-picture" + val iriEncoded: String = URLEncoder.encode(iri, "UTF-8") val stillImageFileValueUuid: IRI = "goZ7JFRNSeqF-dNxsqAS7Q" } @@ -672,10 +672,14 @@ class ValuesRouteV2E2ESpec extends E2ESpec { BasicHttpCredentials(SharedTestDataADM.anythingUser1.email, SharedTestDataADM.testPass) ) val response: HttpResponse = singleAwaitingRequest(request) - val responseStr = responseToString(response) + val responseStr = responseToString(response) assert(response.status == StatusCodes.OK, responseStr) val expectedResponseStr = - readOrWriteTextFile(responseStr, Paths.get("..", s"test_data/valuesE2EV2/$fileBasename.jsonld"), writeTestDataFiles) + readOrWriteTextFile( + responseStr, + Paths.get("..", s"test_data/valuesE2EV2/$fileBasename.jsonld"), + writeTestDataFiles + ) compareJSONLDForResourcesResponse(expectedJSONLD = expectedResponseStr, receivedJSONLD = responseStr) clientTestDataCollector.addFile( @@ -689,27 +693,27 @@ class ValuesRouteV2E2ESpec extends E2ESpec { ) ) } - private val customValueUUID = "CpO1TIDf1IS55dQbyIuDsA" + private val customValueUUID = "CpO1TIDf1IS55dQbyIuDsA" private val customValueIri: IRI = s"http://rdfh.ch/0001/a-thing/values/$customValueUUID" "The values v2 endpoint" should { "get the latest versions of values, given their UUIDs" in { // The UUIDs of values in TestDing. val testDingValues: Map[String, String] = Map( - "int-value" -> TestDing.intValueUuid, - "decimal-value" -> TestDing.decimalValueUuid, - "date-value" -> TestDing.dateValueUuid, - "boolean-value" -> TestDing.booleanValueUuid, - "uri-value" -> TestDing.uriValueUuid, - "interval-value" -> TestDing.intervalValueUuid, - "time-value" -> TestDing.timeValueUuid, - "color-value" -> TestDing.colorValueUuid, - "geom-value" -> TestDing.geomValueUuid, - "geoname-value" -> TestDing.geonameValueUuid, - "text-value-with-standoff" -> TestDing.textValueWithStandoffUuid, + "int-value" -> TestDing.intValueUuid, + "decimal-value" -> TestDing.decimalValueUuid, + "date-value" -> TestDing.dateValueUuid, + "boolean-value" -> TestDing.booleanValueUuid, + "uri-value" -> TestDing.uriValueUuid, + "interval-value" -> TestDing.intervalValueUuid, + "time-value" -> TestDing.timeValueUuid, + "color-value" -> TestDing.colorValueUuid, + "geom-value" -> TestDing.geomValueUuid, + "geoname-value" -> TestDing.geonameValueUuid, + "text-value-with-standoff" -> TestDing.textValueWithStandoffUuid, "text-value-without-standoff" -> TestDing.textValueWithoutStandoffUuid, - "list-value" -> TestDing.listValueUuid, - "link-value" -> TestDing.linkValueUuid + "list-value" -> TestDing.listValueUuid, + "link-value" -> TestDing.linkValueUuid ) testDingValues.foreach { case (valueTypeName, valueUuid) => @@ -729,8 +733,8 @@ class ValuesRouteV2E2ESpec extends E2ESpec { "get a past version of a value, given its UUID and a timestamp" in { val resourceIri = URLEncoder.encode("http://rdfh.ch/0001/thing-with-history", "UTF-8") - val valueUuid = "pLlW4ODASumZfZFbJdpw1g" - val timestamp = "20190212T090510Z" + val valueUuid = "pLlW4ODASumZfZFbJdpw1g" + val timestamp = "20190212T090510Z" val request = Get(baseApiUrl + s"/v2/values/$resourceIri/$valueUuid?version=$timestamp") ~> addCredentials( BasicHttpCredentials(anythingUserEmail, password) @@ -750,9 +754,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create an integer value" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasInteger".toSmartIri - val intValue: Int = 4 + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasInteger".toSmartIri + val intValue: Int = 4 val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -785,7 +789,7 @@ class ValuesRouteV2E2ESpec extends E2ESpec { HttpEntity(RdfMediaTypes.`application/ld+json`, jsonLDEntity) ) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password)) val response: HttpResponse = singleAwaitingRequest(request) - val responseStr: String = responseToString(response) + val responseStr: String = responseToString(response) assert(response.status == StatusCodes.OK, responseStr) val responseJsonDoc: JsonLDDocument = JsonLDUtil.parseJsonLD(responseStr) val valueIri: IRI = @@ -825,7 +829,7 @@ class ValuesRouteV2E2ESpec extends E2ESpec { "create an integer value with a custom value IRI" in { val resourceIri: IRI = AThing.iri - val intValue: Int = 30 + val intValue: Int = 30 val jsonLDEntity = s"""{ @@ -894,13 +898,13 @@ class ValuesRouteV2E2ESpec extends E2ESpec { assert(response.status == StatusCodes.BadRequest, response.toString) val errorMessage: String = Await.result(Unmarshal(response.entity).to[String], 1.second) - val invalidIri: Boolean = errorMessage.contains(s"IRI: '$customValueIri' already exists, try another one.") + val invalidIri: Boolean = errorMessage.contains(s"IRI: '$customValueIri' already exists, try another one.") invalidIri should be(true) } "create an integer value with a custom UUID" in { - val resourceIri: IRI = AThing.iri - val intValue: Int = 45 + val resourceIri: IRI = AThing.iri + val intValue: Int = 45 val intValueCustomUUID = "IN4R19yYR0ygi3K2VEHpUQ" val jsonLDEntity = @@ -938,7 +942,7 @@ class ValuesRouteV2E2ESpec extends E2ESpec { assert(response.status == StatusCodes.OK, response.toString) val responseJsonDoc: JsonLDDocument = responseToJsonLDDocument(response) - val valueUUID: String = responseJsonDoc.body.requireString(OntologyConstants.KnoraApiV2Complex.ValueHasUUID) + val valueUUID: String = responseJsonDoc.body.requireString(OntologyConstants.KnoraApiV2Complex.ValueHasUUID) assert(valueUUID == intValueCustomUUID) val valueIri: IRI = responseJsonDoc.body.requireStringWithValidation(JsonLDKeywords.ID, stringFormatter.validateAndEscapeIri) @@ -948,9 +952,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { "do not create an integer value if the custom UUID is not part of the custom IRI" in { val resourceIri: IRI = AThing.iri - val intValue: Int = 45 - val aUUID = "IN4R19yYR0ygi3K2VEHpUQ" - val valueIri = s"http://rdfh.ch/0001/a-thing/values/IN4R19yYR0ygi3K2VEHpNN" + val intValue: Int = 45 + val aUUID = "IN4R19yYR0ygi3K2VEHpUQ" + val valueIri = s"http://rdfh.ch/0001/a-thing/values/IN4R19yYR0ygi3K2VEHpNN" val jsonLDEntity = s"""{ | "@id" : "$resourceIri", @@ -979,8 +983,8 @@ class ValuesRouteV2E2ESpec extends E2ESpec { "create an integer value with a custom creation date" in { val customCreationDate: Instant = Instant.parse("2020-06-04T11:36:54.502951Z") - val resourceIri: IRI = AThing.iri - val intValue: Int = 25 + val resourceIri: IRI = AThing.iri + val intValue: Int = 25 val jsonLDEntity = s"""{ @@ -1034,10 +1038,10 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create an integer value with custom IRI, UUID, and creation date" in { - val resourceIri: IRI = AThing.iri - val intValue: Int = 10 - val customValueIri: IRI = "http://rdfh.ch/0001/a-thing/values/7VDvMOnuitf_r1Ju7BglsQ" - val customValueUUID = "7VDvMOnuitf_r1Ju7BglsQ" + val resourceIri: IRI = AThing.iri + val intValue: Int = 10 + val customValueIri: IRI = "http://rdfh.ch/0001/a-thing/values/7VDvMOnuitf_r1Ju7BglsQ" + val customValueUUID = "7VDvMOnuitf_r1Ju7BglsQ" val customCreationDate: Instant = Instant.parse("2020-06-04T12:58:54.502951Z") val jsonLDEntity = @@ -1096,7 +1100,7 @@ class ValuesRouteV2E2ESpec extends E2ESpec { "not create an integer value if the simple schema is submitted" in { val resourceIri: IRI = AThing.iri - val intValue: Int = 10 + val intValue: Int = 10 val jsonLDEntity = s"""{ @@ -1114,15 +1118,15 @@ class ValuesRouteV2E2ESpec extends E2ESpec { HttpEntity(RdfMediaTypes.`application/ld+json`, jsonLDEntity) ) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password)) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.BadRequest, responseAsString) } "create an integer value with custom permissions" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasInteger".toSmartIri - val intValue: Int = 1 - val customPermissions: String = "CR knora-admin:Creator|V http://rdfh.ch/groups/0001/thing-searcher" + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasInteger".toSmartIri + val intValue: Int = 1 + val customPermissions: String = "CR knora-admin:Creator|V http://rdfh.ch/groups/0001/thing-searcher" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -1181,9 +1185,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a text value without standoff and without a comment" in { - val resourceIri: IRI = AThing.iri - val valueAsString: String = "text without standoff" - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri + val resourceIri: IRI = AThing.iri + val valueAsString: String = "text without standoff" + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity: String = createTextValueWithoutStandoffRequest( @@ -1230,7 +1234,7 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "not update a text value without a comment without changing it" in { - val resourceIri: IRI = AThing.iri + val resourceIri: IRI = AThing.iri val valueAsString: String = "text without standoff" val jsonLDEntity = updateTextValueWithoutStandoffRequest( @@ -1248,7 +1252,7 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "not update a text value so it's empty" in { - val resourceIri: IRI = AThing.iri + val resourceIri: IRI = AThing.iri val valueAsString: String = "" val jsonLDEntity = updateTextValueWithoutStandoffRequest( @@ -1266,9 +1270,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a text value without standoff" in { - val resourceIri: IRI = AThing.iri - val valueAsString: String = "text without standoff updated" - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri + val resourceIri: IRI = AThing.iri + val valueAsString: String = "text without standoff updated" + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = updateTextValueWithoutStandoffRequest( @@ -1316,9 +1320,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a text value without standoff, adding a comment" in { - val resourceIri: IRI = AThing.iri - val valueAsString: String = "text without standoff updated" - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri + val resourceIri: IRI = AThing.iri + val valueAsString: String = "text without standoff updated" + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = updateTextValueWithCommentRequest( @@ -1367,7 +1371,7 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "not update a text value without standoff and with a comment without changing it" in { - val resourceIri: IRI = AThing.iri + val resourceIri: IRI = AThing.iri val valueAsString: String = "text without standoff updated" val jsonLDEntity = updateTextValueWithCommentRequest( @@ -1386,9 +1390,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a text value without standoff, changing only the a comment" in { - val resourceIri: IRI = AThing.iri - val valueAsString: String = "text without standoff updated" - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri + val resourceIri: IRI = AThing.iri + val valueAsString: String = "text without standoff updated" + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = updateTextValueWithCommentRequest( @@ -1426,10 +1430,10 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a text value without standoff and with a comment" in { - val resourceIri: IRI = AThing.iri - val valueAsString: String = "this is a text value that has a comment" - val valueHasComment: String = "this is a comment" - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri + val resourceIri: IRI = AThing.iri + val valueAsString: String = "this is a text value that has a comment" + val valueHasComment: String = "this is a comment" + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -1488,8 +1492,8 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a text value with standoff test1" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = createTextValueWithStandoffRequest( @@ -1514,7 +1518,7 @@ class ValuesRouteV2E2ESpec extends E2ESpec { HttpEntity(RdfMediaTypes.`application/ld+json`, jsonLDEntity) ) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password)) val response: HttpResponse = singleAwaitingRequest(request) - val responseStr = responseToString(response) + val responseStr = responseToString(response) assert(response.status == StatusCodes.OK, responseStr) val responseJsonDoc: JsonLDDocument = JsonLDUtil.parseJsonLD(responseStr) val valueIri: IRI = @@ -1974,7 +1978,7 @@ class ValuesRouteV2E2ESpec extends E2ESpec { | """.stripMargin - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = createTextValueWithStandoffRequest( @@ -2024,7 +2028,7 @@ class ValuesRouteV2E2ESpec extends E2ESpec { | """.stripMargin - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = createTextValueWithStandoffRequest( @@ -2060,9 +2064,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a text value with standoff containing escaped text" in { - val resourceIri = AThing.iri + val resourceIri = AThing.iri val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) - val jsonLDEntity = FileUtil.readTextFile(Paths.get("..", "test_data/valuesE2EV2/CreateValueWithEscape.jsonld")) + val jsonLDEntity = FileUtil.readTextFile(Paths.get("..", "test_data/valuesE2EV2/CreateValueWithEscape.jsonld")) val request = Post( baseApiUrl + "/v2/values", HttpEntity(RdfMediaTypes.`application/ld+json`, jsonLDEntity) @@ -2132,8 +2136,8 @@ class ValuesRouteV2E2ESpec extends E2ESpec { // Create the text value. - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val textValueAsXml = @@ -2173,7 +2177,7 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "not create an empty text value" in { - val resourceIri: IRI = AThing.iri + val resourceIri: IRI = AThing.iri val valueAsString: String = "" val jsonLDEntity = createTextValueWithoutStandoffRequest( @@ -2190,9 +2194,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a decimal value" in { - val resourceIri: IRI = AThing.iri - val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDecimal".toSmartIri - val decimalValueAsDecimal = BigDecimal(4.3) + val resourceIri: IRI = AThing.iri + val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDecimal".toSmartIri + val decimalValueAsDecimal = BigDecimal(4.3) val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -2257,17 +2261,17 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a date value representing a range with day precision" in { - val resourceIri: IRI = AThing.iri - val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri - val dateValueHasCalendar = "GREGORIAN" - val dateValueHasStartYear = 2018 - val dateValueHasStartMonth = 10 - val dateValueHasStartDay = 5 - val dateValueHasStartEra = "CE" - val dateValueHasEndYear = 2018 - val dateValueHasEndMonth = 10 - val dateValueHasEndDay = 6 - val dateValueHasEndEra = "CE" + val resourceIri: IRI = AThing.iri + val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri + val dateValueHasCalendar = "GREGORIAN" + val dateValueHasStartYear = 2018 + val dateValueHasStartMonth = 10 + val dateValueHasStartDay = 5 + val dateValueHasStartEra = "CE" + val dateValueHasEndYear = 2018 + val dateValueHasEndMonth = 10 + val dateValueHasEndDay = 6 + val dateValueHasEndEra = "CE" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = createDateValueWithDayPrecisionRequest( @@ -2338,15 +2342,15 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a date value representing a range with month precision" in { - val resourceIri: IRI = AThing.iri - val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri - val dateValueHasCalendar = "GREGORIAN" - val dateValueHasStartYear = 2018 - val dateValueHasStartMonth = 10 - val dateValueHasStartEra = "CE" - val dateValueHasEndYear = 2018 - val dateValueHasEndMonth = 11 - val dateValueHasEndEra = "CE" + val resourceIri: IRI = AThing.iri + val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri + val dateValueHasCalendar = "GREGORIAN" + val dateValueHasStartYear = 2018 + val dateValueHasStartMonth = 10 + val dateValueHasStartEra = "CE" + val dateValueHasEndYear = 2018 + val dateValueHasEndMonth = 11 + val dateValueHasEndEra = "CE" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = createDateValueWithMonthPrecisionRequest( @@ -2415,13 +2419,13 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a date value representing a range with year precision" in { - val resourceIri: IRI = AThing.iri - val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri - val dateValueHasCalendar = "GREGORIAN" - val dateValueHasStartYear = 2018 - val dateValueHasStartEra = "CE" - val dateValueHasEndYear = 2019 - val dateValueHasEndEra = "CE" + val resourceIri: IRI = AThing.iri + val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri + val dateValueHasCalendar = "GREGORIAN" + val dateValueHasStartYear = 2018 + val dateValueHasStartEra = "CE" + val dateValueHasEndYear = 2019 + val dateValueHasEndEra = "CE" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = createDateValueWithYearPrecisionRequest( @@ -2486,13 +2490,13 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a date value representing a single date with day precision" in { - val resourceIri: IRI = AThing.iri - val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri - val dateValueHasCalendar = "GREGORIAN" - val dateValueHasStartYear = 2018 - val dateValueHasStartMonth = 10 - val dateValueHasStartDay = 5 - val dateValueHasStartEra = "CE" + val resourceIri: IRI = AThing.iri + val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri + val dateValueHasCalendar = "GREGORIAN" + val dateValueHasStartYear = 2018 + val dateValueHasStartMonth = 10 + val dateValueHasStartDay = 5 + val dateValueHasStartEra = "CE" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity: String = createDateValueWithDayPrecisionRequest( @@ -2550,12 +2554,12 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a date value representing a single date with month precision" in { - val resourceIri: IRI = AThing.iri - val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri - val dateValueHasCalendar = "GREGORIAN" - val dateValueHasStartYear = 2018 - val dateValueHasStartMonth = 10 - val dateValueHasStartEra = "CE" + val resourceIri: IRI = AThing.iri + val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri + val dateValueHasCalendar = "GREGORIAN" + val dateValueHasStartYear = 2018 + val dateValueHasStartMonth = 10 + val dateValueHasStartEra = "CE" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = createDateValueWithMonthPrecisionRequest( @@ -2611,11 +2615,11 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a date value representing a single date with year precision" in { - val resourceIri: IRI = AThing.iri - val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri - val dateValueHasCalendar = "GREGORIAN" - val dateValueHasStartYear = 2018 - val dateValueHasStartEra = "CE" + val resourceIri: IRI = AThing.iri + val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri + val dateValueHasCalendar = "GREGORIAN" + val dateValueHasStartYear = 2018 + val dateValueHasStartEra = "CE" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = createDateValueWithYearPrecisionRequest( @@ -2667,12 +2671,12 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a date value representing a single Islamic date with day precision" in { - val resourceIri: IRI = AThing.iri - val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri - val dateValueHasCalendar = "ISLAMIC" - val dateValueHasStartYear = 1407 - val dateValueHasStartMonth = 1 - val dateValueHasStartDay = 26 + val resourceIri: IRI = AThing.iri + val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri + val dateValueHasCalendar = "ISLAMIC" + val dateValueHasStartYear = 1407 + val dateValueHasStartMonth = 1 + val dateValueHasStartDay = 26 val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = createIslamicDateValueWithDayPrecisionRequest( @@ -2724,15 +2728,15 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create an Islamic date value representing a range with day precision" in { - val resourceIri: IRI = AThing.iri - val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri - val dateValueHasCalendar = "ISLAMIC" - val dateValueHasStartYear = 1407 - val dateValueHasStartMonth = 1 - val dateValueHasStartDay = 15 - val dateValueHasEndYear = 1407 - val dateValueHasEndMonth = 1 - val dateValueHasEndDay = 26 + val resourceIri: IRI = AThing.iri + val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri + val dateValueHasCalendar = "ISLAMIC" + val dateValueHasStartYear = 1407 + val dateValueHasStartMonth = 1 + val dateValueHasStartDay = 15 + val dateValueHasEndYear = 1407 + val dateValueHasEndMonth = 1 + val dateValueHasEndDay = 26 val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = createIslamicDateValueWithDayPrecisionRequest( @@ -2786,9 +2790,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a boolean value" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasBoolean".toSmartIri - val booleanValue: Boolean = true + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasBoolean".toSmartIri + val booleanValue: Boolean = true val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -2845,8 +2849,8 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a geometry value" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasGeometry".toSmartIri + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasGeometry".toSmartIri val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -2903,10 +2907,10 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create an interval value" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasInterval".toSmartIri - val intervalStart = BigDecimal("1.2") - val intervalEnd = BigDecimal("3.4") + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasInterval".toSmartIri + val intervalStart = BigDecimal("1.2") + val intervalEnd = BigDecimal("3.4") val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -2983,9 +2987,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a time value" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasTimeStamp".toSmartIri - val timeStamp = Instant.parse("2019-08-28T15:59:12.725007Z") + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasTimeStamp".toSmartIri + val timeStamp = Instant.parse("2019-08-28T15:59:12.725007Z") val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -3050,9 +3054,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a list value" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasListItem".toSmartIri - val listNode = "http://rdfh.ch/lists/0001/treeList03" + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasListItem".toSmartIri + val listNode = "http://rdfh.ch/lists/0001/treeList03" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -3115,9 +3119,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a color value" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasColor".toSmartIri - val color = "#ff3333" + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasColor".toSmartIri + val color = "#ff3333" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -3174,9 +3178,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a URI value" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasUri".toSmartIri - val uri = "https://www.knora.org" + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasUri".toSmartIri + val uri = "https://www.knora.org" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -3241,9 +3245,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a geoname value" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasGeoname".toSmartIri - val geonameCode = "2661604" + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasGeoname".toSmartIri + val geonameCode = "2661604" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -3301,9 +3305,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a link between two resources, without a comment" in { - val resourceIri: IRI = AThing.iri - val linkPropertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasOtherThing".toSmartIri - val linkValuePropertyIri: SmartIri = linkPropertyIri.fromLinkPropToLinkValueProp + val resourceIri: IRI = AThing.iri + val linkPropertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasOtherThing".toSmartIri + val linkValuePropertyIri: SmartIri = linkPropertyIri.fromLinkPropToLinkValueProp val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity: String = @@ -3363,15 +3367,15 @@ class ValuesRouteV2E2ESpec extends E2ESpec { ) val savedTarget: JsonLDObject = savedValue.requireObject(OntologyConstants.KnoraApiV2Complex.LinkValueHasTarget) - val savedTargetIri: IRI = savedTarget.requireString(JsonLDKeywords.ID) + val savedTargetIri: IRI = savedTarget.requireString(JsonLDKeywords.ID) savedTargetIri should ===(TestDing.iri) } "create a link between two resources with a custom link value IRI, UUID, creationDate" in { - val resourceIri: IRI = AThing.iri - val targetResourceIri: IRI = "http://rdfh.ch/0001/CNhWoNGGT7iWOrIwxsEqvA" - val customValueIri: IRI = "http://rdfh.ch/0001/a-thing/values/mr9i2aUUJolv64V_9hYdTw" - val customValueUUID = "mr9i2aUUJolv64V_9hYdTw" + val resourceIri: IRI = AThing.iri + val targetResourceIri: IRI = "http://rdfh.ch/0001/CNhWoNGGT7iWOrIwxsEqvA" + val customValueIri: IRI = "http://rdfh.ch/0001/a-thing/values/mr9i2aUUJolv64V_9hYdTw" + val customValueUUID = "mr9i2aUUJolv64V_9hYdTw" val customCreationDate: Instant = Instant.parse("2020-06-04T11:36:54.502951Z") val jsonLDEntity = @@ -3431,9 +3435,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update an integer value" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasInteger".toSmartIri - val intValue: Int = 5 + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasInteger".toSmartIri + val intValue: Int = 5 val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -3467,7 +3471,7 @@ class ValuesRouteV2E2ESpec extends E2ESpec { BasicHttpCredentials(anythingUserEmail, password) ) val response: HttpResponse = singleAwaitingRequest(request) - val responseStr: String = responseToString(response) + val responseStr: String = responseToString(response) assert(response.status == StatusCodes.OK, responseStr) val responseJsonDoc: JsonLDDocument = JsonLDUtil.parseJsonLD(responseStr) val valueIri: IRI = @@ -3508,11 +3512,11 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update an integer value with a custom creation date" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasInteger".toSmartIri - val intValue: Int = 6 + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasInteger".toSmartIri + val intValue: Int = 6 val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) - val valueCreationDate = Instant.now + val valueCreationDate = Instant.now val jsonLDEntity = s"""{ @@ -3581,11 +3585,11 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update an integer value with a custom new value version IRI" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasInteger".toSmartIri - val intValue: Int = 7 + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasInteger".toSmartIri + val intValue: Int = 7 val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) - val newValueVersionIri: IRI = s"http://rdfh.ch/0001/a-thing/values/W8COP_RXRpqVsjW9NL2JYg" + val newValueVersionIri: IRI = s"http://rdfh.ch/0001/a-thing/values/W8COP_RXRpqVsjW9NL2JYg" val jsonLDEntity = updateIntValueWithCustomNewValueVersionIriRequest( resourceIri = resourceIri, @@ -3621,8 +3625,8 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "not update an integer value with a custom new value version IRI that is the same as the current IRI" in { - val resourceIri: IRI = AThing.iri - val intValue: Int = 8 + val resourceIri: IRI = AThing.iri + val intValue: Int = 8 val newValueVersionIri: IRI = s"http://rdfh.ch/0001/a-thing/values/W8COP_RXRpqVsjW9NL2JYg" val jsonLDEntity = updateIntValueWithCustomNewValueVersionIriRequest( @@ -3637,13 +3641,13 @@ class ValuesRouteV2E2ESpec extends E2ESpec { BasicHttpCredentials(anythingUserEmail, password) ) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.BadRequest, responseAsString) } "not update an integer value with an invalid custom new value version IRI" in { - val resourceIri: IRI = AThing.iri - val intValue: Int = 8 + val resourceIri: IRI = AThing.iri + val intValue: Int = 8 val newValueVersionIri: IRI = "foo" val jsonLDEntity = updateIntValueWithCustomNewValueVersionIriRequest( @@ -3658,13 +3662,13 @@ class ValuesRouteV2E2ESpec extends E2ESpec { BasicHttpCredentials(anythingUserEmail, password) ) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.BadRequest, responseAsString) } "not update an integer value with a custom new value version IRI that refers to the wrong project code" in { - val resourceIri: IRI = AThing.iri - val intValue: Int = 8 + val resourceIri: IRI = AThing.iri + val intValue: Int = 8 val newValueVersionIri: IRI = "http://rdfh.ch/0002/a-thing/values/foo" val jsonLDEntity = updateIntValueWithCustomNewValueVersionIriRequest( @@ -3679,13 +3683,13 @@ class ValuesRouteV2E2ESpec extends E2ESpec { BasicHttpCredentials(anythingUserEmail, password) ) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.BadRequest, responseAsString) } "not update an integer value with a custom new value version IRI that refers to the wrong resource" in { - val resourceIri: IRI = AThing.iri - val intValue: Int = 8 + val resourceIri: IRI = AThing.iri + val intValue: Int = 8 val newValueVersionIri: IRI = "http://rdfh.ch/0001/nResNuvARcWYUdWyo0GWGw/values/iEYi6E7Ntjvj2syzJZiXlg" val jsonLDEntity = updateIntValueWithCustomNewValueVersionIriRequest( @@ -3700,13 +3704,13 @@ class ValuesRouteV2E2ESpec extends E2ESpec { BasicHttpCredentials(anythingUserEmail, password) ) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.BadRequest, responseAsString) } "not update an integer value if the simple schema is submitted" in { val resourceIri: IRI = AThing.iri - val intValue: Int = 10 + val intValue: Int = 10 val jsonLDEntity = s"""{ @@ -3728,15 +3732,15 @@ class ValuesRouteV2E2ESpec extends E2ESpec { BasicHttpCredentials(anythingUserEmail, password) ) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.BadRequest, responseAsString) } "update an integer value with custom permissions" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasInteger".toSmartIri - val intValue: Int = 3879 - val customPermissions: String = "CR http://rdfh.ch/groups/0001/thing-searcher" + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasInteger".toSmartIri + val intValue: Int = 3879 + val customPermissions: String = "CR http://rdfh.ch/groups/0001/thing-searcher" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -3796,9 +3800,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update an integer value, changing only the permissions" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasInteger".toSmartIri - val customPermissions: String = "CR http://rdfh.ch/groups/0001/thing-searcher|V knora-admin:KnownUser" + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasInteger".toSmartIri + val customPermissions: String = "CR http://rdfh.ch/groups/0001/thing-searcher|V knora-admin:KnownUser" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -3855,9 +3859,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a decimal value" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDecimal".toSmartIri - val decimalValue = BigDecimal(5.6) + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDecimal".toSmartIri + val decimalValue = BigDecimal(5.6) val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -3925,7 +3929,7 @@ class ValuesRouteV2E2ESpec extends E2ESpec { "update a text value with standoff" in { val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -3988,10 +3992,10 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a text value with standoff containing escaped text" in { - val resourceIri = AThing.iri + val resourceIri = AThing.iri val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) - val jsonLDEntity = FileUtil.readTextFile(Paths.get("..","test_data/valuesE2EV2/UpdateValueWithEscape.jsonld")) - val jsonLDEntityWithResourceValueIri = jsonLDEntity.replace("VALUE_IRI", textValueWithEscapeIri.get) + val jsonLDEntity = FileUtil.readTextFile(Paths.get("..", "test_data/valuesE2EV2/UpdateValueWithEscape.jsonld")) + val jsonLDEntityWithResourceValueIri = jsonLDEntity.replace("VALUE_IRI", textValueWithEscapeIri.get) val request = Put( baseApiUrl + "/v2/values", HttpEntity(RdfMediaTypes.`application/ld+json`, jsonLDEntityWithResourceValueIri) @@ -4023,10 +4027,10 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a text value with a comment" in { - val resourceIri: IRI = AThing.iri - val valueAsString: String = "this is a text value that has an updated comment" - val valueHasComment: String = "this is an updated comment" - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri + val resourceIri: IRI = AThing.iri + val valueAsString: String = "this is a text value that has an updated comment" + val valueHasComment: String = "this is an updated comment" + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasText".toSmartIri val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = updateTextValueWithCommentRequest( @@ -4066,17 +4070,17 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a date value representing a range with day precision" in { - val resourceIri: IRI = AThing.iri - val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri - val dateValueHasCalendar = "GREGORIAN" - val dateValueHasStartYear = 2018 - val dateValueHasStartMonth = 10 - val dateValueHasStartDay = 5 - val dateValueHasStartEra = "CE" - val dateValueHasEndYear = 2018 - val dateValueHasEndMonth = 12 - val dateValueHasEndDay = 6 - val dateValueHasEndEra = "CE" + val resourceIri: IRI = AThing.iri + val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri + val dateValueHasCalendar = "GREGORIAN" + val dateValueHasStartYear = 2018 + val dateValueHasStartMonth = 10 + val dateValueHasStartDay = 5 + val dateValueHasStartEra = "CE" + val dateValueHasEndYear = 2018 + val dateValueHasEndMonth = 12 + val dateValueHasEndDay = 6 + val dateValueHasEndEra = "CE" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = updateDateValueWithDayPrecisionRequest( @@ -4148,15 +4152,15 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a date value representing a range with month precision" in { - val resourceIri: IRI = AThing.iri - val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri - val dateValueHasCalendar = "GREGORIAN" - val dateValueHasStartYear = 2018 - val dateValueHasStartMonth = 9 - val dateValueHasStartEra = "CE" - val dateValueHasEndYear = 2018 - val dateValueHasEndMonth = 12 - val dateValueHasEndEra = "CE" + val resourceIri: IRI = AThing.iri + val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri + val dateValueHasCalendar = "GREGORIAN" + val dateValueHasStartYear = 2018 + val dateValueHasStartMonth = 9 + val dateValueHasStartEra = "CE" + val dateValueHasEndYear = 2018 + val dateValueHasEndMonth = 12 + val dateValueHasEndEra = "CE" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = updateDateValueWithMonthPrecisionRequest( @@ -4226,13 +4230,13 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a date value representing a range with year precision" in { - val resourceIri: IRI = AThing.iri - val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri - val dateValueHasCalendar = "GREGORIAN" - val dateValueHasStartYear = 2018 - val dateValueHasStartEra = "CE" - val dateValueHasEndYear = 2020 - val dateValueHasEndEra = "CE" + val resourceIri: IRI = AThing.iri + val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri + val dateValueHasCalendar = "GREGORIAN" + val dateValueHasStartYear = 2018 + val dateValueHasStartEra = "CE" + val dateValueHasEndYear = 2020 + val dateValueHasEndEra = "CE" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = updateDateValueWithYearPrecisionRequest( @@ -4298,13 +4302,13 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a date value representing a single date with day precision" in { - val resourceIri: IRI = AThing.iri - val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri - val dateValueHasCalendar = "GREGORIAN" - val dateValueHasStartYear = 2018 - val dateValueHasStartMonth = 10 - val dateValueHasStartDay = 6 - val dateValueHasStartEra = "CE" + val resourceIri: IRI = AThing.iri + val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri + val dateValueHasCalendar = "GREGORIAN" + val dateValueHasStartYear = 2018 + val dateValueHasStartMonth = 10 + val dateValueHasStartDay = 6 + val dateValueHasStartEra = "CE" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = updateDateValueWithDayPrecisionRequest( @@ -4363,12 +4367,12 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a date value representing a single date with month precision" in { - val resourceIri: IRI = AThing.iri - val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri - val dateValueHasCalendar = "GREGORIAN" - val dateValueHasStartYear = 2018 - val dateValueHasStartMonth = 7 - val dateValueHasStartEra = "CE" + val resourceIri: IRI = AThing.iri + val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri + val dateValueHasCalendar = "GREGORIAN" + val dateValueHasStartYear = 2018 + val dateValueHasStartMonth = 7 + val dateValueHasStartEra = "CE" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = updateDateValueWithMonthPrecisionRequest( @@ -4425,11 +4429,11 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a date value representing a single date with year precision" in { - val resourceIri: IRI = AThing.iri - val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri - val dateValueHasCalendar = "GREGORIAN" - val dateValueHasStartYear = 2019 - val dateValueHasStartEra = "CE" + val resourceIri: IRI = AThing.iri + val propertyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasDate".toSmartIri + val dateValueHasCalendar = "GREGORIAN" + val dateValueHasStartYear = 2019 + val dateValueHasStartEra = "CE" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = updateDateValueWithYearPrecisionRequest( @@ -4482,9 +4486,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a boolean value" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasBoolean".toSmartIri - val booleanValue: Boolean = false + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasBoolean".toSmartIri + val booleanValue: Boolean = false val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -4542,8 +4546,8 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a geometry value" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasGeometry".toSmartIri + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasGeometry".toSmartIri val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -4601,10 +4605,10 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update an interval value" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasInterval".toSmartIri - val intervalStart = BigDecimal("5.6") - val intervalEnd = BigDecimal("7.8") + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasInterval".toSmartIri + val intervalStart = BigDecimal("5.6") + val intervalEnd = BigDecimal("7.8") val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -4682,9 +4686,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a time value" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasTimeStamp".toSmartIri - val timeStamp = Instant.parse("2019-12-16T09:14:56.409249Z") + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasTimeStamp".toSmartIri + val timeStamp = Instant.parse("2019-12-16T09:14:56.409249Z") val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -4750,9 +4754,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a list value" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasListItem".toSmartIri - val listNode = "http://rdfh.ch/lists/0001/treeList02" + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasListItem".toSmartIri + val listNode = "http://rdfh.ch/lists/0001/treeList02" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -4816,9 +4820,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a color value" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasColor".toSmartIri - val color = "#ff3344" + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasColor".toSmartIri + val color = "#ff3344" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -4876,9 +4880,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a URI value" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasUri".toSmartIri - val uri = "https://docs.knora.org" + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasUri".toSmartIri + val uri = "https://docs.knora.org" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -4944,9 +4948,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a geoname value" in { - val resourceIri: IRI = AThing.iri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasGeoname".toSmartIri - val geonameCode = "2988507" + val resourceIri: IRI = AThing.iri + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasGeoname".toSmartIri + val geonameCode = "2988507" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = @@ -5005,10 +5009,10 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a link between two resources" in { - val resourceIri: IRI = AThing.iri - val linkPropertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasOtherThing".toSmartIri - val linkValuePropertyIri: SmartIri = linkPropertyIri.fromLinkPropToLinkValueProp - val linkTargetIri: IRI = "http://rdfh.ch/0001/5IEswyQFQp2bxXDrOyEfEA" + val resourceIri: IRI = AThing.iri + val linkPropertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasOtherThing".toSmartIri + val linkValuePropertyIri: SmartIri = linkPropertyIri.fromLinkPropToLinkValueProp + val linkTargetIri: IRI = "http://rdfh.ch/0001/5IEswyQFQp2bxXDrOyEfEA" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = updateLinkValueRequest( @@ -5062,12 +5066,12 @@ class ValuesRouteV2E2ESpec extends E2ESpec { ) val savedTarget: JsonLDObject = savedValue.requireObject(OntologyConstants.KnoraApiV2Complex.LinkValueHasTarget) - val savedTargetIri: IRI = savedTarget.requireString(JsonLDKeywords.ID) + val savedTargetIri: IRI = savedTarget.requireString(JsonLDKeywords.ID) savedTargetIri should ===(linkTargetIri) } "not update a link without a comment without changing it" in { - val resourceIri: IRI = AThing.iri + val resourceIri: IRI = AThing.iri val linkTargetIri: IRI = "http://rdfh.ch/0001/5IEswyQFQp2bxXDrOyEfEA" val jsonLDEntity = updateLinkValueRequest( @@ -5085,11 +5089,11 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a link between two resources, adding a comment" in { - val resourceIri: IRI = AThing.iri - val linkPropertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasOtherThing".toSmartIri - val linkValuePropertyIri: SmartIri = linkPropertyIri.fromLinkPropToLinkValueProp - val linkTargetIri: IRI = "http://rdfh.ch/0001/5IEswyQFQp2bxXDrOyEfEA" - val comment = "adding a comment" + val resourceIri: IRI = AThing.iri + val linkPropertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasOtherThing".toSmartIri + val linkValuePropertyIri: SmartIri = linkPropertyIri.fromLinkPropToLinkValueProp + val linkTargetIri: IRI = "http://rdfh.ch/0001/5IEswyQFQp2bxXDrOyEfEA" + val comment = "adding a comment" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = updateLinkValueRequest( @@ -5136,11 +5140,11 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "update a link between two resources, changing only the comment" in { - val resourceIri: IRI = AThing.iri - val linkPropertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasOtherThing".toSmartIri - val linkValuePropertyIri: SmartIri = linkPropertyIri.fromLinkPropToLinkValueProp - val linkTargetIri: IRI = "http://rdfh.ch/0001/5IEswyQFQp2bxXDrOyEfEA" - val comment = "changing only the comment" + val resourceIri: IRI = AThing.iri + val linkPropertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasOtherThing".toSmartIri + val linkValuePropertyIri: SmartIri = linkPropertyIri.fromLinkPropToLinkValueProp + val linkTargetIri: IRI = "http://rdfh.ch/0001/5IEswyQFQp2bxXDrOyEfEA" + val comment = "changing only the comment" val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) val jsonLDEntity = updateLinkValueRequest( @@ -5187,9 +5191,9 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "not update a link with a comment without changing it" in { - val resourceIri: IRI = AThing.iri + val resourceIri: IRI = AThing.iri val linkTargetIri: IRI = "http://rdfh.ch/0001/5IEswyQFQp2bxXDrOyEfEA" - val comment = "changing only the comment" + val comment = "changing only the comment" val jsonLDEntity = updateLinkValueRequest( resourceIri = resourceIri, @@ -5207,11 +5211,11 @@ class ValuesRouteV2E2ESpec extends E2ESpec { } "create a link between two resources, with a comment" in { - val resourceIri: IRI = AThing.iri - val linkPropertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasOtherThing".toSmartIri - val linkValuePropertyIri: SmartIri = linkPropertyIri.fromLinkPropToLinkValueProp + val resourceIri: IRI = AThing.iri + val linkPropertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasOtherThing".toSmartIri + val linkValuePropertyIri: SmartIri = linkPropertyIri.fromLinkPropToLinkValueProp val maybeResourceLastModDate: Option[Instant] = getResourceLastModificationDate(resourceIri, anythingUserEmail) - val comment = "Initial comment" + val comment = "Initial comment" val jsonLDEntity = s"""{ @@ -5256,7 +5260,7 @@ class ValuesRouteV2E2ESpec extends E2ESpec { ) val savedTarget: JsonLDObject = savedValue.requireObject(OntologyConstants.KnoraApiV2Complex.LinkValueHasTarget) - val savedTargetIri: IRI = savedTarget.requireString(JsonLDKeywords.ID) + val savedTargetIri: IRI = savedTarget.requireString(JsonLDKeywords.ID) savedTargetIri should ===(TestDing.iri) val savedComment: String = savedValue.requireString(OntologyConstants.KnoraApiV2Complex.ValueHasComment) @@ -5350,13 +5354,13 @@ class ValuesRouteV2E2ESpec extends E2ESpec { HttpEntity(RdfMediaTypes.`application/ld+json`, jsonLDEntity) ) ~> addCredentials(BasicHttpCredentials(anythingUserEmail, password)) val response: HttpResponse = singleAwaitingRequest(request) - val responseAsString = responseToString(response) + val responseAsString = responseToString(response) assert(response.status == StatusCodes.BadRequest, responseAsString) } "delete an integer value without supplying a delete comment" in { val resourceIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw" - val valueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/dJ1ES8QTQNepFKF5-EAqdg" + val valueIri: IRI = "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/dJ1ES8QTQNepFKF5-EAqdg" val jsonLDEntity = deleteIntValueRequest( resourceIri = resourceIri, @@ -5376,7 +5380,7 @@ class ValuesRouteV2E2ESpec extends E2ESpec { val getRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(resourceIri, "UTF-8")}?version=${URLEncoder .encode("2018-05-28T15:52:03.897Z", "UTF-8")}") val getResponse: HttpResponse = singleAwaitingRequest(getRequest) - val getResponseAsString = responseToString(getResponse) + val getResponseAsString = responseToString(getResponse) assert(getResponse.status == StatusCodes.OK, getResponseAsString) } diff --git a/webapi/src/test/scala/org/knora/webapi/e2e/v2/ValuesV2R2RSpec.scala b/webapi/src/test/scala/org/knora/webapi/e2e/v2/ValuesV2R2RSpec.scala index 650a45a292..40af60d438 100644 --- a/webapi/src/test/scala/org/knora/webapi/e2e/v2/ValuesV2R2RSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/e2e/v2/ValuesV2R2RSpec.scala @@ -53,7 +53,7 @@ class ValuesV2R2RSpec extends R2RSpec { private val aThingPictureIri = "http://rdfh.ch/0001/a-thing-picture" private val anythingUserEmail = SharedTestDataADM.anythingUser1.email - private val password = SharedTestDataADM.testPass + private val password = SharedTestDataADM.testPass private val stillImageFileValueIri = new MutableTestIri diff --git a/webapi/src/test/scala/org/knora/webapi/it/VersionRouteITSpec.scala b/webapi/src/test/scala/org/knora/webapi/it/VersionRouteITSpec.scala index 0ffc66bd60..6e7f88e8eb 100644 --- a/webapi/src/test/scala/org/knora/webapi/it/VersionRouteITSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/it/VersionRouteITSpec.scala @@ -17,10 +17,9 @@ import scala.concurrent.duration._ import scala.languageFeature.postfixOps object VersionRouteITSpec { - val config: Config = ConfigFactory.parseString( - """ - |akka.loglevel = "DEBUG" - |akka.stdout-loglevel = "DEBUG" + val config: Config = ConfigFactory.parseString(""" + |akka.loglevel = "DEBUG" + |akka.stdout-loglevel = "DEBUG" """.stripMargin) } @@ -30,7 +29,7 @@ object VersionRouteITSpec { class VersionRouteITSpec extends ITKnoraLiveSpec(VersionRouteITSpec.config) { private def getJsonResponse: JsObject = { - val request = Get(baseApiUrl + s"/version") + val request = Get(baseApiUrl + s"/version") val response: HttpResponse = singleAwaitingRequest(request) val responseBody: String = Await.result(response.entity.toStrict(10.seconds).map(_.data.decodeString("UTF-8")), 10.seconds) @@ -40,7 +39,7 @@ class VersionRouteITSpec extends ITKnoraLiveSpec(VersionRouteITSpec.config) { private def checkNonEmpty(field: String): Boolean = { val responseBodyJson = getJsonResponse - var result = false + var result = false try { val value = responseBodyJson.fields(field).toString().replaceAll("\"", "") result = !value.equals("") @@ -53,14 +52,14 @@ class VersionRouteITSpec extends ITKnoraLiveSpec(VersionRouteITSpec.config) { "The Version Route" should { "return 'OK'" in { - val request = Get(baseApiUrl + s"/version") + val request = Get(baseApiUrl + s"/version") val response: HttpResponse = singleAwaitingRequest(request) response.status should be(StatusCodes.OK) } "return 'version' as name" in { val responseBodyJson = getJsonResponse - val value = responseBodyJson.fields("name").toString().replaceAll("\"", "") + val value = responseBodyJson.fields("name").toString().replaceAll("\"", "") assert(value.equals("version")) } diff --git a/webapi/src/test/scala/org/knora/webapi/it/v1/DrawingsGodsV1ITSpec.scala b/webapi/src/test/scala/org/knora/webapi/it/v1/DrawingsGodsV1ITSpec.scala index 27d0371e23..194fcbca34 100644 --- a/webapi/src/test/scala/org/knora/webapi/it/v1/DrawingsGodsV1ITSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/it/v1/DrawingsGodsV1ITSpec.scala @@ -60,9 +60,9 @@ class DrawingsGodsV1ITSpec "issue: https://github.com/dhlab-basel/Knora/issues/408" should { val drawingsOfGodsUserEmail = "ddd1@unil.ch" - val testPass = "test" - val pathToChlaus = Paths.get("..", "test_data/test_route/images/Chlaus.jpg") - var loginToken: String = "" + val testPass = "test" + val pathToChlaus = Paths.get("..", "test_data/test_route/images/Chlaus.jpg") + var loginToken: String = "" "log in as a Knora user" in { /* Correct username and correct password */ @@ -75,7 +75,7 @@ class DrawingsGodsV1ITSpec |} """.stripMargin - val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) + val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) val response: HttpResponse = singleAwaitingRequest(request) assert(response.status == StatusCodes.OK) diff --git a/webapi/src/test/scala/org/knora/webapi/it/v1/ErrorV1ITSpec.scala b/webapi/src/test/scala/org/knora/webapi/it/v1/ErrorV1ITSpec.scala index d66f9e5e98..e570f4c13a 100644 --- a/webapi/src/test/scala/org/knora/webapi/it/v1/ErrorV1ITSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/it/v1/ErrorV1ITSpec.scala @@ -17,7 +17,7 @@ import scala.concurrent.duration._ class ErrorV1ITSpec extends ITKnoraLiveSpec with TriplestoreJsonProtocol { "Make a request that causes an internal server error" in { - val request = Get(baseApiUrl + "/v1/error/unitMsg") + val request = Get(baseApiUrl + "/v1/error/unitMsg") val response = singleAwaitingRequest(request, 5.seconds) // println(response.toString()) assert(response.status == StatusCodes.InternalServerError) diff --git a/webapi/src/test/scala/org/knora/webapi/it/v1/KnoraSipiIntegrationV1ITSpec.scala b/webapi/src/test/scala/org/knora/webapi/it/v1/KnoraSipiIntegrationV1ITSpec.scala index f781691175..7e85d11279 100644 --- a/webapi/src/test/scala/org/knora/webapi/it/v1/KnoraSipiIntegrationV1ITSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/it/v1/KnoraSipiIntegrationV1ITSpec.scala @@ -50,56 +50,56 @@ class KnoraSipiIntegrationV1ITSpec RdfDataObject(path = "test_data/all_data/anything-data.ttl", name = "http://www.knora.org/data/0001/anything") ) - private val userEmail = SharedTestDataADM.rootUser.email - private val password = SharedTestDataADM.testPass - private val pathToChlaus = Paths.get("..", "test_data/test_route/images/Chlaus.jpg") - private val pathToMarbles = Paths.get("..", "test_data/test_route/images/marbles.tif") + private val userEmail = SharedTestDataADM.rootUser.email + private val password = SharedTestDataADM.testPass + private val pathToChlaus = Paths.get("..", "test_data/test_route/images/Chlaus.jpg") + private val pathToMarbles = Paths.get("..", "test_data/test_route/images/marbles.tif") private val pathToXSLTransformation = Paths.get("..", "test_data/test_route/texts/letterToHtml.xsl") private val pathToMappingWithXSLT = Paths.get("..", "test_data/test_route/texts/mappingForLetterWithXSLTransformation.xml") private val secondPageIri = new MutableTestIri - private val pathToBEOLBodyXSLTransformation = Paths.get("..", "test_data/test_route/texts/beol/standoffToTEI.xsl") - private val pathToBEOLStandoffTEIMapping = Paths.get("..", "test_data/test_route/texts/beol/BEOLTEIMapping.xml") + private val pathToBEOLBodyXSLTransformation = Paths.get("..", "test_data/test_route/texts/beol/standoffToTEI.xsl") + private val pathToBEOLStandoffTEIMapping = Paths.get("..", "test_data/test_route/texts/beol/BEOLTEIMapping.xml") private val pathToBEOLHeaderXSLTransformation = Paths.get("..", "test_data/test_route/texts/beol/header.xsl") - private val pathToBEOLGravsearchTemplate = Paths.get("..", "test_data/test_route/texts/beol/gravsearch.txt") - private val pathToBEOLLetterMapping = Paths.get("..", "test_data/test_route/texts/beol/testLetter/beolMapping.xml") - private val pathToBEOLBulkXML = Paths.get("..", "test_data/test_route/texts/beol/testLetter/bulk.xml") - private val letterIri = new MutableTestIri - private val gravsearchTemplateIri = new MutableTestIri - - private val pdfResourceIri = new MutableTestIri - private val zipResourceIri = new MutableTestIri - private val wavResourceIri = new MutableTestIri + private val pathToBEOLGravsearchTemplate = Paths.get("..", "test_data/test_route/texts/beol/gravsearch.txt") + private val pathToBEOLLetterMapping = Paths.get("..", "test_data/test_route/texts/beol/testLetter/beolMapping.xml") + private val pathToBEOLBulkXML = Paths.get("..", "test_data/test_route/texts/beol/testLetter/bulk.xml") + private val letterIri = new MutableTestIri + private val gravsearchTemplateIri = new MutableTestIri + + private val pdfResourceIri = new MutableTestIri + private val zipResourceIri = new MutableTestIri + private val wavResourceIri = new MutableTestIri private val videoResourceIri = new MutableTestIri private val minimalPdfOriginalFilename = "minimal.pdf" - private val pathToMinimalPdf = Paths.get("..", s"test_data/test_route/files/$minimalPdfOriginalFilename") - private val minimalPdfWidth = 1250 - private val minimalPdfHeight = 600 + private val pathToMinimalPdf = Paths.get("..", s"test_data/test_route/files/$minimalPdfOriginalFilename") + private val minimalPdfWidth = 1250 + private val minimalPdfHeight = 600 private val testPdfOriginalFilename = "test.pdf" - private val pathToTestPdf = Paths.get("..", s"test_data/test_route/files/$testPdfOriginalFilename") - private val testPdfWidth = 2480 - private val testPdfHeight = 3508 + private val pathToTestPdf = Paths.get("..", s"test_data/test_route/files/$testPdfOriginalFilename") + private val testPdfWidth = 2480 + private val testPdfHeight = 3508 private val minimalZipOriginalFilename = "minimal.zip" - private val pathToMinimalZip = Paths.get("..", s"test_data/test_route/files/$minimalZipOriginalFilename") + private val pathToMinimalZip = Paths.get("..", s"test_data/test_route/files/$minimalZipOriginalFilename") private val testZipOriginalFilename = "test.zip" - private val pathToTestZip = Paths.get("..", s"test_data/test_route/files/$testZipOriginalFilename") + private val pathToTestZip = Paths.get("..", s"test_data/test_route/files/$testZipOriginalFilename") private val minimalWavOriginalFilename = "minimal.wav" - private val pathToMinimalWav = Paths.get("..", s"test_data/test_route/files/$minimalWavOriginalFilename") + private val pathToMinimalWav = Paths.get("..", s"test_data/test_route/files/$minimalWavOriginalFilename") private val testWavOriginalFilename = "test.wav" - private val pathToTestWav = Paths.get("..", s"test_data/test_route/files/$testWavOriginalFilename") + private val pathToTestWav = Paths.get("..", s"test_data/test_route/files/$testWavOriginalFilename") private val testVideoOriginalFilename = "testVideo.mp4" - private val pathToTestVideo = Paths.get("..", s"test_data/test_route/files/$testVideoOriginalFilename") + private val pathToTestVideo = Paths.get("..", s"test_data/test_route/files/$testVideoOriginalFilename") private val testVideo2OriginalFilename = "testVideo2.mp4" - private val pathToTestVideo2 = Paths.get("..", s"test_data/test_route/files/$testVideoOriginalFilename") + private val pathToTestVideo2 = Paths.get("..", s"test_data/test_route/files/$testVideoOriginalFilename") /** * Adds the IRI of a XSL transformation to the given mapping. @@ -191,7 +191,7 @@ class KnoraSipiIntegrationV1ITSpec |} """.stripMargin - val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) + val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) val response: HttpResponse = singleAwaitingRequest(request) assert(response.status == StatusCodes.OK) @@ -285,7 +285,7 @@ class KnoraSipiIntegrationV1ITSpec val knoraParams = JsObject( Map( "restype_id" -> JsString("http://www.knora.org/ontology/0001/anything#Thing"), - "label" -> JsString("Wild thing"), + "label" -> JsString("Wild thing"), "project_id" -> JsString("http://rdfh.ch/projects/0001"), "properties" -> JsObject( Map( @@ -293,7 +293,7 @@ class KnoraSipiIntegrationV1ITSpec JsObject( Map( "richtext_value" -> JsObject( - "xml" -> JsString(standoffXml), + "xml" -> JsString(standoffXml), "mapping_id" -> JsString("http://rdfh.ch/standoff/mappings/StandardMapping") ) ) @@ -382,8 +382,8 @@ class KnoraSipiIntegrationV1ITSpec baseApiUrl + "/v1/resources/" + URLEncoder.encode(pageResourceIri, "UTF-8") ) ~> addCredentials(BasicHttpCredentials(userEmail, password)) val pageJson: JsObject = getResponseJson(knoraRequestNewPageResource) - val locdata = pageJson.fields("resinfo").asJsObject.fields("locdata").asJsObject - val origname = locdata.fields("origname").asInstanceOf[JsString].value + val locdata = pageJson.fields("resinfo").asJsObject.fields("locdata").asJsObject + val origname = locdata.fields("origname").asInstanceOf[JsString].value val imageUrl = locdata.fields("path").asInstanceOf[JsString].value.replace("http://0.0.0.0:1024", baseInternalSipiUrl) assert(origname == dest.getFileName.toString) @@ -411,10 +411,10 @@ class KnoraSipiIntegrationV1ITSpec val knoraParams = JsObject( Map( "restype_id" -> JsString("http://www.knora.org/ontology/knora-base#XSLTransformation"), - "label" -> JsString("XSLT"), + "label" -> JsString("XSLT"), "project_id" -> JsString("http://rdfh.ch/projects/0001"), "properties" -> JsObject(), - "file" -> JsString(uploadedFile.internalFilename) + "file" -> JsString(uploadedFile.internalFilename) ) ) @@ -532,10 +532,10 @@ class KnoraSipiIntegrationV1ITSpec val bodyXsltParams = JsObject( Map( "restype_id" -> JsString("http://www.knora.org/ontology/knora-base#XSLTransformation"), - "label" -> JsString("XSLT"), + "label" -> JsString("XSLT"), "project_id" -> JsString("http://rdfh.ch/projects/yTerZGyxjZVqFMNNKXCDPF"), "properties" -> JsObject(), - "file" -> JsString(uploadedBodyXsltFile.internalFilename) + "file" -> JsString(uploadedBodyXsltFile.internalFilename) ) ) @@ -602,10 +602,10 @@ class KnoraSipiIntegrationV1ITSpec val gravsearchTemplateParams = JsObject( Map( "restype_id" -> JsString("http://www.knora.org/ontology/knora-base#TextRepresentation"), - "label" -> JsString("BEOL Gravsearch template"), + "label" -> JsString("BEOL Gravsearch template"), "project_id" -> JsString("http://rdfh.ch/projects/yTerZGyxjZVqFMNNKXCDPF"), "properties" -> JsObject(), - "file" -> JsString(uploadedGravsearchTemplateFile.internalFilename) + "file" -> JsString(uploadedGravsearchTemplateFile.internalFilename) ) ) @@ -637,10 +637,10 @@ class KnoraSipiIntegrationV1ITSpec val headerXsltParams = JsObject( Map( "restype_id" -> JsString("http://www.knora.org/ontology/knora-base#XSLTransformation"), - "label" -> JsString("BEOL header XSLT"), + "label" -> JsString("BEOL header XSLT"), "project_id" -> JsString("http://rdfh.ch/projects/yTerZGyxjZVqFMNNKXCDPF"), "properties" -> JsObject(), - "file" -> JsString(uploadedHeaderXsltFile.internalFilename) + "file" -> JsString(uploadedHeaderXsltFile.internalFilename) ) ) @@ -761,10 +761,10 @@ class KnoraSipiIntegrationV1ITSpec val createDocumentResourceParams = JsObject( Map( "restype_id" -> JsString("http://www.knora.org/ontology/0001/anything#ThingDocument"), - "label" -> JsString("PDF file"), + "label" -> JsString("PDF file"), "project_id" -> JsString("http://rdfh.ch/projects/0001"), "properties" -> JsObject(), - "file" -> JsString(uploadedPdfFile.internalFilename) + "file" -> JsString(uploadedPdfFile.internalFilename) ) ) @@ -790,9 +790,9 @@ class KnoraSipiIntegrationV1ITSpec ) ~> addCredentials(BasicHttpCredentials(userEmail, password)) val documentResourceResponse: JsObject = getResponseJson(documentResourceRequest) - val locdata = documentResourceResponse.fields("resinfo").asJsObject.fields("locdata").asJsObject - val nx = locdata.fields("nx").asInstanceOf[JsNumber].value.toInt - val ny = locdata.fields("ny").asInstanceOf[JsNumber].value.toInt + val locdata = documentResourceResponse.fields("resinfo").asJsObject.fields("locdata").asJsObject + val nx = locdata.fields("nx").asInstanceOf[JsNumber].value.toInt + val ny = locdata.fields("ny").asInstanceOf[JsNumber].value.toInt val pdfUrl = locdata.fields("path").asInstanceOf[JsString].value.replace("http://0.0.0.0:1024", baseInternalSipiUrl) assert(nx == minimalPdfWidth) @@ -834,9 +834,9 @@ class KnoraSipiIntegrationV1ITSpec ) ~> addCredentials(BasicHttpCredentials(userEmail, password)) val documentResourceResponse: JsObject = getResponseJson(documentResourceRequest) - val locdata = documentResourceResponse.fields("resinfo").asJsObject.fields("locdata").asJsObject - val nx = locdata.fields("nx").asInstanceOf[JsNumber].value.toInt - val ny = locdata.fields("ny").asInstanceOf[JsNumber].value.toInt + val locdata = documentResourceResponse.fields("resinfo").asJsObject.fields("locdata").asJsObject + val nx = locdata.fields("nx").asInstanceOf[JsNumber].value.toInt + val ny = locdata.fields("ny").asInstanceOf[JsNumber].value.toInt assert(nx == testPdfWidth) assert(ny == testPdfHeight) } @@ -855,10 +855,10 @@ class KnoraSipiIntegrationV1ITSpec val archiveResourceParams = JsObject( Map( "restype_id" -> JsString("http://www.knora.org/ontology/knora-base#ArchiveRepresentation"), - "label" -> JsString("Zip file"), + "label" -> JsString("Zip file"), "project_id" -> JsString("http://rdfh.ch/projects/0001"), "properties" -> JsObject(), - "file" -> JsString(uploadedZipFile.internalFilename) + "file" -> JsString(uploadedZipFile.internalFilename) ) ) @@ -884,7 +884,7 @@ class KnoraSipiIntegrationV1ITSpec ) ~> addCredentials(BasicHttpCredentials(userEmail, password)) val documentResourceResponse: JsObject = getResponseJson(documentResourceRequest) - val locdata = documentResourceResponse.fields("resinfo").asJsObject.fields("locdata").asJsObject + val locdata = documentResourceResponse.fields("resinfo").asJsObject.fields("locdata").asJsObject val zipUrl = locdata.fields("path").asInstanceOf[JsString].value.replace("http://0.0.0.0:1024", baseInternalSipiUrl) @@ -924,7 +924,7 @@ class KnoraSipiIntegrationV1ITSpec ) ~> addCredentials(BasicHttpCredentials(userEmail, password)) val documentResourceResponse: JsObject = getResponseJson(documentResourceRequest) - val locdata = documentResourceResponse.fields("resinfo").asJsObject.fields("locdata").asJsObject + val locdata = documentResourceResponse.fields("resinfo").asJsObject.fields("locdata").asJsObject val zipUrl = locdata.fields("path").asInstanceOf[JsString].value.replace("http://0.0.0.0:1024", baseInternalSipiUrl) @@ -947,10 +947,10 @@ class KnoraSipiIntegrationV1ITSpec val createAudioResourceParams = JsObject( Map( "restype_id" -> JsString("http://www.knora.org/ontology/knora-base#AudioRepresentation"), - "label" -> JsString("Wav file"), + "label" -> JsString("Wav file"), "project_id" -> JsString("http://rdfh.ch/projects/0001"), "properties" -> JsObject(), - "file" -> JsString(uploadedWavFile.internalFilename) + "file" -> JsString(uploadedWavFile.internalFilename) ) ) @@ -976,7 +976,7 @@ class KnoraSipiIntegrationV1ITSpec ) ~> addCredentials(BasicHttpCredentials(userEmail, password)) val audioResourceResponse: JsObject = getResponseJson(audioResourceRequest) - val locdata = audioResourceResponse.fields("resinfo").asJsObject.fields("locdata").asJsObject + val locdata = audioResourceResponse.fields("resinfo").asJsObject.fields("locdata").asJsObject val zipUrl = locdata.fields("path").asInstanceOf[JsString].value.replace("http://0.0.0.0:1024", baseInternalSipiUrl) @@ -1016,7 +1016,7 @@ class KnoraSipiIntegrationV1ITSpec ) ~> addCredentials(BasicHttpCredentials(userEmail, password)) val audioResourceResponse: JsObject = getResponseJson(audioResourceRequest) - val locdata = audioResourceResponse.fields("resinfo").asJsObject.fields("locdata").asJsObject + val locdata = audioResourceResponse.fields("resinfo").asJsObject.fields("locdata").asJsObject val wavUrl = locdata.fields("path").asInstanceOf[JsString].value.replace("http://0.0.0.0:1024", baseInternalSipiUrl) @@ -1040,10 +1040,10 @@ class KnoraSipiIntegrationV1ITSpec val createVideoResourceParams = JsObject( Map( "restype_id" -> JsString("http://www.knora.org/ontology/knora-base#MovingImageRepresentation"), - "label" -> JsString("Wav file"), + "label" -> JsString("Wav file"), "project_id" -> JsString("http://rdfh.ch/projects/0001"), "properties" -> JsObject(), - "file" -> JsString(uploadedVideoFile.internalFilename) + "file" -> JsString(uploadedVideoFile.internalFilename) ) ) @@ -1069,7 +1069,7 @@ class KnoraSipiIntegrationV1ITSpec ) ~> addCredentials(BasicHttpCredentials(userEmail, password)) val videoResourceResponse: JsObject = getResponseJson(videoResourceRequest) - val locdata = videoResourceResponse.fields("resinfo").asJsObject.fields("locdata").asJsObject + val locdata = videoResourceResponse.fields("resinfo").asJsObject.fields("locdata").asJsObject val videoUrl = locdata.fields("path").asInstanceOf[JsString].value.replace("http://0.0.0.0:1024", baseInternalSipiUrl) @@ -1109,7 +1109,7 @@ class KnoraSipiIntegrationV1ITSpec ) ~> addCredentials(BasicHttpCredentials(userEmail, password)) val videoResourceResponse: JsObject = getResponseJson(videoResourceRequest) - val locdata = videoResourceResponse.fields("resinfo").asJsObject.fields("locdata").asJsObject + val locdata = videoResourceResponse.fields("resinfo").asJsObject.fields("locdata").asJsObject val videoUrl = locdata.fields("path").asInstanceOf[JsString].value.replace("http://0.0.0.0:1024", baseInternalSipiUrl) diff --git a/webapi/src/test/scala/org/knora/webapi/it/v2/KnoraSipiIntegrationV2ITSpec.scala b/webapi/src/test/scala/org/knora/webapi/it/v2/KnoraSipiIntegrationV2ITSpec.scala index 41fd551949..4315878c62 100644 --- a/webapi/src/test/scala/org/knora/webapi/it/v2/KnoraSipiIntegrationV2ITSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/it/v2/KnoraSipiIntegrationV2ITSpec.scala @@ -43,82 +43,82 @@ class KnoraSipiIntegrationV2ITSpec with TriplestoreJsonProtocol { private implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - private val anythingUserEmail = SharedTestDataADM.anythingAdminUser.email + private val anythingUserEmail = SharedTestDataADM.anythingAdminUser.email private val incunabulaUserEmail = SharedTestDataADM.incunabulaMemberUser.email - private val password = SharedTestDataADM.testPass + private val password = SharedTestDataADM.testPass - private val stillImageResourceIri = new MutableTestIri + private val stillImageResourceIri = new MutableTestIri private val stillImageFileValueIri = new MutableTestIri - private val pdfResourceIri = new MutableTestIri - private val pdfValueIri = new MutableTestIri - private val xmlResourceIri = new MutableTestIri - private val xmlValueIri = new MutableTestIri - private val csvResourceIri = new MutableTestIri - private val csvValueIri = new MutableTestIri - private val zipResourceIri = new MutableTestIri - private val zipValueIri = new MutableTestIri - private val wavResourceIri = new MutableTestIri - private val wavValueIri = new MutableTestIri + private val pdfResourceIri = new MutableTestIri + private val pdfValueIri = new MutableTestIri + private val xmlResourceIri = new MutableTestIri + private val xmlValueIri = new MutableTestIri + private val csvResourceIri = new MutableTestIri + private val csvValueIri = new MutableTestIri + private val zipResourceIri = new MutableTestIri + private val zipValueIri = new MutableTestIri + private val wavResourceIri = new MutableTestIri + private val wavValueIri = new MutableTestIri private val videoResourceIri = new MutableTestIri - private val videoValueIri = new MutableTestIri + private val videoValueIri = new MutableTestIri private val marblesOriginalFilename = "marbles.tif" - private val pathToMarbles = Paths.get("..", s"test_data/test_route/images/$marblesOriginalFilename") - private val marblesWidth = 1419 - private val marblesHeight = 1001 + private val pathToMarbles = Paths.get("..", s"test_data/test_route/images/$marblesOriginalFilename") + private val marblesWidth = 1419 + private val marblesHeight = 1001 private val pathToMarblesWithWrongExtension = Paths.get("..", "test_data/test_route/images/marbles_with_wrong_extension.jpg") private val trp88OriginalFilename = "Trp88.tiff" - private val pathToTrp88 = Paths.get("..", s"test_data/test_route/images/$trp88OriginalFilename") - private val trp88Width = 499 - private val trp88Height = 630 + private val pathToTrp88 = Paths.get("..", s"test_data/test_route/images/$trp88OriginalFilename") + private val trp88Width = 499 + private val trp88Height = 630 private val minimalPdfOriginalFilename = "minimal.pdf" - private val pathToMinimalPdf = Paths.get("..", s"test_data/test_route/files/$minimalPdfOriginalFilename") - private val minimalPdfWidth = 1250 - private val minimalPdfHeight = 600 + private val pathToMinimalPdf = Paths.get("..", s"test_data/test_route/files/$minimalPdfOriginalFilename") + private val minimalPdfWidth = 1250 + private val minimalPdfHeight = 600 private val testPdfOriginalFilename = "test.pdf" - private val pathToTestPdf = Paths.get("..", s"test_data/test_route/files/$testPdfOriginalFilename") - private val testPdfWidth = 2480 - private val testPdfHeight = 3508 + private val pathToTestPdf = Paths.get("..", s"test_data/test_route/files/$testPdfOriginalFilename") + private val testPdfWidth = 2480 + private val testPdfHeight = 3508 private val csv1OriginalFilename = "eggs.csv" - private val pathToCsv1 = Paths.get("..", s"test_data/test_route/files/$csv1OriginalFilename") + private val pathToCsv1 = Paths.get("..", s"test_data/test_route/files/$csv1OriginalFilename") private val csv2OriginalFilename = "spam.csv" - private val pathToCsv2 = Paths.get("..", s"test_data/test_route/files/$csv2OriginalFilename") + private val pathToCsv2 = Paths.get("..", s"test_data/test_route/files/$csv2OriginalFilename") private val xml1OriginalFilename = "test1.xml" - private val pathToXml1 = Paths.get("..", s"test_data/test_route/files/$xml1OriginalFilename") + private val pathToXml1 = Paths.get("..", s"test_data/test_route/files/$xml1OriginalFilename") private val xml2OriginalFilename = "test2.xml" - private val pathToXml2 = Paths.get("..", s"test_data/test_route/files/$xml2OriginalFilename") + private val pathToXml2 = Paths.get("..", s"test_data/test_route/files/$xml2OriginalFilename") private val minimalZipOriginalFilename = "minimal.zip" - private val pathToMinimalZip = Paths.get("..", s"test_data/test_route/files/$minimalZipOriginalFilename") + private val pathToMinimalZip = Paths.get("..", s"test_data/test_route/files/$minimalZipOriginalFilename") private val testZipOriginalFilename = "test.zip" - private val pathToTestZip = Paths.get("..", s"test_data/test_route/files/$testZipOriginalFilename") + private val pathToTestZip = Paths.get("..", s"test_data/test_route/files/$testZipOriginalFilename") private val test7zOriginalFilename = "test.7z" - private val pathToTest7z = Paths.get("..", s"test_data/test_route/files/$test7zOriginalFilename") + private val pathToTest7z = Paths.get("..", s"test_data/test_route/files/$test7zOriginalFilename") private val minimalWavOriginalFilename = "minimal.wav" - private val pathToMinimalWav = Paths.get("..", s"test_data/test_route/files/$minimalWavOriginalFilename") - private val minimalWavDuration = BigDecimal("0.0") + private val pathToMinimalWav = Paths.get("..", s"test_data/test_route/files/$minimalWavOriginalFilename") + private val minimalWavDuration = BigDecimal("0.0") private val testWavOriginalFilename = "test.wav" - private val pathToTestWav = Paths.get("..", s"test_data/test_route/files/$testWavOriginalFilename") + private val pathToTestWav = Paths.get("..", s"test_data/test_route/files/$testWavOriginalFilename") private val testVideoOriginalFilename = "testVideo.mp4" - private val pathToTestVideo = Paths.get("..", s"test_data/test_route/files/$testVideoOriginalFilename") + private val pathToTestVideo = Paths.get("..", s"test_data/test_route/files/$testVideoOriginalFilename") private val testVideo2OriginalFilename = "testVideo2.mp4" - private val pathToTestVideo2 = Paths.get("..", s"test_data/test_route/files/$testVideo2OriginalFilename") + private val pathToTestVideo2 = Paths.get("..", s"test_data/test_route/files/$testVideo2OriginalFilename") private val thingDocumentIRI = "http://0.0.0.0:3333/ontology/0001/anything/v2#ThingDocument" @@ -249,7 +249,7 @@ class KnoraSipiIntegrationV2ITSpec validationFun = stringFormatter.toSparqlEncodedString ) - val width = savedValue.requireInt(OntologyConstants.KnoraApiV2Complex.StillImageFileValueHasDimX) + val width = savedValue.requireInt(OntologyConstants.KnoraApiV2Complex.StillImageFileValueHasDimX) val height = savedValue.requireInt(OntologyConstants.KnoraApiV2Complex.StillImageFileValueHasDimY) SavedImage( @@ -276,8 +276,8 @@ class KnoraSipiIntegrationV2ITSpec ) val pageCount: Option[Int] = savedValue.maybeInt(OntologyConstants.KnoraApiV2Complex.DocumentFileValueHasPageCount) - val dimX: Option[Int] = savedValue.maybeInt(OntologyConstants.KnoraApiV2Complex.DocumentFileValueHasDimX) - val dimY: Option[Int] = savedValue.maybeInt(OntologyConstants.KnoraApiV2Complex.DocumentFileValueHasDimY) + val dimX: Option[Int] = savedValue.maybeInt(OntologyConstants.KnoraApiV2Complex.DocumentFileValueHasDimX) + val dimY: Option[Int] = savedValue.maybeInt(OntologyConstants.KnoraApiV2Complex.DocumentFileValueHasDimY) SavedDocument( internalFilename = internalFilename, @@ -384,7 +384,7 @@ class KnoraSipiIntegrationV2ITSpec ) // Send a POST request to Sipi, asking it to convert the image to JPEG 2000 and store it in a temporary file. - val sipiRequest = Post(s"$baseInternalSipiUrl/upload?token=$invalidToken", sipiFormData) + val sipiRequest = Post(s"$baseInternalSipiUrl/upload?token=$invalidToken", sipiFormData) val sipiResponse = singleAwaitingRequest(sipiRequest) assert(sipiResponse.status == StatusCodes.Unauthorized) } @@ -400,7 +400,7 @@ class KnoraSipiIntegrationV2ITSpec |} """.stripMargin - val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) + val request = Post(baseApiUrl + s"/v2/authentication", HttpEntity(ContentTypes.`application/json`, params)) val response: HttpResponse = singleAwaitingRequest(request) assert(response.status == StatusCodes.OK) @@ -443,7 +443,7 @@ class KnoraSipiIntegrationV2ITSpec stillImageResourceIri.set(responseJsonDoc.body.requireIDAsKnoraDataIri.toString) // Get the resource from Knora. - val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(stillImageResourceIri.get, "UTF-8")}") + val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(stillImageResourceIri.get, "UTF-8")}") val resource: JsonLDDocument = getResponseJsonLD(knoraGetRequest) assert( resource.requireTypeAsKnoraTypeIri.toString == "http://0.0.0.0:3333/ontology/0001/anything/v2#ThingPicture" @@ -519,7 +519,7 @@ class KnoraSipiIntegrationV2ITSpec // Get the resource from Knora. val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(stillImageResourceIri.get, "UTF-8")}") - val resource = getResponseJsonLD(knoraGetRequest) + val resource = getResponseJsonLD(knoraGetRequest) // Get the new file value from the resource. val savedValue: JsonLDObject = getValueFromResource( @@ -572,7 +572,7 @@ class KnoraSipiIntegrationV2ITSpec // Request the temporary image from Sipi. val sipiGetTmpFileRequest = Get(temporaryDirectDownloadUrl) - val sipiResponse = singleAwaitingRequest(sipiGetTmpFileRequest) + val sipiResponse = singleAwaitingRequest(sipiGetTmpFileRequest) assert(sipiResponse.status == StatusCodes.NotFound) } @@ -607,7 +607,7 @@ class KnoraSipiIntegrationV2ITSpec pdfResourceIri.set(responseJsonDoc.body.requireIDAsKnoraDataIri.toString) // Get the resource from Knora. - val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(pdfResourceIri.get, "UTF-8")}") + val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(pdfResourceIri.get, "UTF-8")}") val resource: JsonLDDocument = getResponseJsonLD(knoraGetRequest) assert(resource.requireTypeAsKnoraTypeIri.toString == thingDocumentIRI) @@ -673,7 +673,7 @@ class KnoraSipiIntegrationV2ITSpec // Get the resource from Knora. val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(pdfResourceIri.get, "UTF-8")}") - val resource = getResponseJsonLD(knoraGetRequest) + val resource = getResponseJsonLD(knoraGetRequest) // Get the new file value from the resource. val savedValue: JsonLDObject = getValueFromResource( @@ -755,7 +755,7 @@ class KnoraSipiIntegrationV2ITSpec // Get the resource from Knora. val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(resourceIri, "UTF-8")}") - val resource = getResponseJsonLD(knoraGetRequest) + val resource = getResponseJsonLD(knoraGetRequest) // Get the new file value from the resource. @@ -815,7 +815,7 @@ class KnoraSipiIntegrationV2ITSpec // Get the resource from Knora. val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(csvResourceIri.get, "UTF-8")}") - val resource = getResponseJsonLD(knoraGetRequest) + val resource = getResponseJsonLD(knoraGetRequest) // Get the new file value from the resource. val savedValue: JsonLDObject = getValueFromResource( @@ -885,7 +885,7 @@ class KnoraSipiIntegrationV2ITSpec // Get the resource from Knora. val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(resourceIri, "UTF-8")}") - val resource = getResponseJsonLD(knoraGetRequest) + val resource = getResponseJsonLD(knoraGetRequest) // Get the new file value from the resource. @@ -946,7 +946,7 @@ class KnoraSipiIntegrationV2ITSpec // Get the resource from Knora. val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(xmlResourceIri.get, "UTF-8")}") - val resource = getResponseJsonLD(knoraGetRequest) + val resource = getResponseJsonLD(knoraGetRequest) // Get the new file value from the resource. val savedValue: JsonLDObject = getValueFromResource( @@ -1011,7 +1011,7 @@ class KnoraSipiIntegrationV2ITSpec zipResourceIri.set(responseJsonDoc.body.requireIDAsKnoraDataIri.toString) // Get the resource from Knora. - val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(zipResourceIri.get, "UTF-8")}") + val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(zipResourceIri.get, "UTF-8")}") val resource: JsonLDDocument = getResponseJsonLD(knoraGetRequest) resource.requireTypeAsKnoraTypeIri.toString should equal( @@ -1077,7 +1077,7 @@ class KnoraSipiIntegrationV2ITSpec // Get the resource from Knora. val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(zipResourceIri.get, "UTF-8")}") - val resource = getResponseJsonLD(knoraGetRequest) + val resource = getResponseJsonLD(knoraGetRequest) // Get the new file value from the resource. val savedValue: JsonLDObject = getValueFromResource( @@ -1119,7 +1119,7 @@ class KnoraSipiIntegrationV2ITSpec zipResourceIri.set(responseJsonDoc.body.requireIDAsKnoraDataIri.toString) // Get the resource from Knora. - val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(zipResourceIri.get, "UTF-8")}") + val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(zipResourceIri.get, "UTF-8")}") val resource: JsonLDDocument = getResponseJsonLD(knoraGetRequest) resource.requireTypeAsKnoraTypeIri.toString should equal( @@ -1178,7 +1178,7 @@ class KnoraSipiIntegrationV2ITSpec wavResourceIri.set(responseJsonDoc.body.requireIDAsKnoraDataIri.toString) // Get the resource from Knora. - val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(wavResourceIri.get, "UTF-8")}") + val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(wavResourceIri.get, "UTF-8")}") val resource: JsonLDDocument = getResponseJsonLD(knoraGetRequest) assert( resource.requireTypeAsKnoraTypeIri.toString == "http://api.knora.org/ontology/knora-api/v2#AudioRepresentation" @@ -1243,7 +1243,7 @@ class KnoraSipiIntegrationV2ITSpec // Get the resource from Knora. val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(wavResourceIri.get, "UTF-8")}") - val resource = getResponseJsonLD(knoraGetRequest) + val resource = getResponseJsonLD(knoraGetRequest) // Get the new file value from the resource. val savedValue: JsonLDObject = getValueFromResource( @@ -1283,7 +1283,7 @@ class KnoraSipiIntegrationV2ITSpec videoResourceIri.set(responseJsonDoc.body.requireIDAsKnoraDataIri.toString) // Get the resource from Knora. - val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(videoResourceIri.get, "UTF-8")}") + val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(videoResourceIri.get, "UTF-8")}") val resource: JsonLDDocument = getResponseJsonLD(knoraGetRequest) assert( resource.requireTypeAsKnoraTypeIri.toString == "http://api.knora.org/ontology/knora-api/v2#MovingImageRepresentation" @@ -1347,7 +1347,7 @@ class KnoraSipiIntegrationV2ITSpec // Get the resource from Knora. val knoraGetRequest = Get(s"$baseApiUrl/v2/resources/${URLEncoder.encode(videoResourceIri.get, "UTF-8")}") - val resource = getResponseJsonLD(knoraGetRequest) + val resource = getResponseJsonLD(knoraGetRequest) // Get the new file value from the resource. val savedValue: JsonLDObject = getValueFromResource( diff --git a/webapi/src/test/scala/org/knora/webapi/messages/StringFormatterSpec.scala b/webapi/src/test/scala/org/knora/webapi/messages/StringFormatterSpec.scala index 1e6a7bf7b7..116ac0fd28 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/StringFormatterSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/StringFormatterSpec.scala @@ -121,12 +121,12 @@ class StringFormatterSpec extends CoreSpec() { "recognize the url of the dhlab site as a valid IRI" in { val testUrl: String = "http://dhlab.unibas.ch/" - val validIri = stringFormatter.validateAndEscapeIri(testUrl, throw AssertionException(s"Invalid IRI $testUrl")) + val validIri = stringFormatter.validateAndEscapeIri(testUrl, throw AssertionException(s"Invalid IRI $testUrl")) validIri should be(testUrl) } "recognize the url of the DaSCH site as a valid IRI" in { - val testUrl = "http://dasch.swiss" + val testUrl = "http://dasch.swiss" val validIri = stringFormatter.validateAndEscapeIri(testUrl, throw AssertionException(s"Invalid IRI $testUrl")) validIri should be(testUrl) } @@ -1015,11 +1015,11 @@ class StringFormatterSpec extends CoreSpec() { for (i <- 1 to totalIris) { val iriStr = s"http://0.0.0.0:3333/ontology/00FF/images/v2#class$i" - val iri = iriStr.toSmartIri.toOntologySchema(InternalSchema) + val iri = iriStr.toSmartIri.toOntologySchema(InternalSchema) } - val parseEnd = System.currentTimeMillis - val parseDuration = (parseEnd - parseStart).toDouble + val parseEnd = System.currentTimeMillis + val parseDuration = (parseEnd - parseStart).toDouble val parseDurationPerIri = parseDuration / totalIris.toDouble println(f"Parse and store $totalIris IRIs, $parseDuration ms, time per IRI $parseDurationPerIri%1.5f ms") @@ -1027,11 +1027,11 @@ class StringFormatterSpec extends CoreSpec() { for (i <- 1 to totalIris) { val iriStr = s"http://0.0.0.0:3333/ontology/00FF/images/v2#class$i" - val iri = iriStr.toSmartIri.toOntologySchema(InternalSchema) + val iri = iriStr.toSmartIri.toOntologySchema(InternalSchema) } - val retrieveEnd = System.currentTimeMillis - val retrieveDuration = (retrieveEnd - retrieveStart).toDouble + val retrieveEnd = System.currentTimeMillis + val retrieveDuration = (retrieveEnd - retrieveStart).toDouble val retrieveDurationPerIri = retrieveDuration / totalIris.toDouble println(f"Retrieve time $retrieveDuration ms, time per IRI $retrieveDurationPerIri%1.5f ms") @@ -1040,8 +1040,8 @@ class StringFormatterSpec extends CoreSpec() { "return the data named graph of a project with short code" in { val shortcode = SharedTestDataV1.imagesProjectInfo.shortcode val shortname = SharedTestDataV1.imagesProjectInfo.shortname - val expected = s"http://www.knora.org/data/$shortcode/$shortname" - val result = stringFormatter.projectDataNamedGraphV1(SharedTestDataV1.imagesProjectInfo) + val expected = s"http://www.knora.org/data/$shortcode/$shortname" + val result = stringFormatter.projectDataNamedGraphV1(SharedTestDataV1.imagesProjectInfo) result should be(expected) // check consistency of our test data @@ -1166,28 +1166,28 @@ class StringFormatterSpec extends CoreSpec() { "generate an ARK URL for a resource IRI without a timestamp" in { val resourceIri: IRI = "http://rdfh.ch/0001/cmfk1DMHRBiR4-_6HXpEFA" - val arkUrl = resourceIri.toSmartIri.fromResourceIriToArkUrl() + val arkUrl = resourceIri.toSmartIri.fromResourceIriToArkUrl() assert(arkUrl == "http://0.0.0.0:3336/ark:/72163/1/0001/cmfk1DMHRBiR4=_6HXpEFAn") } "generate an ARK URL for a resource IRI with a timestamp with a fractional part" in { val resourceIri: IRI = "http://rdfh.ch/0001/cmfk1DMHRBiR4-_6HXpEFA" - val timestamp = Instant.parse("2018-06-04T08:56:22.9876543Z") - val arkUrl = resourceIri.toSmartIri.fromResourceIriToArkUrl(maybeTimestamp = Some(timestamp)) + val timestamp = Instant.parse("2018-06-04T08:56:22.9876543Z") + val arkUrl = resourceIri.toSmartIri.fromResourceIriToArkUrl(maybeTimestamp = Some(timestamp)) assert(arkUrl == "http://0.0.0.0:3336/ark:/72163/1/0001/cmfk1DMHRBiR4=_6HXpEFAn.20180604T0856229876543Z") } "generate an ARK URL for a resource IRI with a timestamp with a leading zero" in { val resourceIri: IRI = "http://rdfh.ch/0001/cmfk1DMHRBiR4-_6HXpEFA" - val timestamp = Instant.parse("2018-06-04T08:56:22.098Z") - val arkUrl = resourceIri.toSmartIri.fromResourceIriToArkUrl(maybeTimestamp = Some(timestamp)) + val timestamp = Instant.parse("2018-06-04T08:56:22.098Z") + val arkUrl = resourceIri.toSmartIri.fromResourceIriToArkUrl(maybeTimestamp = Some(timestamp)) assert(arkUrl == "http://0.0.0.0:3336/ark:/72163/1/0001/cmfk1DMHRBiR4=_6HXpEFAn.20180604T085622098Z") } "generate an ARK URL for a resource IRI with a timestamp without a fractional part" in { val resourceIri: IRI = "http://rdfh.ch/0001/cmfk1DMHRBiR4-_6HXpEFA" - val timestamp = Instant.parse("2018-06-04T08:56:22Z") - val arkUrl = resourceIri.toSmartIri.fromResourceIriToArkUrl(maybeTimestamp = Some(timestamp)) + val timestamp = Instant.parse("2018-06-04T08:56:22Z") + val arkUrl = resourceIri.toSmartIri.fromResourceIriToArkUrl(maybeTimestamp = Some(timestamp)) assert(arkUrl == "http://0.0.0.0:3336/ark:/72163/1/0001/cmfk1DMHRBiR4=_6HXpEFAn.20180604T085622Z") } @@ -1352,9 +1352,9 @@ class StringFormatterSpec extends CoreSpec() { } "convert a UUID to Base-64 encoding and back again" in { - val uuid = UUID.randomUUID + val uuid = UUID.randomUUID val base64EncodedUuid = stringFormatter.base64EncodeUuid(uuid) - val base4DecodedUuid = stringFormatter.base64DecodeUuid(base64EncodedUuid) + val base4DecodedUuid = stringFormatter.base64DecodeUuid(base64EncodedUuid) uuid should be(base4DecodedUuid) } diff --git a/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/permissionsmessages/PermissionsMessagesADMSpec.scala b/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/permissionsmessages/PermissionsMessagesADMSpec.scala index e18f458810..c5879a7379 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/permissionsmessages/PermissionsMessagesADMSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/permissionsmessages/PermissionsMessagesADMSpec.scala @@ -842,7 +842,7 @@ class PermissionsMessagesADMSpec extends CoreSpec() { "querying the user's 'PermissionsDataADM' with 'hasPermissionFor'" should { "return true if the user is allowed to create a resource (root user)" in { - val projectIri = INCUNABULA_PROJECT_IRI + val projectIri = INCUNABULA_PROJECT_IRI val resourceClassIri = s"$INCUNABULA_ONTOLOGY_IRI#book" val result = SharedTestDataADM.rootUser.permissions.hasPermissionFor( @@ -856,7 +856,7 @@ class PermissionsMessagesADMSpec extends CoreSpec() { "return true if the user is allowed to create a resource (project admin user)" in { - val projectIri = INCUNABULA_PROJECT_IRI + val projectIri = INCUNABULA_PROJECT_IRI val resourceClassIri = s"$INCUNABULA_ONTOLOGY_IRI#book" val result = SharedTestDataADM.incunabulaProjectAdminUser.permissions @@ -867,7 +867,7 @@ class PermissionsMessagesADMSpec extends CoreSpec() { "return true if the user is allowed to create a resource (project member user)" in { - val projectIri = INCUNABULA_PROJECT_IRI + val projectIri = INCUNABULA_PROJECT_IRI val resourceClassIri = s"$INCUNABULA_ONTOLOGY_IRI#book" val result = SharedTestDataADM.incunabulaMemberUser.permissions @@ -877,7 +877,7 @@ class PermissionsMessagesADMSpec extends CoreSpec() { } "return false if the user is not allowed to create a resource" in { - val projectIri = INCUNABULA_PROJECT_IRI + val projectIri = INCUNABULA_PROJECT_IRI val resourceClassIri = s"$INCUNABULA_ONTOLOGY_IRI#book" val result = SharedTestDataADM.normalUser.permissions.hasPermissionFor( @@ -890,9 +890,9 @@ class PermissionsMessagesADMSpec extends CoreSpec() { } "return true if the user is allowed to create a resource (ProjectResourceCreateRestrictedPermission)" in { - val projectIri = IMAGES_PROJECT_IRI - val allowedResourceClassIri01 = s"$IMAGES_ONTOLOGY_IRI#bild" - val allowedResourceClassIri02 = s"$IMAGES_ONTOLOGY_IRI#bildformat" + val projectIri = IMAGES_PROJECT_IRI + val allowedResourceClassIri01 = s"$IMAGES_ONTOLOGY_IRI#bild" + val allowedResourceClassIri02 = s"$IMAGES_ONTOLOGY_IRI#bildformat" val notAllowedResourceClassIri = s"$IMAGES_ONTOLOGY_IRI#person" val result1 = SharedTestDataADM.imagesReviewerUser.permissions @@ -905,7 +905,7 @@ class PermissionsMessagesADMSpec extends CoreSpec() { } "return false if the user is not allowed to create a resource (ProjectResourceCreateRestrictedPermission)" in { - val projectIri = IMAGES_PROJECT_IRI + val projectIri = IMAGES_PROJECT_IRI val notAllowedResourceClassIri = s"$IMAGES_ONTOLOGY_IRI#person" val result = SharedTestDataADM.imagesReviewerUser.permissions @@ -918,14 +918,14 @@ class PermissionsMessagesADMSpec extends CoreSpec() { "return true if the user has the 'ProjectAdminAllPermission' (incunabula project admin user)" in { val projectIri = INCUNABULA_PROJECT_IRI - val result = SharedTestDataADM.incunabulaProjectAdminUser.permissions.hasProjectAdminAllPermissionFor(projectIri) + val result = SharedTestDataADM.incunabulaProjectAdminUser.permissions.hasProjectAdminAllPermissionFor(projectIri) result should be(true) } "return false if the user has the 'ProjectAdminAllPermission' (incunabula member user)" in { val projectIri = INCUNABULA_PROJECT_IRI - val result = SharedTestDataADM.incunabulaMemberUser.permissions.hasProjectAdminAllPermissionFor(projectIri) + val result = SharedTestDataADM.incunabulaMemberUser.permissions.hasProjectAdminAllPermissionFor(projectIri) result should be(false) } @@ -945,7 +945,7 @@ class PermissionsMessagesADMSpec extends CoreSpec() { "not update permission group if invalid permission IRI given" in { val permissionIri = "invalid-permission-iri" - val newGroupIri = SharedTestDataADM.imagesReviewerGroup.id + val newGroupIri = SharedTestDataADM.imagesReviewerGroup.id val caught = intercept[BadRequestException]( PermissionChangeGroupRequestADM( permissionIri = permissionIri, @@ -959,7 +959,7 @@ class PermissionsMessagesADMSpec extends CoreSpec() { "not update permission group if invalid group IRI given" in { val permissionIri = SharedPermissionsTestData.perm001_d1.iri - val newGroupIri = "invalid-group-iri" + val newGroupIri = "invalid-group-iri" val caught = intercept[BadRequestException]( PermissionChangeGroupRequestADM( permissionIri = permissionIri, @@ -972,7 +972,7 @@ class PermissionsMessagesADMSpec extends CoreSpec() { } "not update hasPermissions set of a permission if invalid permission IRI given" in { - val permissionIri = "invalid-permission-iri" + val permissionIri = "invalid-permission-iri" val hasPermissions = Set(PermissionADM.ProjectAdminAllPermission) val caught = intercept[BadRequestException]( PermissionChangeHasPermissionsRequestADM( @@ -986,7 +986,7 @@ class PermissionsMessagesADMSpec extends CoreSpec() { } "not update hasPermissions set of a permission if invalid empty set given" in { - val permissionIri = SharedPermissionsTestData.perm001_d1.iri + val permissionIri = SharedPermissionsTestData.perm001_d1.iri val hasPermissions = Set.empty[PermissionADM] val caught = intercept[BadRequestException]( PermissionChangeHasPermissionsRequestADM( @@ -1000,7 +1000,7 @@ class PermissionsMessagesADMSpec extends CoreSpec() { } "not update resource class of a doap if invalid permission IRI given" in { - val permissionIri = "invalid-permission-iri" + val permissionIri = "invalid-permission-iri" val resourceClassIri = SharedOntologyTestDataADM.INCUNABULA_BOOK_RESOURCE_CLASS val caught = intercept[BadRequestException]( PermissionChangeResourceClassRequestADM( @@ -1014,7 +1014,7 @@ class PermissionsMessagesADMSpec extends CoreSpec() { } "not update resource class of a doap if invalid resource class IRI is given" in { - val permissionIri = SharedPermissionsTestData.perm001_d1.iri + val permissionIri = SharedPermissionsTestData.perm001_d1.iri val resourceClassIri = "invalid-iri" val caught = intercept[BadRequestException]( PermissionChangeResourceClassRequestADM( @@ -1029,7 +1029,7 @@ class PermissionsMessagesADMSpec extends CoreSpec() { "not update property of a doap if invalid permission IRI given" in { val permissionIri = "invalid-permission-iri" - val propertyIri = SharedOntologyTestDataADM.IMAGES_TITEL_PROPERTY + val propertyIri = SharedOntologyTestDataADM.IMAGES_TITEL_PROPERTY val caught = intercept[BadRequestException]( PermissionChangePropertyRequestADM( permissionIri = permissionIri, @@ -1043,7 +1043,7 @@ class PermissionsMessagesADMSpec extends CoreSpec() { "not update property of a doap if invalid property IRI is given" in { val permissionIri = SharedPermissionsTestData.perm001_d1.iri - val propertyIri = "invalid-iri" + val propertyIri = "invalid-iri" val caught = intercept[BadRequestException]( PermissionChangePropertyRequestADM( permissionIri = permissionIri, diff --git a/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/usersmessages/UsersMessagesADMSpec.scala b/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/usersmessages/UsersMessagesADMSpec.scala index 2556686f39..24d3f0f81d 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/usersmessages/UsersMessagesADMSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/usersmessages/UsersMessagesADMSpec.scala @@ -26,18 +26,18 @@ object UsersMessagesADMSpec { */ class UsersMessagesADMSpec extends CoreSpec(UsersMessagesADMSpec.config) { - private val id = SharedTestDataADM.rootUser.id - private val username = SharedTestDataADM.rootUser.username - private val email = SharedTestDataADM.rootUser.email - private val password = SharedTestDataADM.rootUser.password - private val token = SharedTestDataADM.rootUser.token - private val givenName = SharedTestDataADM.rootUser.givenName - private val familyName = SharedTestDataADM.rootUser.familyName - private val status = SharedTestDataADM.rootUser.status - private val lang = SharedTestDataADM.rootUser.lang - private val groups = SharedTestDataADM.rootUser.groups - private val projects = SharedTestDataADM.rootUser.projects - private val sessionId = SharedTestDataADM.rootUser.sessionId + private val id = SharedTestDataADM.rootUser.id + private val username = SharedTestDataADM.rootUser.username + private val email = SharedTestDataADM.rootUser.email + private val password = SharedTestDataADM.rootUser.password + private val token = SharedTestDataADM.rootUser.token + private val givenName = SharedTestDataADM.rootUser.givenName + private val familyName = SharedTestDataADM.rootUser.familyName + private val status = SharedTestDataADM.rootUser.status + private val lang = SharedTestDataADM.rootUser.lang + private val groups = SharedTestDataADM.rootUser.groups + private val projects = SharedTestDataADM.rootUser.projects + private val sessionId = SharedTestDataADM.rootUser.sessionId private val permissions = SharedTestDataADM.rootUser.permissions private implicit val stringFormatter: StringFormatter = StringFormatter.getInstanceForConstantOntologies @@ -94,7 +94,7 @@ class UsersMessagesADMSpec extends CoreSpec(UsersMessagesADMSpec.config) { "allow checking the SCrypt passwords" in { val encoder = new SCryptPasswordEncoder() - val hp = encoder.encode("123456") + val hp = encoder.encode("123456") val up = UserADM( id = "something", username = "something", @@ -120,7 +120,7 @@ class UsersMessagesADMSpec extends CoreSpec(UsersMessagesADMSpec.config) { "allow checking the BCrypt passwords" in { val encoder = new BCryptPasswordEncoder() - val hp = encoder.encode("123456") + val hp = encoder.encode("123456") val up = UserADM( id = "something", username = "something", @@ -177,7 +177,7 @@ class UsersMessagesADMSpec extends CoreSpec(UsersMessagesADMSpec.config) { "check whether a user identified by email is the same as a user identified by username" in { val userEmail = "user@example.org" - val username = "user" + val username = "user" val user = UserADM( id = "http://rdfh.ch/users/example", @@ -189,7 +189,7 @@ class UsersMessagesADMSpec extends CoreSpec(UsersMessagesADMSpec.config) { lang = "en" ) - val emailID = UserIdentifierADM(maybeEmail = Some(userEmail)) + val emailID = UserIdentifierADM(maybeEmail = Some(userEmail)) val usernameID = UserIdentifierADM(maybeUsername = Some(username)) assert(user.isSelf(emailID)) diff --git a/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/valueObjects/GroupsValueObjectsADMSpec.scala b/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/valueObjects/GroupsValueObjectsADMSpec.scala index 2f3d3a33bd..1d9c3bc24e 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/valueObjects/GroupsValueObjectsADMSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/valueObjects/GroupsValueObjectsADMSpec.scala @@ -17,7 +17,7 @@ import zio.prelude.Validation */ class GroupsValueObjectsADMSpec extends UnitSpec(ValueObjectsADMSpec.config) { "GroupIRI value object" when { - val validGroupIri = "http://rdfh.ch/groups/0803/qBCJAdzZSCqC_2snW5Q7Nw" + val validGroupIri = "http://rdfh.ch/groups/0803/qBCJAdzZSCqC_2snW5Q7Nw" val groupIRIWithUUIDVersion3 = "http://rdfh.ch/groups/0803/rKAU0FNjPUKWqOT8MEW_UQ" "created using empty value" should { @@ -69,7 +69,7 @@ class GroupsValueObjectsADMSpec extends UnitSpec(ValueObjectsADMSpec.config) { } "GroupDescriptions value object" when { - val validDescription = Seq(StringLiteralV2(value = "Valid description", language = Some("en"))) + val validDescription = Seq(StringLiteralV2(value = "Valid description", language = Some("en"))) val invalidDescription = Seq(StringLiteralV2(value = "Invalid description \r", language = Some("en"))) "created using empty value" should { diff --git a/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/valueObjects/ListsValueObjectsADMSpec.scala b/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/valueObjects/ListsValueObjectsADMSpec.scala index 740d5c8ef5..5024f2cc22 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/valueObjects/ListsValueObjectsADMSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/valueObjects/ListsValueObjectsADMSpec.scala @@ -17,7 +17,7 @@ import zio.prelude.Validation */ class ListsValueObjectsADMSpec extends UnitSpec(ValueObjectsADMSpec.config) { "ListIRI value object" when { - val validListIri = "http://rdfh.ch/lists/0803/qBCJAdzZSCqC_2snW5Q7Nw" + val validListIri = "http://rdfh.ch/lists/0803/qBCJAdzZSCqC_2snW5Q7Nw" val listIRIWithUUIDVersion3 = "http://rdfh.ch/lists/0803/6_xROK_UN1S2ZVNSzLlSXQ" "created using empty value" should { @@ -83,7 +83,7 @@ class ListsValueObjectsADMSpec extends UnitSpec(ValueObjectsADMSpec.config) { } "Labels value object" when { - val validLabels = Seq(StringLiteralV2(value = "New Label", language = Some("en"))) + val validLabels = Seq(StringLiteralV2(value = "New Label", language = Some("en"))) val invalidLabels = Seq(StringLiteralV2(value = "\r", language = Some("en"))) "created using empty value" should { @@ -107,7 +107,7 @@ class ListsValueObjectsADMSpec extends UnitSpec(ValueObjectsADMSpec.config) { } "Comments value object" when { - val validComments = Seq(StringLiteralV2(value = "Valid comment", language = Some("en"))) + val validComments = Seq(StringLiteralV2(value = "Valid comment", language = Some("en"))) val invalidComments = Seq(StringLiteralV2(value = "Invalid comment \r", language = Some("en"))) "created using empty value" should { diff --git a/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/valueObjects/ProjectsValueObjectsADMSpec.scala b/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/valueObjects/ProjectsValueObjectsADMSpec.scala index f233eafad5..b7ab53d0c9 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/valueObjects/ProjectsValueObjectsADMSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/valueObjects/ProjectsValueObjectsADMSpec.scala @@ -17,7 +17,7 @@ import zio.prelude.Validation */ class ProjectsValueObjectsADMSpec extends UnitSpec(ValueObjectsADMSpec.config) { "ProjectIRI value object" when { - val validProjectIri = "http://rdfh.ch/projects/0001" + val validProjectIri = "http://rdfh.ch/projects/0001" val projectIRIWithUUIDVersion3 = "http://rdfh.ch/projects/tZjZhGSZMeCLA5VeUmwAmg" "created using empty value" should { @@ -48,7 +48,7 @@ class ProjectsValueObjectsADMSpec extends UnitSpec(ValueObjectsADMSpec.config) { } "Shortcode value object" when { - val validShortcode = "1234" + val validShortcode = "1234" val invalidShortcode = "12345" "created using empty value" should { @@ -77,7 +77,7 @@ class ProjectsValueObjectsADMSpec extends UnitSpec(ValueObjectsADMSpec.config) { } "Shortname value object" when { - val validShortname = "validShortname" + val validShortname = "validShortname" val invalidShortname = "~!@#$%^&*()_+" "created using empty value" should { diff --git a/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/valueObjects/UsersValueObjectsADMSpec.scala b/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/valueObjects/UsersValueObjectsADMSpec.scala index 2cb994a0c5..a6ca4770ee 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/valueObjects/UsersValueObjectsADMSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/admin/responder/valueObjects/UsersValueObjectsADMSpec.scala @@ -16,7 +16,7 @@ import zio.prelude.Validation */ class UsersValueObjectsADMSpec extends UnitSpec(ValueObjectsADMSpec.config) { "UserIRI value object" when { - val validUserIRI = "http://rdfh.ch/users/jDEEitJESRi3pDaDjjQ1WQ" + val validUserIRI = "http://rdfh.ch/users/jDEEitJESRi3pDaDjjQ1WQ" val userIRIWithUUIDVersion3 = "http://rdfh.ch/users/cCmdcpn2MO211YYOplR1hQ" "created using empty value" should { @@ -41,7 +41,7 @@ class UsersValueObjectsADMSpec extends UnitSpec(ValueObjectsADMSpec.config) { } "Username value object" when { - val validUsername = "user008" + val validUsername = "user008" val invalidUsername = "user!@#$%^&*()_+" "created using empty value" should { @@ -107,7 +107,7 @@ class UsersValueObjectsADMSpec extends UnitSpec(ValueObjectsADMSpec.config) { } "Email value object" when { - val validEmailAddress = "address@ch" + val validEmailAddress = "address@ch" val invalidEmailAddress = "invalid_email_address" "created using empty value" should { diff --git a/webapi/src/test/scala/org/knora/webapi/messages/store/triplestoremessages/TriplestoreMessagesSpec.scala b/webapi/src/test/scala/org/knora/webapi/messages/store/triplestoremessages/TriplestoreMessagesSpec.scala index 10793c4605..c3ee581a9c 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/store/triplestoremessages/TriplestoreMessagesSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/store/triplestoremessages/TriplestoreMessagesSpec.scala @@ -21,7 +21,7 @@ class TriplestoreMessagesSpec extends AnyWordSpecLike with Matchers with ListADM "work for a 'StringLiteralV2' without language tag" in { val string = StringLiteralV2("stringwithoutlang", None) - val json = string.toJson.compactPrint + val json = string.toJson.compactPrint json should be("{\"value\":\"stringwithoutlang\"}") @@ -33,7 +33,7 @@ class TriplestoreMessagesSpec extends AnyWordSpecLike with Matchers with ListADM "work for a 'StringLiteralV2' with language tag" in { val string = StringLiteralV2("stringwithlang", Some("de")) - val json = string.toJson.compactPrint + val json = string.toJson.compactPrint json should be("{\"value\":\"stringwithlang\",\"language\":\"de\"}") diff --git a/webapi/src/test/scala/org/knora/webapi/messages/util/ConstructResponseUtilV2Spec.scala b/webapi/src/test/scala/org/knora/webapi/messages/util/ConstructResponseUtilV2Spec.scala index 60bbaec38f..23ea860fd5 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/util/ConstructResponseUtilV2Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/util/ConstructResponseUtilV2Spec.scala @@ -26,19 +26,20 @@ import scala.concurrent.{Await, Future} */ class ConstructResponseUtilV2Spec extends CoreSpec() with ImplicitSender { private implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - private implicit val timeout: Timeout = 10.seconds - private val incunabulaUser = SharedTestDataADM.incunabulaProjectAdminUser - private val anythingAdminUser = SharedTestDataADM.anythingAdminUser - private val anonymousUser = SharedTestDataADM.anonymousUser - private val resourcesResponderV2SpecFullData = new ResourcesResponderV2SpecFullData - private val constructResponseUtilV2SpecFullData = new ConstructResponseUtilV2SpecFullData - private val rdfFormatUtil = RdfFeatureFactory.getRdfFormatUtil(defaultFeatureFactoryConfig) + private implicit val timeout: Timeout = 10.seconds + private val incunabulaUser = SharedTestDataADM.incunabulaProjectAdminUser + private val anythingAdminUser = SharedTestDataADM.anythingAdminUser + private val anonymousUser = SharedTestDataADM.anonymousUser + private val resourcesResponderV2SpecFullData = new ResourcesResponderV2SpecFullData + private val constructResponseUtilV2SpecFullData = new ConstructResponseUtilV2SpecFullData + private val rdfFormatUtil = RdfFeatureFactory.getRdfFormatUtil(defaultFeatureFactoryConfig) "ConstructResponseUtilV2" should { "convert a resource Turtle response into a resource" in { val resourceIri: IRI = "http://rdfh.ch/0803/c5058f3a" - val turtleStr: String = FileUtil.readTextFile(Paths.get("..", "test_data/constructResponseUtilV2/Zeitglocklein.ttl")) + val turtleStr: String = + FileUtil.readTextFile(Paths.get("..", "test_data/constructResponseUtilV2/Zeitglocklein.ttl")) val resourceRequestResponse: SparqlExtendedConstructResponse = SparqlExtendedConstructResponse.parseTurtleResponse(turtleStr, rdfFormatUtil, log).get val mainResourcesAndValueRdfData: ConstructResponseUtilV2.MainResourcesAndValueRdfData = @@ -283,7 +284,7 @@ class ConstructResponseUtilV2Spec extends CoreSpec() with ImplicitSender { */ val resourceIris: Seq[IRI] = Seq("http://rdfh.ch/0803/76570a749901", "http://rdfh.ch/0803/773f258402") - val turtleStr: String = FileUtil.readTextFile(Paths.get("..", "test_data/constructResponseUtilV2/mainQuery1.ttl")) + val turtleStr: String = FileUtil.readTextFile(Paths.get("..", "test_data/constructResponseUtilV2/mainQuery1.ttl")) val resourceRequestResponse: SparqlExtendedConstructResponse = SparqlExtendedConstructResponse.parseTurtleResponse(turtleStr, rdfFormatUtil, log).get val mainResourcesAndValueRdfData: ConstructResponseUtilV2.MainResourcesAndValueRdfData = @@ -350,7 +351,7 @@ class ConstructResponseUtilV2Spec extends CoreSpec() with ImplicitSender { */ val resourceIris: Seq[IRI] = Seq("http://rdfh.ch/0803/c5058f3a", "http://rdfh.ch/0803/ff17e5ef9601") - val turtleStr: String = FileUtil.readTextFile(Paths.get("..", "test_data/constructResponseUtilV2/mainQuery2.ttl")) + val turtleStr: String = FileUtil.readTextFile(Paths.get("..", "test_data/constructResponseUtilV2/mainQuery2.ttl")) val resourceRequestResponse: SparqlExtendedConstructResponse = SparqlExtendedConstructResponse.parseTurtleResponse(turtleStr, rdfFormatUtil, log).get val mainResourcesAndValueRdfData: ConstructResponseUtilV2.MainResourcesAndValueRdfData = diff --git a/webapi/src/test/scala/org/knora/webapi/messages/util/PermissionUtilADMSpec.scala b/webapi/src/test/scala/org/knora/webapi/messages/util/PermissionUtilADMSpec.scala index 6fffaa3f42..926d8a3741 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/util/PermissionUtilADMSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/util/PermissionUtilADMSpec.scala @@ -31,9 +31,9 @@ class PermissionUtilADMSpec extends CoreSpec("PermissionUtilSpec") with Implicit val parsedPermissionLiteral: Map[EntityPermission, Set[IRI]] = Map( RestrictedViewPermission -> Set(OntologyConstants.KnoraAdmin.UnknownUser), - ViewPermission -> Set(OntologyConstants.KnoraAdmin.KnownUser), - ModifyPermission -> Set(OntologyConstants.KnoraAdmin.ProjectMember), - ChangeRightsPermission -> Set(OntologyConstants.KnoraAdmin.Creator) + ViewPermission -> Set(OntologyConstants.KnoraAdmin.KnownUser), + ModifyPermission -> Set(OntologyConstants.KnoraAdmin.ProjectMember), + ChangeRightsPermission -> Set(OntologyConstants.KnoraAdmin.Creator) ) "PermissionUtil" should { @@ -269,7 +269,7 @@ class PermissionUtilADMSpec extends CoreSpec("PermissionUtilSpec") with Implicit ) val permissionsString = "CR 1,knora-admin:Creator|D 2|M knora-admin:ProjectMember|V knora-admin:KnownUser" - val result = PermissionUtilADM.formatPermissionADMs(permissions, PermissionType.OAP) + val result = PermissionUtilADM.formatPermissionADMs(permissions, PermissionType.OAP) result should equal(permissionsString) diff --git a/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/JsonLDUtilSpec.scala b/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/JsonLDUtilSpec.scala index 0962e74a59..de0871b7cb 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/JsonLDUtilSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/JsonLDUtilSpec.scala @@ -22,7 +22,7 @@ abstract class JsonLDUtilSpec(featureToggle: FeatureToggle) extends CoreSpec { parent = new KnoraSettingsFeatureFactoryConfig(settings) ) - private val rdfFormatUtil: RdfFormatUtil = RdfFeatureFactory.getRdfFormatUtil(featureFactoryConfig) + private val rdfFormatUtil: RdfFormatUtil = RdfFeatureFactory.getRdfFormatUtil(featureFactoryConfig) private val rdfModelFactory: RdfModelFactory = RdfFeatureFactory.getRdfModelFactory(featureFactoryConfig) "The JSON-LD tool" should { @@ -104,9 +104,9 @@ abstract class JsonLDUtilSpec(featureToggle: FeatureToggle) extends CoreSpec { """.stripMargin val compactedJsonLDDoc: JsonLDDocument = JsonLDUtil.parseJsonLD(ontologyJsonLDInputStr) - val formattedCompactedDoc = compactedJsonLDDoc.toPrettyString() - val receivedOutputAsJsValue: JsValue = JsonParser(formattedCompactedDoc) - val expectedOutputAsJsValue: JsValue = JsonParser(ontologyCompactedJsonLDOutputStr) + val formattedCompactedDoc = compactedJsonLDDoc.toPrettyString() + val receivedOutputAsJsValue: JsValue = JsonParser(formattedCompactedDoc) + val expectedOutputAsJsValue: JsValue = JsonParser(ontologyCompactedJsonLDOutputStr) receivedOutputAsJsValue should ===(expectedOutputAsJsValue) } @@ -134,7 +134,8 @@ abstract class JsonLDUtilSpec(featureToggle: FeatureToggle) extends CoreSpec { "convert an RDF4J Model representing an ontology to JSON-LD" in { // Read a Turtle file. - val turtle = FileUtil.readTextFile(Paths.get("..", "test_data/ontologyR2RV2/anythingOntologyWithValueObjects.ttl")) + val turtle = + FileUtil.readTextFile(Paths.get("..", "test_data/ontologyR2RV2/anythingOntologyWithValueObjects.ttl")) // Parse it to an RDF4J Model. val inputModel: RdfModel = rdfFormatUtil.parseToRdfModel(rdfStr = turtle, rdfFormat = Turtle) @@ -177,7 +178,8 @@ abstract class JsonLDUtilSpec(featureToggle: FeatureToggle) extends CoreSpec { outputModelAsJsonLDDocument should ===(jsonLDDocument) // Read an isomorphic Turtle file. - val expectedTurtle = FileUtil.readTextFile(Paths.get("..", "test_data/resourcesR2RV2/BookReiseInsHeiligeLand.ttl")) + val expectedTurtle = + FileUtil.readTextFile(Paths.get("..", "test_data/resourcesR2RV2/BookReiseInsHeiligeLand.ttl")) // Parse it to an RDF4J Model. val expectedModel: RdfModel = rdfFormatUtil.parseToRdfModel(rdfStr = expectedTurtle, rdfFormat = Turtle) @@ -203,7 +205,8 @@ abstract class JsonLDUtilSpec(featureToggle: FeatureToggle) extends CoreSpec { jsonLDOutputModel should ===(inputModel) // Read an isomorphic JSON-LD file. - val expectedJsonLD = FileUtil.readTextFile(Paths.get("..", "test_data/resourcesR2RV2/BookReiseInsHeiligeLand.jsonld")) + val expectedJsonLD = + FileUtil.readTextFile(Paths.get("..", "test_data/resourcesR2RV2/BookReiseInsHeiligeLand.jsonld")) // Parse it to a JsonLDDocument and compare it with the generated one. val expectedJsonLDDocument: JsonLDDocument = JsonLDUtil.parseJsonLD(expectedJsonLD) @@ -241,13 +244,13 @@ abstract class JsonLDUtilSpec(featureToggle: FeatureToggle) extends CoreSpec { val expectedWithFoo1AtTopLevel = JsonLDObject( value = Map( - "@id" -> JsonLDString(value = "http://rdfh.ch/foo1"), - "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), + "@id" -> JsonLDString(value = "http://rdfh.ch/foo1"), + "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "foo 1"), "http://example.org/foo#hasOtherFoo" -> JsonLDObject(value = Map( - "@id" -> JsonLDString(value = "http://rdfh.ch/foo2"), - "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), + "@id" -> JsonLDString(value = "http://rdfh.ch/foo2"), + "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "foo 2"), "http://example.org/foo#hasOtherFoo" -> JsonLDObject( value = Map("@id" -> JsonLDString(value = "http://rdfh.ch/foo1")) @@ -259,13 +262,13 @@ abstract class JsonLDUtilSpec(featureToggle: FeatureToggle) extends CoreSpec { val expectedWithFoo2AtTopLevel = JsonLDObject( value = Map( - "@id" -> JsonLDString(value = "http://rdfh.ch/foo2"), - "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), + "@id" -> JsonLDString(value = "http://rdfh.ch/foo2"), + "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "foo 2"), "http://example.org/foo#hasOtherFoo" -> JsonLDObject(value = Map( - "@id" -> JsonLDString(value = "http://rdfh.ch/foo1"), - "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), + "@id" -> JsonLDString(value = "http://rdfh.ch/foo1"), + "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "foo 1"), "http://example.org/foo#hasOtherFoo" -> JsonLDObject( value = Map("@id" -> JsonLDString(value = "http://rdfh.ch/foo2")) @@ -313,24 +316,24 @@ abstract class JsonLDUtilSpec(featureToggle: FeatureToggle) extends CoreSpec { val expectedHierarchicalJsonLD = JsonLDObject( value = Map( - "@id" -> JsonLDString(value = "http://rdfh.ch/foo1"), + "@id" -> JsonLDString(value = "http://rdfh.ch/foo1"), "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), "http://example.org/foo#hasBar" -> JsonLDObject( value = Map( - "@type" -> JsonLDString(value = "http://example.org/foo#Bar"), + "@type" -> JsonLDString(value = "http://example.org/foo#Bar"), "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "bar 1") ) ), "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "foo 1"), "http://example.org/foo#hasOtherFoo" -> JsonLDObject(value = Map( - "@id" -> JsonLDString(value = "http://rdfh.ch/foo2"), - "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), + "@id" -> JsonLDString(value = "http://rdfh.ch/foo2"), + "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "foo 2"), - "http://example.org/foo#hasIndex" -> JsonLDInt(value = 3), + "http://example.org/foo#hasIndex" -> JsonLDInt(value = 3), "http://example.org/foo#hasBar" -> JsonLDObject(value = Map( - "@type" -> JsonLDString(value = "http://example.org/foo#Bar"), + "@type" -> JsonLDString(value = "http://example.org/foo#Bar"), "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "bar 2") ) ) @@ -350,12 +353,12 @@ abstract class JsonLDUtilSpec(featureToggle: FeatureToggle) extends CoreSpec { Vector( JsonLDObject(value = Map( - "@id" -> JsonLDString(value = "http://rdfh.ch/foo1"), - "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), + "@id" -> JsonLDString(value = "http://rdfh.ch/foo1"), + "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "foo 1"), "http://example.org/foo#hasBar" -> JsonLDObject(value = Map( - "@type" -> JsonLDString(value = "http://example.org/foo#Bar"), + "@type" -> JsonLDString(value = "http://example.org/foo#Bar"), "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "bar 1") ) ), @@ -366,14 +369,14 @@ abstract class JsonLDUtilSpec(featureToggle: FeatureToggle) extends CoreSpec { ), JsonLDObject(value = Map( - "@id" -> JsonLDString(value = "http://rdfh.ch/foo2"), - "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), + "@id" -> JsonLDString(value = "http://rdfh.ch/foo2"), + "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "foo 2"), - "http://example.org/foo#hasIndex" -> JsonLDInt(value = 3), + "http://example.org/foo#hasIndex" -> JsonLDInt(value = 3), "http://example.org/foo#hasBar" -> JsonLDObject(value = Map( "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "bar 2"), - "@type" -> JsonLDString(value = "http://example.org/foo#Bar") + "@type" -> JsonLDString(value = "http://example.org/foo#Bar") ) ) ) diff --git a/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/KnoraResponseV2Spec.scala b/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/KnoraResponseV2Spec.scala index 0665d29282..27b9761d52 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/KnoraResponseV2Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/KnoraResponseV2Spec.scala @@ -43,24 +43,24 @@ abstract class KnoraResponseV2Spec(featureToggle: FeatureToggle) extends CoreSpe private val hierarchicalJsonLD = JsonLDDocument( JsonLDObject( value = Map( - "@id" -> JsonLDString(value = "http://rdfh.ch/foo1"), + "@id" -> JsonLDString(value = "http://rdfh.ch/foo1"), "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), "http://example.org/foo#hasBar" -> JsonLDObject( value = Map( - "@type" -> JsonLDString(value = "http://example.org/foo#Bar"), + "@type" -> JsonLDString(value = "http://example.org/foo#Bar"), "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "bar 1") ) ), "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "foo 1"), "http://example.org/foo#hasOtherFoo" -> JsonLDObject(value = Map( - "@id" -> JsonLDString(value = "http://rdfh.ch/foo2"), - "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), + "@id" -> JsonLDString(value = "http://rdfh.ch/foo2"), + "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "foo 2"), - "http://example.org/foo#hasIndex" -> JsonLDInt(value = 3), + "http://example.org/foo#hasIndex" -> JsonLDInt(value = 3), "http://example.org/foo#hasBar" -> JsonLDObject(value = Map( - "@type" -> JsonLDString(value = "http://example.org/foo#Bar"), + "@type" -> JsonLDString(value = "http://example.org/foo#Bar"), "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "bar 2") ) ) @@ -77,12 +77,12 @@ abstract class KnoraResponseV2Spec(featureToggle: FeatureToggle) extends CoreSpe Vector( JsonLDObject(value = Map( - "@id" -> JsonLDString(value = "http://rdfh.ch/foo1"), - "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), + "@id" -> JsonLDString(value = "http://rdfh.ch/foo1"), + "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "foo 1"), "http://example.org/foo#hasBar" -> JsonLDObject(value = Map( - "@type" -> JsonLDString(value = "http://example.org/foo#Bar"), + "@type" -> JsonLDString(value = "http://example.org/foo#Bar"), "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "bar 1") ) ), @@ -93,14 +93,14 @@ abstract class KnoraResponseV2Spec(featureToggle: FeatureToggle) extends CoreSpe ), JsonLDObject(value = Map( - "@id" -> JsonLDString(value = "http://rdfh.ch/foo2"), - "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), + "@id" -> JsonLDString(value = "http://rdfh.ch/foo2"), + "@type" -> JsonLDString(value = "http://example.org/foo#Foo"), "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "foo 2"), - "http://example.org/foo#hasIndex" -> JsonLDInt(value = 3), + "http://example.org/foo#hasIndex" -> JsonLDInt(value = 3), "http://example.org/foo#hasBar" -> JsonLDObject(value = Map( "http://www.w3.org/2000/01/rdf-schema#label" -> JsonLDString(value = "bar 2"), - "@type" -> JsonLDString(value = "http://example.org/foo#Bar") + "@type" -> JsonLDString(value = "http://example.org/foo#Bar") ) ) ) @@ -131,7 +131,8 @@ abstract class KnoraResponseV2Spec(featureToggle: FeatureToggle) extends CoreSpe "KnoraResponseV2" should { "convert Turtle to JSON-LD" in { // Read a Turtle file representing a resource. TODO: Use sample project metadata for this test. - val turtle: String = FileUtil.readTextFile(Paths.get("..", "test_data/resourcesR2RV2/BookReiseInsHeiligeLand.ttl")) + val turtle: String = + FileUtil.readTextFile(Paths.get("..", "test_data/resourcesR2RV2/BookReiseInsHeiligeLand.ttl")) // Wrap it in a KnoraTurtleResponseV2. val turtleTestResponse = TurtleTestResponse(turtle) @@ -159,7 +160,8 @@ abstract class KnoraResponseV2Spec(featureToggle: FeatureToggle) extends CoreSpe "convert JSON-LD to Turtle" in { // Read a JSON-LD file representing a resource. - val jsonLD: String = FileUtil.readTextFile(Paths.get("..", "test_data/resourcesR2RV2/BookReiseInsHeiligeLand.jsonld")) + val jsonLD: String = + FileUtil.readTextFile(Paths.get("..", "test_data/resourcesR2RV2/BookReiseInsHeiligeLand.jsonld")) // Wrap it in a KnoraJsonLDResponseV2. val jsonLDTestResponse = JsonLDTestResponse(JsonLDUtil.parseJsonLD(jsonLD)) diff --git a/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/RdfFormatUtilSpec.scala b/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/RdfFormatUtilSpec.scala index 5e69f588bc..bc2e968868 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/RdfFormatUtilSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/RdfFormatUtilSpec.scala @@ -23,8 +23,8 @@ abstract class RdfFormatUtilSpec(featureToggle: FeatureToggle) extends CoreSpec parent = new KnoraSettingsFeatureFactoryConfig(settings) ) - private val rdfFormatUtil: RdfFormatUtil = RdfFeatureFactory.getRdfFormatUtil(featureFactoryConfig) - private val rdfNodeFactory: RdfNodeFactory = RdfFeatureFactory.getRdfNodeFactory(featureFactoryConfig) + private val rdfFormatUtil: RdfFormatUtil = RdfFeatureFactory.getRdfFormatUtil(featureFactoryConfig) + private val rdfNodeFactory: RdfNodeFactory = RdfFeatureFactory.getRdfNodeFactory(featureFactoryConfig) private val rdfModelFactory: RdfModelFactory = RdfFeatureFactory.getRdfModelFactory(featureFactoryConfig) private val expectedThingLabelStatement = rdfNodeFactory.makeStatement( @@ -37,9 +37,9 @@ abstract class RdfFormatUtilSpec(featureToggle: FeatureToggle) extends CoreSpec * Processes `anything-onto.ttl` and checks whether the expected content is received. */ class TestStreamProcessor extends RdfStreamProcessor { - var startCalled: Boolean = false - var finishCalled: Boolean = false - var gotKnoraBaseNamespace = false + var startCalled: Boolean = false + var finishCalled: Boolean = false + var gotKnoraBaseNamespace = false var gotThingLabelStatement: Boolean = false override def start(): Unit = @@ -85,11 +85,12 @@ abstract class RdfFormatUtilSpec(featureToggle: FeatureToggle) extends CoreSpec "RdfFormatUtil" should { "parse RDF in Turtle format, producing an RdfModel, then format it as Turtle again" in { - val inputTurtle: String = FileUtil.readTextFile(Paths.get("..", "test_data/resourcesR2RV2/BookReiseInsHeiligeLand.ttl")) + val inputTurtle: String = + FileUtil.readTextFile(Paths.get("..", "test_data/resourcesR2RV2/BookReiseInsHeiligeLand.ttl")) val inputModel: RdfModel = rdfFormatUtil.parseToRdfModel(rdfStr = inputTurtle, rdfFormat = Turtle) checkModelForRdfTypeBook(inputModel) - val outputTurtle: String = rdfFormatUtil.format(rdfModel = inputModel, rdfFormat = Turtle) + val outputTurtle: String = rdfFormatUtil.format(rdfModel = inputModel, rdfFormat = Turtle) val outputModel: RdfModel = rdfFormatUtil.parseToRdfModel(rdfStr = outputTurtle, rdfFormat = Turtle) checkModelForRdfTypeBook(outputModel) assert(outputModel == inputModel) @@ -101,14 +102,15 @@ abstract class RdfFormatUtilSpec(featureToggle: FeatureToggle) extends CoreSpec val inputModel: RdfModel = rdfFormatUtil.parseToRdfModel(rdfStr = inputTurtle, rdfFormat = JsonLD) checkModelForRdfTypeBook(inputModel) - val outputTurtle: String = rdfFormatUtil.format(rdfModel = inputModel, rdfFormat = JsonLD) + val outputTurtle: String = rdfFormatUtil.format(rdfModel = inputModel, rdfFormat = JsonLD) val outputModel: RdfModel = rdfFormatUtil.parseToRdfModel(rdfStr = outputTurtle, rdfFormat = JsonLD) checkModelForRdfTypeBook(outputModel) assert(outputModel == inputModel) } "parse RDF in Turtle format, producing a JsonLDDocument, then format it as Turtle again" in { - val inputTurtle: String = FileUtil.readTextFile(Paths.get("..", "test_data/resourcesR2RV2/BookReiseInsHeiligeLand.ttl")) + val inputTurtle: String = + FileUtil.readTextFile(Paths.get("..", "test_data/resourcesR2RV2/BookReiseInsHeiligeLand.ttl")) val inputModel: RdfModel = rdfFormatUtil.parseToRdfModel(rdfStr = inputTurtle, rdfFormat = Turtle) val inputJsonLDDocument: JsonLDDocument = rdfFormatUtil.parseToJsonLDDocument(rdfStr = inputTurtle, rdfFormat = Turtle) @@ -118,14 +120,15 @@ abstract class RdfFormatUtilSpec(featureToggle: FeatureToggle) extends CoreSpec checkModelForRdfTypeBook(jsonLDOutputModel) assert(jsonLDOutputModel == inputModel) - val outputTurtle: String = rdfFormatUtil.format(rdfModel = jsonLDOutputModel, rdfFormat = Turtle) + val outputTurtle: String = rdfFormatUtil.format(rdfModel = jsonLDOutputModel, rdfFormat = Turtle) val turtleOutputModel: RdfModel = rdfFormatUtil.parseToRdfModel(rdfStr = outputTurtle, rdfFormat = Turtle) checkModelForRdfTypeBook(turtleOutputModel) assert(turtleOutputModel == inputModel) } "parse RDF in RDF/XML format, producing a JsonLDDocument, then format it as RDF/XML again" in { - val inputRdfXml: String = FileUtil.readTextFile(Paths.get("..", "test_data/resourcesR2RV2/BookReiseInsHeiligeLand.rdf")) + val inputRdfXml: String = + FileUtil.readTextFile(Paths.get("..", "test_data/resourcesR2RV2/BookReiseInsHeiligeLand.rdf")) val inputModel: RdfModel = rdfFormatUtil.parseToRdfModel(rdfStr = inputRdfXml, rdfFormat = RdfXml) val inputJsonLDDocument: JsonLDDocument = rdfFormatUtil.parseToJsonLDDocument(rdfStr = inputRdfXml, rdfFormat = RdfXml) @@ -135,22 +138,22 @@ abstract class RdfFormatUtilSpec(featureToggle: FeatureToggle) extends CoreSpec checkModelForRdfTypeBook(jsonLDOutputModel) assert(jsonLDOutputModel == inputModel) - val outputRdfXml: String = rdfFormatUtil.format(rdfModel = jsonLDOutputModel, rdfFormat = RdfXml) + val outputRdfXml: String = rdfFormatUtil.format(rdfModel = jsonLDOutputModel, rdfFormat = RdfXml) val rdfXmlOutputModel: RdfModel = rdfFormatUtil.parseToRdfModel(rdfStr = outputRdfXml, rdfFormat = RdfXml) checkModelForRdfTypeBook(rdfXmlOutputModel) assert(rdfXmlOutputModel == inputModel) } "parse RDF in TriG format" in { - val graphIri = "http://example.org/data#" - val inputTrig = FileUtil.readTextFile(Paths.get("..", "test_data/rdfFormatUtil/BookReiseInsHeiligeLand.trig")) + val graphIri = "http://example.org/data#" + val inputTrig = FileUtil.readTextFile(Paths.get("..", "test_data/rdfFormatUtil/BookReiseInsHeiligeLand.trig")) val inputModel: RdfModel = rdfFormatUtil.parseToRdfModel(rdfStr = inputTrig, rdfFormat = TriG) checkModelForRdfTypeBook(rdfModel = inputModel, context = Some(graphIri)) } "parse RDF in N-Quads format" in { - val graphIri = "http://example.org/data#" - val inputTrig = FileUtil.readTextFile(Paths.get("..", "test_data/rdfFormatUtil/BookReiseInsHeiligeLand.nq")) + val graphIri = "http://example.org/data#" + val inputTrig = FileUtil.readTextFile(Paths.get("..", "test_data/rdfFormatUtil/BookReiseInsHeiligeLand.nq")) val inputModel: RdfModel = rdfFormatUtil.parseToRdfModel(rdfStr = inputTrig, rdfFormat = NQuads) checkModelForRdfTypeBook(rdfModel = inputModel, context = Some(graphIri)) } @@ -158,7 +161,9 @@ abstract class RdfFormatUtilSpec(featureToggle: FeatureToggle) extends CoreSpec "read Turtle, add a graph IRI to it, write it to a TriG file, and read back the TriG file" in { val graphIri = "http://example.org/data#" val rdfSource = RdfInputStreamSource( - new BufferedInputStream(Files.newInputStream(Paths.get("..", "test_data/resourcesR2RV2/BookReiseInsHeiligeLand.ttl"))) + new BufferedInputStream( + Files.newInputStream(Paths.get("..", "test_data/resourcesR2RV2/BookReiseInsHeiligeLand.ttl")) + ) ) val outputFile: Path = Files.createTempFile("test", ".trig") @@ -176,7 +181,9 @@ abstract class RdfFormatUtilSpec(featureToggle: FeatureToggle) extends CoreSpec "read Turtle, add a graph IRI to it, write it to an N-Quads file, and read back the N-Quads file" in { val graphIri = "http://example.org/data#" val rdfSource = RdfInputStreamSource( - new BufferedInputStream(Files.newInputStream(Paths.get("..", "test_data/resourcesR2RV2/BookReiseInsHeiligeLand.ttl"))) + new BufferedInputStream( + Files.newInputStream(Paths.get("..", "test_data/resourcesR2RV2/BookReiseInsHeiligeLand.ttl")) + ) ) val outputFile: Path = Files.createTempFile("test", ".trig") @@ -209,16 +216,16 @@ abstract class RdfFormatUtilSpec(featureToggle: FeatureToggle) extends CoreSpec val inputJsonLD: String = FileUtil.readTextFile(Paths.get("..", "test_data/resourcesR2RV2/BookReiseInsHeiligeLandSimple.jsonld")) val inputJsonLDDocument: JsonLDDocument = JsonLDUtil.parseJsonLD(inputJsonLD) - val outputModel: RdfModel = inputJsonLDDocument.toRdfModel(rdfModelFactory) + val outputModel: RdfModel = inputJsonLDDocument.toRdfModel(rdfModelFactory) // Add namespaces, which were removed by compacting the JSON-LD document when parsing it. val namespaces: Map[String, IRI] = Map( "incunabula" -> "http://0.0.0.0:3333/ontology/0803/incunabula/simple/v2#", - "knora-api" -> "http://api.knora.org/ontology/knora-api/simple/v2#", - "rdf" -> "http://www.w3.org/1999/02/22-rdf-syntax-ns#", - "rdfs" -> "http://www.w3.org/2000/01/rdf-schema#", - "xsd" -> "http://www.w3.org/2001/XMLSchema#" + "knora-api" -> "http://api.knora.org/ontology/knora-api/simple/v2#", + "rdf" -> "http://www.w3.org/1999/02/22-rdf-syntax-ns#", + "rdfs" -> "http://www.w3.org/2000/01/rdf-schema#", + "xsd" -> "http://www.w3.org/2001/XMLSchema#" ) for ((prefix, namespace) <- namespaces) { @@ -267,7 +274,7 @@ abstract class RdfFormatUtilSpec(featureToggle: FeatureToggle) extends CoreSpec // Read back the ByteArrayOutputStream and check that it's correct. val byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray) - val testStreamProcessor = new TestStreamProcessor + val testStreamProcessor = new TestStreamProcessor rdfFormatUtil.parseWithStreamProcessor( rdfSource = RdfInputStreamSource(byteArrayInputStream), diff --git a/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/RdfModelSpec.scala b/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/RdfModelSpec.scala index 6b6e9575d9..85ed71f9d0 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/RdfModelSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/RdfModelSpec.scala @@ -25,8 +25,8 @@ abstract class RdfModelSpec(featureToggle: FeatureToggle) extends CoreSpec { parent = new KnoraSettingsFeatureFactoryConfig(settings) ) - private val model: RdfModel = RdfFeatureFactory.getRdfModelFactory(featureFactoryConfig).makeEmptyModel - private val nodeFactory: RdfNodeFactory = RdfFeatureFactory.getRdfNodeFactory(featureFactoryConfig) + private val model: RdfModel = RdfFeatureFactory.getRdfModelFactory(featureFactoryConfig).makeEmptyModel + private val nodeFactory: RdfNodeFactory = RdfFeatureFactory.getRdfNodeFactory(featureFactoryConfig) private val rdfFormatUtil: RdfFormatUtil = RdfFeatureFactory.getRdfFormatUtil(featureFactoryConfig) /** @@ -50,8 +50,8 @@ abstract class RdfModelSpec(featureToggle: FeatureToggle) extends CoreSpec { "An RdfModel" should { "add a triple with a datatype literal object, without first creating a Statement" in { - val subj: IriNode = nodeFactory.makeIriNode("http://example.org/1") - val pred: IriNode = nodeFactory.makeIriNode("http://example.org/int_prop") + val subj: IriNode = nodeFactory.makeIriNode("http://example.org/1") + val pred: IriNode = nodeFactory.makeIriNode("http://example.org/int_prop") val obj: DatatypeLiteral = nodeFactory.makeDatatypeLiteral(value = "5", datatype = OntologyConstants.Xsd.Integer) model.add(subj = subj, pred = pred, obj = obj) @@ -157,9 +157,9 @@ abstract class RdfModelSpec(featureToggle: FeatureToggle) extends CoreSpec { } "add, find, and remove quads" in { - val labelPred: IriNode = nodeFactory.makeIriNode(OntologyConstants.Rdfs.Label) + val labelPred: IriNode = nodeFactory.makeIriNode(OntologyConstants.Rdfs.Label) val commentPred: IriNode = nodeFactory.makeIriNode(OntologyConstants.Rdfs.Comment) - val context1 = "http://example.org/graph1" + val context1 = "http://example.org/graph1" val graph1LabelStatement = nodeFactory.makeStatement( subj = nodeFactory.makeIriNode("http://example.org/6"), @@ -232,8 +232,8 @@ abstract class RdfModelSpec(featureToggle: FeatureToggle) extends CoreSpec { } "Remove a statement from the default graph, rather than an otherwise identical statement in a named graph" in { - val subj: IriNode = nodeFactory.makeIriNode("http://example.org/foo") - val pred: IriNode = nodeFactory.makeIriNode(OntologyConstants.Rdfs.Label) + val subj: IriNode = nodeFactory.makeIriNode("http://example.org/foo") + val pred: IriNode = nodeFactory.makeIriNode(OntologyConstants.Rdfs.Label) val obj: DatatypeLiteral = nodeFactory.makeDatatypeLiteral(value = "Foo", datatype = OntologyConstants.Xsd.String) val statementInDefaultGraph: Statement = nodeFactory.makeStatement( @@ -265,8 +265,8 @@ abstract class RdfModelSpec(featureToggle: FeatureToggle) extends CoreSpec { } "Remove a statement from the default graph, and an otherwise identical statement in a named graph" in { - val subj: IriNode = nodeFactory.makeIriNode("http://example.org/bar") - val pred: IriNode = nodeFactory.makeIriNode(OntologyConstants.Rdfs.Label) + val subj: IriNode = nodeFactory.makeIriNode("http://example.org/bar") + val pred: IriNode = nodeFactory.makeIriNode(OntologyConstants.Rdfs.Label) val obj: DatatypeLiteral = nodeFactory.makeDatatypeLiteral(value = "Bar", datatype = OntologyConstants.Xsd.String) val statementInDefaultGraph: Statement = nodeFactory.makeStatement( @@ -326,13 +326,13 @@ abstract class RdfModelSpec(featureToggle: FeatureToggle) extends CoreSpec { val expectedResults = Seq( Map( - "resource" -> "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw", - "value" -> "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/bXMwnrHvQH2DMjOFrGmNzg", + "resource" -> "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw", + "value" -> "http://rdfh.ch/0001/H6gBWUuJSuuO-CilHV8kQw/values/bXMwnrHvQH2DMjOFrGmNzg", "decimalValue" -> "1.5" ), Map( - "resource" -> "http://rdfh.ch/0001/uqmMo72OQ2K2xe7mkIytlg", - "value" -> "http://rdfh.ch/0001/uqmMo72OQ2K2xe7mkIytlg/values/85et-o-STOmn2JcVqrGTCQ", + "resource" -> "http://rdfh.ch/0001/uqmMo72OQ2K2xe7mkIytlg", + "value" -> "http://rdfh.ch/0001/uqmMo72OQ2K2xe7mkIytlg/values/85et-o-STOmn2JcVqrGTCQ", "decimalValue" -> "2.1" ) ) diff --git a/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/ShaclValidatorSpec.scala b/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/ShaclValidatorSpec.scala index f922e3a985..d51af0e7e5 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/ShaclValidatorSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/util/rdf/ShaclValidatorSpec.scala @@ -38,12 +38,12 @@ abstract class ShaclValidatorSpec(featureToggle: FeatureToggle) parent = new KnoraSettingsFeatureFactoryConfig(settings) ) - private val rdfFormatUtil: RdfFormatUtil = RdfFeatureFactory.getRdfFormatUtil(featureFactoryConfig) - private val nodeFactory: RdfNodeFactory = RdfFeatureFactory.getRdfNodeFactory(featureFactoryConfig) + private val rdfFormatUtil: RdfFormatUtil = RdfFeatureFactory.getRdfFormatUtil(featureFactoryConfig) + private val nodeFactory: RdfNodeFactory = RdfFeatureFactory.getRdfNodeFactory(featureFactoryConfig) private val shaclValidator: ShaclValidator = RdfFeatureFactory.getShaclValidator(featureFactoryConfig) private val conformsIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.Shacl.Conforms) - private val resultIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.Shacl.Result) + private val resultIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.Shacl.Result) private val sourceConstraintComponentIri: IriNode = nodeFactory.makeIriNode(OntologyConstants.Shacl.SourceConstraintComponent) private val datatypeConstraintComponentIri: IriNode = diff --git a/webapi/src/test/scala/org/knora/webapi/messages/util/search/gravsearch/types/GravsearchTypeInspectorSpec.scala b/webapi/src/test/scala/org/knora/webapi/messages/util/search/gravsearch/types/GravsearchTypeInspectorSpec.scala index 8c13f85a06..57dd4750df 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/util/search/gravsearch/types/GravsearchTypeInspectorSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/util/search/gravsearch/types/GravsearchTypeInspectorSpec.scala @@ -1332,7 +1332,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "The type inspection utility" should { "remove the type annotations from a WHERE clause" in { - val parsedQuery = GravsearchParser.parseQuery(QueryWithExplicitTypeAnnotations) + val parsedQuery = GravsearchParser.parseQuery(QueryWithExplicitTypeAnnotations) val whereClauseWithoutAnnotations = GravsearchTypeInspectionUtil.removeTypeAnnotations(parsedQuery.whereClause) whereClauseWithoutAnnotations should ===(whereClauseWithoutAnnotations) } @@ -1341,7 +1341,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "The annotation-reading type inspector" should { "get type information from a simple query" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = false) - val parsedQuery = GravsearchParser.parseQuery(QueryWithExplicitTypeAnnotations) + val parsedQuery = GravsearchParser.parseQuery(QueryWithExplicitTypeAnnotations) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1610,7 +1610,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "sanitize inconsistent types resulted from a union" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryWithInconsistentTypes3) + val parsedQuery = GravsearchParser.parseQuery(QueryWithInconsistentTypes3) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1669,7 +1669,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { """.stripMargin val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(queryWithOptional) + val parsedQuery = GravsearchParser.parseQuery(queryWithOptional) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1730,7 +1730,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "infer the most specific type from redundant ones given in a query" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryWithRedundantTypes) + val parsedQuery = GravsearchParser.parseQuery(QueryWithRedundantTypes) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1740,7 +1740,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "infer that an entity is a knora-api:Resource if there is an rdf:type statement about it and the specified type is a Knora resource class" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryRdfTypeRule) + val parsedQuery = GravsearchParser.parseQuery(QueryRdfTypeRule) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1754,7 +1754,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "infer a property's knora-api:objectType if the property's IRI is used as a predicate" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryKnoraObjectTypeFromPropertyIriRule) + val parsedQuery = GravsearchParser.parseQuery(QueryKnoraObjectTypeFromPropertyIriRule) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1763,7 +1763,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "infer an entity's type if the entity is used as the object of a statement and the predicate's knora-api:objectType is known" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryTypeOfObjectFromPropertyRule) + val parsedQuery = GravsearchParser.parseQuery(QueryTypeOfObjectFromPropertyRule) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1772,7 +1772,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "infer the knora-api:objectType of a property variable if it's used with an object whose type is known" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryKnoraObjectTypeFromObjectRule) + val parsedQuery = GravsearchParser.parseQuery(QueryKnoraObjectTypeFromObjectRule) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1781,7 +1781,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "infer an entity's type if the entity is used as the subject of a statement, the predicate is an IRI, and the predicate's knora-api:subjectType is known" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryTypeOfSubjectFromPropertyRule) + val parsedQuery = GravsearchParser.parseQuery(QueryTypeOfSubjectFromPropertyRule) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1790,7 +1790,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "infer the knora-api:objectType of a property variable if it's compared to a known property IRI in a FILTER" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryPropertyVarTypeFromFilterRule) + val parsedQuery = GravsearchParser.parseQuery(QueryPropertyVarTypeFromFilterRule) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1799,7 +1799,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "infer the type of a non-property variable if it's compared to an XSD literal in a FILTER" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryNonPropertyVarTypeFromFilterRule) + val parsedQuery = GravsearchParser.parseQuery(QueryNonPropertyVarTypeFromFilterRule) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1808,7 +1808,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "infer the type of a non-property variable used as the argument of a function in a FILTER" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryVarTypeFromFunction) + val parsedQuery = GravsearchParser.parseQuery(QueryVarTypeFromFunction) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1817,7 +1817,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "infer the type of a non-property IRI used as the argument of a function in a FILTER" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryIriTypeFromFunction) + val parsedQuery = GravsearchParser.parseQuery(QueryIriTypeFromFunction) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1826,7 +1826,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "infer the types in a query that requires 6 iterations" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(PathologicalQuery) + val parsedQuery = GravsearchParser.parseQuery(PathologicalQuery) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1835,7 +1835,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "know the object type of rdfs:label" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryWithRdfsLabelAndLiteral) + val parsedQuery = GravsearchParser.parseQuery(QueryWithRdfsLabelAndLiteral) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1844,7 +1844,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "infer the type of a variable used as the object of rdfs:label" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryWithRdfsLabelAndVariable) + val parsedQuery = GravsearchParser.parseQuery(QueryWithRdfsLabelAndVariable) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1853,7 +1853,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "infer the type of a variable when it is compared with another variable in a FILTER (in the simple schema)" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryComparingResourcesInSimpleSchema) + val parsedQuery = GravsearchParser.parseQuery(QueryComparingResourcesInSimpleSchema) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1862,7 +1862,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "infer the type of a variable when it is compared with another variable in a FILTER (in the complex schema)" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryComparingResourcesInComplexSchema) + val parsedQuery = GravsearchParser.parseQuery(QueryComparingResourcesInComplexSchema) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1871,7 +1871,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "infer the type of a resource IRI when it is compared with a variable in a FILTER (in the simple schema)" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryComparingResourceIriInSimpleSchema) + val parsedQuery = GravsearchParser.parseQuery(QueryComparingResourceIriInSimpleSchema) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1880,7 +1880,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "infer the type of a resource IRI when it is compared with a variable in a FILTER (in the complex schema)" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryComparingResourceIriInComplexSchema) + val parsedQuery = GravsearchParser.parseQuery(QueryComparingResourceIriInComplexSchema) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1889,7 +1889,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "infer knora-api:Resource as the subject type of a subproperty of knora-api:hasLinkTo" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryWithFilterComparison) + val parsedQuery = GravsearchParser.parseQuery(QueryWithFilterComparison) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1898,7 +1898,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "reject a query with a non-Knora property whose type cannot be inferred" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryNonKnoraTypeWithoutAnnotation) + val parsedQuery = GravsearchParser.parseQuery(QueryNonKnoraTypeWithoutAnnotation) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) assertThrows[GravsearchException] { @@ -1908,7 +1908,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "accept a query with a non-Knora property whose type can be inferred" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryNonKnoraTypeWithAnnotation) + val parsedQuery = GravsearchParser.parseQuery(QueryNonKnoraTypeWithAnnotation) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1917,7 +1917,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "ignore Gravsearch options" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryWithGravsearchOptions) + val parsedQuery = GravsearchParser.parseQuery(QueryWithGravsearchOptions) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) val result = Await.result(resultFuture, timeout) @@ -1926,7 +1926,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "reject a query with inconsistent types inferred from statements" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryWithInconsistentTypes1) + val parsedQuery = GravsearchParser.parseQuery(QueryWithInconsistentTypes1) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) assertThrows[GravsearchException] { @@ -1936,7 +1936,7 @@ class GravsearchTypeInspectorSpec extends CoreSpec() with ImplicitSender { "reject a query with inconsistent types inferred from a FILTER" in { val typeInspectionRunner = new GravsearchTypeInspectionRunner(responderData = responderData, inferTypes = true) - val parsedQuery = GravsearchParser.parseQuery(QueryWithInconsistentTypes2) + val parsedQuery = GravsearchParser.parseQuery(QueryWithInconsistentTypes2) val resultFuture: Future[GravsearchTypeInspectionResult] = typeInspectionRunner.inspectTypes(parsedQuery.whereClause, requestingUser = anythingAdminUser) assertThrows[GravsearchException] { diff --git a/webapi/src/test/scala/org/knora/webapi/messages/util/standoff/StandoffTagUtilV2Spec.scala b/webapi/src/test/scala/org/knora/webapi/messages/util/standoff/StandoffTagUtilV2Spec.scala index 73a4291a57..6cdd42c224 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/util/standoff/StandoffTagUtilV2Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/util/standoff/StandoffTagUtilV2Spec.scala @@ -21,7 +21,7 @@ import scala.concurrent.duration._ * Tests [[StandoffTagUtilV2]]. */ class StandoffTagUtilV2Spec extends CoreSpec { - private implicit val timeout: Timeout = 10.seconds + private implicit val timeout: Timeout = 10.seconds private implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance val standoff1: Vector[StandoffTagV2] = Vector( @@ -106,76 +106,76 @@ class StandoffTagUtilV2Spec extends CoreSpec { val sparqlResultsV1 = Map( "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/3" -> Map( - "http://www.knora.org/ontology/knora-base#standoffTagHasStartParent" -> "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/2", - "http://www.knora.org/ontology/knora-base#standoffTagHasStartIndex" -> "3", - "http://www.knora.org/ontology/knora-base#standoffTagHasEnd" -> "247", - "http://www.knora.org/ontology/knora-base#standoffTagHasStart" -> "235", - "http://www.knora.org/ontology/knora-base#standoffTagHasUUID" -> "JPyErhf2RVmq0QYTIAKwYw", + "http://www.knora.org/ontology/knora-base#standoffTagHasStartParent" -> "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/2", + "http://www.knora.org/ontology/knora-base#standoffTagHasStartIndex" -> "3", + "http://www.knora.org/ontology/knora-base#standoffTagHasEnd" -> "247", + "http://www.knora.org/ontology/knora-base#standoffTagHasStart" -> "235", + "http://www.knora.org/ontology/knora-base#standoffTagHasUUID" -> "JPyErhf2RVmq0QYTIAKwYw", "http://www.knora.org/ontology/knora-base#standoffTagHasInternalReference" -> "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/1", - "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" -> "http://www.knora.org/ontology/knora-base#StandoffInternalReferenceTag" + "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" -> "http://www.knora.org/ontology/knora-base#StandoffInternalReferenceTag" ), "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/0" -> Map( - "http://www.knora.org/ontology/knora-base#standoffTagHasStartIndex" -> "0", - "http://www.knora.org/ontology/knora-base#standoffTagHasEnd" -> "297", - "http://www.knora.org/ontology/knora-base#standoffTagHasStart" -> "0", - "http://www.knora.org/ontology/knora-base#standoffTagHasUUID" -> "PQ2Xgu4mTSywsqHM8um1Tg", + "http://www.knora.org/ontology/knora-base#standoffTagHasStartIndex" -> "0", + "http://www.knora.org/ontology/knora-base#standoffTagHasEnd" -> "297", + "http://www.knora.org/ontology/knora-base#standoffTagHasStart" -> "0", + "http://www.knora.org/ontology/knora-base#standoffTagHasUUID" -> "PQ2Xgu4mTSywsqHM8um1Tg", "http://www.knora.org/ontology/standoff#standoffRootTagHasDocumentType" -> "letter", - "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" -> "http://www.knora.org/ontology/standoff#StandoffRootTag" + "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" -> "http://www.knora.org/ontology/standoff#StandoffRootTag" ), "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/2" -> Map( "http://www.knora.org/ontology/knora-base#standoffTagHasStartParent" -> "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/0", - "http://www.knora.org/ontology/knora-base#standoffTagHasStartIndex" -> "2", - "http://www.knora.org/ontology/knora-base#standoffTagHasEnd" -> "295", - "http://www.knora.org/ontology/knora-base#standoffTagHasStart" -> "75", - "http://www.knora.org/ontology/knora-base#standoffTagHasUUID" -> "ysmmZTLdQEGP6dWtGOmZlg", - "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" -> "http://www.knora.org/ontology/standoff#StandoffParagraphTag" + "http://www.knora.org/ontology/knora-base#standoffTagHasStartIndex" -> "2", + "http://www.knora.org/ontology/knora-base#standoffTagHasEnd" -> "295", + "http://www.knora.org/ontology/knora-base#standoffTagHasStart" -> "75", + "http://www.knora.org/ontology/knora-base#standoffTagHasUUID" -> "ysmmZTLdQEGP6dWtGOmZlg", + "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" -> "http://www.knora.org/ontology/standoff#StandoffParagraphTag" ), "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/1" -> Map( "http://www.knora.org/ontology/knora-base#standoffTagHasOriginalXMLID" -> "first", - "http://www.knora.org/ontology/knora-base#standoffTagHasStartParent" -> "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/0", - "http://www.knora.org/ontology/knora-base#standoffTagHasStartIndex" -> "1", - "http://www.knora.org/ontology/knora-base#standoffTagHasEnd" -> "69", - "http://www.knora.org/ontology/knora-base#standoffTagHasStart" -> "5", - "http://www.knora.org/ontology/knora-base#standoffTagHasUUID" -> "98NJtln8QtaS5u7ahxeUfg", - "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" -> "http://www.knora.org/ontology/standoff#StandoffParagraphTag" + "http://www.knora.org/ontology/knora-base#standoffTagHasStartParent" -> "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/0", + "http://www.knora.org/ontology/knora-base#standoffTagHasStartIndex" -> "1", + "http://www.knora.org/ontology/knora-base#standoffTagHasEnd" -> "69", + "http://www.knora.org/ontology/knora-base#standoffTagHasStart" -> "5", + "http://www.knora.org/ontology/knora-base#standoffTagHasUUID" -> "98NJtln8QtaS5u7ahxeUfg", + "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" -> "http://www.knora.org/ontology/standoff#StandoffParagraphTag" ) ) val sparqlResultsV2 = Map( "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/2" -> Map( "http://www.knora.org/ontology/knora-base#standoffTagHasStartParent" -> "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/0", - "http://www.knora.org/ontology/knora-base#standoffTagHasStartIndex" -> "2", - "http://www.knora.org/ontology/knora-base#standoffTagHasEnd" -> "295", - "http://www.knora.org/ontology/knora-base#standoffTagHasStart" -> "75", - "http://www.knora.org/ontology/knora-base#standoffTagHasUUID" -> "ysmmZTLdQEGP6dWtGOmZlg", - "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" -> "http://www.knora.org/ontology/standoff#StandoffParagraphTag" + "http://www.knora.org/ontology/knora-base#standoffTagHasStartIndex" -> "2", + "http://www.knora.org/ontology/knora-base#standoffTagHasEnd" -> "295", + "http://www.knora.org/ontology/knora-base#standoffTagHasStart" -> "75", + "http://www.knora.org/ontology/knora-base#standoffTagHasUUID" -> "ysmmZTLdQEGP6dWtGOmZlg", + "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" -> "http://www.knora.org/ontology/standoff#StandoffParagraphTag" ), "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/1" -> Map( "http://www.knora.org/ontology/knora-base#standoffTagHasOriginalXMLID" -> "first", - "http://www.knora.org/ontology/knora-base#standoffTagHasStartParent" -> "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/0", - "http://www.knora.org/ontology/knora-base#standoffTagHasStartIndex" -> "1", - "http://www.knora.org/ontology/knora-base#standoffTagHasEnd" -> "69", - "http://www.knora.org/ontology/knora-base#standoffTagHasStart" -> "5", - "http://www.knora.org/ontology/knora-base#standoffTagHasUUID" -> "98NJtln8QtaS5u7ahxeUfg", - "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" -> "http://www.knora.org/ontology/standoff#StandoffParagraphTag" + "http://www.knora.org/ontology/knora-base#standoffTagHasStartParent" -> "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/0", + "http://www.knora.org/ontology/knora-base#standoffTagHasStartIndex" -> "1", + "http://www.knora.org/ontology/knora-base#standoffTagHasEnd" -> "69", + "http://www.knora.org/ontology/knora-base#standoffTagHasStart" -> "5", + "http://www.knora.org/ontology/knora-base#standoffTagHasUUID" -> "98NJtln8QtaS5u7ahxeUfg", + "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" -> "http://www.knora.org/ontology/standoff#StandoffParagraphTag" ), "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/0" -> Map( - "http://www.knora.org/ontology/knora-base#standoffTagHasStartIndex" -> "0", - "http://www.knora.org/ontology/knora-base#standoffTagHasEnd" -> "297", - "http://www.knora.org/ontology/knora-base#standoffTagHasStart" -> "0", - "http://www.knora.org/ontology/knora-base#standoffTagHasUUID" -> "PQ2Xgu4mTSywsqHM8um1Tg", + "http://www.knora.org/ontology/knora-base#standoffTagHasStartIndex" -> "0", + "http://www.knora.org/ontology/knora-base#standoffTagHasEnd" -> "297", + "http://www.knora.org/ontology/knora-base#standoffTagHasStart" -> "0", + "http://www.knora.org/ontology/knora-base#standoffTagHasUUID" -> "PQ2Xgu4mTSywsqHM8um1Tg", "http://www.knora.org/ontology/standoff#standoffRootTagHasDocumentType" -> "letter", - "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" -> "http://www.knora.org/ontology/standoff#StandoffRootTag" + "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" -> "http://www.knora.org/ontology/standoff#StandoffRootTag" ), "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/3" -> Map( - "http://www.knora.org/ontology/knora-base#standoffTagHasStartParent" -> "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/2", - "http://www.knora.org/ontology/knora-base#standoffTagHasStartIndex" -> "3", - "http://www.knora.org/ontology/knora-base#standoffTagHasEnd" -> "247", - "http://www.knora.org/ontology/knora-base#targetHasOriginalXMLID" -> "first", - "http://www.knora.org/ontology/knora-base#standoffTagHasStart" -> "235", - "http://www.knora.org/ontology/knora-base#standoffTagHasUUID" -> "JPyErhf2RVmq0QYTIAKwYw", + "http://www.knora.org/ontology/knora-base#standoffTagHasStartParent" -> "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/2", + "http://www.knora.org/ontology/knora-base#standoffTagHasStartIndex" -> "3", + "http://www.knora.org/ontology/knora-base#standoffTagHasEnd" -> "247", + "http://www.knora.org/ontology/knora-base#targetHasOriginalXMLID" -> "first", + "http://www.knora.org/ontology/knora-base#standoffTagHasStart" -> "235", + "http://www.knora.org/ontology/knora-base#standoffTagHasUUID" -> "JPyErhf2RVmq0QYTIAKwYw", "http://www.knora.org/ontology/knora-base#standoffTagHasInternalReference" -> "http://rdfh.ch/0001/a-thing/values/QJ0z7WgkTziowCAi-aGyWg/standoff/1", - "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" -> "http://www.knora.org/ontology/knora-base#StandoffInternalReferenceTag" + "http://www.w3.org/1999/02/22-rdf-syntax-ns#type" -> "http://www.knora.org/ontology/knora-base#StandoffInternalReferenceTag" ) ) diff --git a/webapi/src/test/scala/org/knora/webapi/messages/util/standoff/XMLToStandoffUtilSpec.scala b/webapi/src/test/scala/org/knora/webapi/messages/util/standoff/XMLToStandoffUtilSpec.scala index c3274268b3..acc11594ba 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/util/standoff/XMLToStandoffUtilSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/util/standoff/XMLToStandoffUtilSpec.scala @@ -254,8 +254,8 @@ class XMLToStandoffUtilSpec extends CoreSpec { "calculate the diffs in a workflow with two versions of a diplomatic transcription and two versions of an editorial text" in { val paragraphID = UUID.randomUUID - val strikeID = UUID.randomUUID - val blueID = UUID.randomUUID + val strikeID = UUID.randomUUID + val blueID = UUID.randomUUID val documentSpecificIDs = Map( "1" -> paragraphID, @@ -368,7 +368,7 @@ class XMLToStandoffUtilSpec extends CoreSpec { standoffUtil.findChangedStandoffTags(diplo1TextWithStandoff.standoff, diplo2TextWithStandoff.standoff) addedTags should be(Set(blueTag)) // Just the tag was added. - removedTags should be(Set()) // No tags were removed. + removedTags should be(Set()) // No tags were removed. // The editor now corrects the editorial text to take into account the change from 'Bus' to 'Bahn'. This // means that the abbreviation 'd' in the transcription now has to be expanded as 'die' rather than 'der'. diff --git a/webapi/src/test/scala/org/knora/webapi/messages/util/standoff/XMLUtilSpec.scala b/webapi/src/test/scala/org/knora/webapi/messages/util/standoff/XMLUtilSpec.scala index c481e0e46b..3511b3accd 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/util/standoff/XMLUtilSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/util/standoff/XMLUtilSpec.scala @@ -89,7 +89,7 @@ class XMLUtilSpec extends CoreSpec { FileUtil.readTextFile(Paths.get("..", "test_data/test_route/texts/beol/xml-with-non-nested-resources.xml")) val xslt = FileUtil.readTextFile(Paths.get("..", "test_data/test_route/texts/beol/header.xsl")) - val transformedXmlWithNestedResource: String = XMLUtil.applyXSLTransformation(xmlWithNestedResource, xslt) + val transformedXmlWithNestedResource: String = XMLUtil.applyXSLTransformation(xmlWithNestedResource, xslt) val transformedXmlWithNonNestedResource: String = XMLUtil.applyXSLTransformation(xmlWithNonNestedResource, xslt) val xmlDiff: Diff = DiffBuilder diff --git a/webapi/src/test/scala/org/knora/webapi/messages/v1/responder/permissionmessages/PermissionMessagesV1Spec.scala b/webapi/src/test/scala/org/knora/webapi/messages/v1/responder/permissionmessages/PermissionMessagesV1Spec.scala index e70e72bb9c..497c5df512 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/v1/responder/permissionmessages/PermissionMessagesV1Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/v1/responder/permissionmessages/PermissionMessagesV1Spec.scala @@ -17,7 +17,7 @@ class PermissionMessagesV1Spec extends AnyWordSpecLike with Matchers { "return true if the user is allowed to create a resource (root user)" in { - val projectIri = INCUNABULA_PROJECT_IRI + val projectIri = INCUNABULA_PROJECT_IRI val resourceClassIri = s"$INCUNABULA_ONTOLOGY_IRI#book" val result = SharedTestDataV1.rootUser.permissionData.hasPermissionFor( @@ -31,7 +31,7 @@ class PermissionMessagesV1Spec extends AnyWordSpecLike with Matchers { "return true if the user is allowed to create a resource (project admin user)" in { - val projectIri = INCUNABULA_PROJECT_IRI + val projectIri = INCUNABULA_PROJECT_IRI val resourceClassIri = s"$INCUNABULA_ONTOLOGY_IRI#book" val result = SharedTestDataV1.incunabulaProjectAdminUser.permissionData @@ -42,7 +42,7 @@ class PermissionMessagesV1Spec extends AnyWordSpecLike with Matchers { "return true if the user is allowed to create a resource (project member user)" in { - val projectIri = INCUNABULA_PROJECT_IRI + val projectIri = INCUNABULA_PROJECT_IRI val resourceClassIri = s"$INCUNABULA_ONTOLOGY_IRI#book" val result = SharedTestDataV1.incunabulaMemberUser.permissionData @@ -52,7 +52,7 @@ class PermissionMessagesV1Spec extends AnyWordSpecLike with Matchers { } "return false if the user is not allowed to create a resource" in { - val projectIri = INCUNABULA_PROJECT_IRI + val projectIri = INCUNABULA_PROJECT_IRI val resourceClassIri = s"$INCUNABULA_ONTOLOGY_IRI#book" val result = SharedTestDataV1.normalUser.permissionData @@ -62,9 +62,9 @@ class PermissionMessagesV1Spec extends AnyWordSpecLike with Matchers { } "return true if the user is allowed to create a resource (ProjectResourceCreateRestrictedPermission)" in { - val projectIri = IMAGES_PROJECT_IRI - val allowedResourceClassIri01 = s"$IMAGES_ONTOLOGY_IRI#bild" - val allowedResourceClassIri02 = s"$IMAGES_ONTOLOGY_IRI#bildformat" + val projectIri = IMAGES_PROJECT_IRI + val allowedResourceClassIri01 = s"$IMAGES_ONTOLOGY_IRI#bild" + val allowedResourceClassIri02 = s"$IMAGES_ONTOLOGY_IRI#bildformat" val notAllowedResourceClassIri = s"$IMAGES_ONTOLOGY_IRI#person" val result1 = SharedTestDataV1.imagesReviewerUser.permissionData @@ -77,7 +77,7 @@ class PermissionMessagesV1Spec extends AnyWordSpecLike with Matchers { } "return false if the user is not allowed to create a resource (ProjectResourceCreateRestrictedPermission)" in { - val projectIri = IMAGES_PROJECT_IRI + val projectIri = IMAGES_PROJECT_IRI val notAllowedResourceClassIri = s"$IMAGES_ONTOLOGY_IRI#person" val result = SharedTestDataV1.imagesReviewerUser.permissionData @@ -98,7 +98,7 @@ class PermissionMessagesV1Spec extends AnyWordSpecLike with Matchers { "return false if the user has the 'ProjectAdminAllPermission' (incunabula member user)" in { val projectIri = INCUNABULA_PROJECT_IRI - val result = SharedTestDataV1.incunabulaMemberUser.permissionData.hasProjectAdminAllPermissionFor(projectIri) + val result = SharedTestDataV1.incunabulaMemberUser.permissionData.hasProjectAdminAllPermissionFor(projectIri) result should be(false) } diff --git a/webapi/src/test/scala/org/knora/webapi/messages/v1/responder/usermessages/UserMessagesV1Spec.scala b/webapi/src/test/scala/org/knora/webapi/messages/v1/responder/usermessages/UserMessagesV1Spec.scala index a3db2fa413..6775f10d60 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/v1/responder/usermessages/UserMessagesV1Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/v1/responder/usermessages/UserMessagesV1Spec.scala @@ -18,17 +18,17 @@ import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder */ class UserMessagesV1Spec extends AnyWordSpecLike with Matchers { - private val lang = SharedTestDataV1.rootUser.userData.lang - private val user_id = SharedTestDataV1.rootUser.userData.user_id - private val token = SharedTestDataV1.rootUser.userData.token - private val firstname = SharedTestDataV1.rootUser.userData.firstname - private val lastname = SharedTestDataV1.rootUser.userData.lastname - private val email = SharedTestDataV1.rootUser.userData.email - private val password = SharedTestDataV1.rootUser.userData.password - private val groups = SharedTestDataV1.rootUser.groups - private val projects_info = SharedTestDataV1.rootUser.projects_info + private val lang = SharedTestDataV1.rootUser.userData.lang + private val user_id = SharedTestDataV1.rootUser.userData.user_id + private val token = SharedTestDataV1.rootUser.userData.token + private val firstname = SharedTestDataV1.rootUser.userData.firstname + private val lastname = SharedTestDataV1.rootUser.userData.lastname + private val email = SharedTestDataV1.rootUser.userData.email + private val password = SharedTestDataV1.rootUser.userData.password + private val groups = SharedTestDataV1.rootUser.groups + private val projects_info = SharedTestDataV1.rootUser.projects_info private val permissionData = SharedTestDataV1.rootUser.permissionData - private val sessionId = SharedTestDataV1.rootUser.sessionId + private val sessionId = SharedTestDataV1.rootUser.sessionId "The UserProfileV1 case class " should { "return a safe UserProfileV1 when requested " in { @@ -69,7 +69,7 @@ class UserMessagesV1Spec extends AnyWordSpecLike with Matchers { "allow checking SCrypt passwords" in { //hashedPassword = encoder.encode(createRequest.password); val encoder = new SCryptPasswordEncoder - val hp = encoder.encode("123456") + val hp = encoder.encode("123456") val up = UserProfileV1( userData = UserDataV1( password = Some(hp), @@ -88,7 +88,7 @@ class UserMessagesV1Spec extends AnyWordSpecLike with Matchers { "allow checking BCrypt passwords" in { //hashedPassword = encoder.encode(createRequest.password); val encoder = new BCryptPasswordEncoder - val hp = encoder.encode("123456") + val hp = encoder.encode("123456") val up = UserProfileV1( userData = UserDataV1( password = Some(hp), diff --git a/webapi/src/test/scala/org/knora/webapi/messages/v2/responder/ontologymessages/ChangePropertyGuiElementRequestV2Spec.scala b/webapi/src/test/scala/org/knora/webapi/messages/v2/responder/ontologymessages/ChangePropertyGuiElementRequestV2Spec.scala index 6d0484528c..0261dbdd34 100644 --- a/webapi/src/test/scala/org/knora/webapi/messages/v2/responder/ontologymessages/ChangePropertyGuiElementRequestV2Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/messages/v2/responder/ontologymessages/ChangePropertyGuiElementRequestV2Spec.scala @@ -60,16 +60,16 @@ class ChangePropertyGuiElementRequestV2Spec extends AsyncCoreSpec { val requestMessageFuture: Future[ChangePropertyGuiElementRequest] = for { requestMessage: ChangePropertyGuiElementRequest <- ChangePropertyGuiElementRequest - .fromJsonLD( - jsonLDDocument = requestDoc, - apiRequestID = UUID.randomUUID, - requestingUser = requestingUser, - responderManager = responderManager, - storeManager = storeManager, - featureFactoryConfig = featureFactoryConfig, - settings = settings, - log = log - ) + .fromJsonLD( + jsonLDDocument = requestDoc, + apiRequestID = UUID.randomUUID, + requestingUser = requestingUser, + responderManager = responderManager, + storeManager = storeManager, + featureFactoryConfig = featureFactoryConfig, + settings = settings, + log = log + ) } yield requestMessage requestMessageFuture map { changePropertyGuiElementRequestMessage => diff --git a/webapi/src/test/scala/org/knora/webapi/models/OntologyModels.scala b/webapi/src/test/scala/org/knora/webapi/models/OntologyModels.scala index 2529f22435..337555edb3 100644 --- a/webapi/src/test/scala/org/knora/webapi/models/OntologyModels.scala +++ b/webapi/src/test/scala/org/knora/webapi/models/OntologyModels.scala @@ -33,7 +33,7 @@ object CreateClassRequest { label: LangString, comment: Option[LangString] ): CreateClassRequest = { - val ontologyId = s"http://0.0.0.0:3333/ontology/0001/$ontologyName/v2" + val ontologyId = s"http://0.0.0.0:3333/ontology/0001/$ontologyName/v2" val maybeComment: String = Comments.handleOptionalComment(comment) val value = s"""{ @@ -94,8 +94,8 @@ object CreatePropertyRequest { label: LangString, comment: Option[LangString] ): CreatePropertyRequest = { - val LocalHost_Ontology = "http://0.0.0.0:3333/ontology" - val ontologyId = LocalHost_Ontology + s"/0001/$ontologyName/v2" + val LocalHost_Ontology = "http://0.0.0.0:3333/ontology" + val ontologyId = LocalHost_Ontology + s"/0001/$ontologyName/v2" val maybeComment: String = Comments.handleOptionalComment(comment) val optionalSubjectClass = subjectClassName match { @@ -151,15 +151,15 @@ sealed trait CardinalityRestriction { object CardinalityRestriction { case object MaxCardinalityOne extends CardinalityRestriction { val cardinality = "owl:maxCardinality" - val value = 1 + val value = 1 } case object MinCardinalityOne extends CardinalityRestriction { val cardinality = "owl:minCardinality" - val value = 1 + val value = 1 } case object MinCardinalityZero extends CardinalityRestriction { val cardinality = "owl:minCardinality" - val value = 0 + val value = 0 } } @@ -194,9 +194,9 @@ object AddCardinalitiesRequest { className: String, restrictions: List[Restriction] ): AddCardinalitiesRequest = { - val ontologyId = s"http://0.0.0.0:3333/ontology/0001/$ontologyName/v2" + val ontologyId = s"http://0.0.0.0:3333/ontology/0001/$ontologyName/v2" val restrictionsString: String = stringifyRestrictions(restrictions) - val value = s""" + val value = s""" |{ | "@id" : "$ontologyId", | "@type" : "owl:Ontology", diff --git a/webapi/src/test/scala/org/knora/webapi/models/filemodels/FileModelUtil.scala b/webapi/src/test/scala/org/knora/webapi/models/filemodels/FileModelUtil.scala index 63b6e7dbd5..a1a23cb42e 100644 --- a/webapi/src/test/scala/org/knora/webapi/models/filemodels/FileModelUtil.scala +++ b/webapi/src/test/scala/org/knora/webapi/models/filemodels/FileModelUtil.scala @@ -191,19 +191,19 @@ object FileModelUtil { * Constants for use in FileModels. */ object FileModelConstants { - val documentRepresentation = "DocumentRepresentation" - val textRepresentation = "TextRepresentation" - val stillImageRepresentation = "StillImageRepresentation" + val documentRepresentation = "DocumentRepresentation" + val textRepresentation = "TextRepresentation" + val stillImageRepresentation = "StillImageRepresentation" val movingImageRepresentation = "MovingImageRepresentation" - val audioRepresentation = "AudioRepresentation" - val archiveRepresentation = "ArchiveRepresentation" - val knoraApiPrefix = "knora-api" - val anythingShortcode = "0001" + val audioRepresentation = "AudioRepresentation" + val archiveRepresentation = "ArchiveRepresentation" + val knoraApiPrefix = "knora-api" + val anythingShortcode = "0001" val defaultJsonLdContextMap = Map( - "rdf" -> "http://www.w3.org/1999/02/22-rdf-syntax-ns#", + "rdf" -> "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "knora-api" -> "http://api.knora.org/ontology/knora-api/v2#", - "rdfs" -> "http://www.w3.org/2000/01/rdf-schema#", - "xsd" -> "http://www.w3.org/2001/XMLSchema#" + "rdfs" -> "http://www.w3.org/2000/01/rdf-schema#", + "xsd" -> "http://www.w3.org/2001/XMLSchema#" ) } @@ -213,10 +213,10 @@ object FileType { pageCount: Option[Int] = Some(1), dimX: Option[Int] = Some(100), dimY: Option[Int] = Some(100) - ) extends FileType - case class StillImageFile(dimX: Int = 100, dimY: Int = 100) extends FileType + ) extends FileType + case class StillImageFile(dimX: Int = 100, dimY: Int = 100) extends FileType case class MovingImageFile(dimX: Int = 100, dimY: Int = 100) extends FileType - case object TextFile extends FileType - case object AudioFile extends FileType - case object ArchiveFile extends FileType + case object TextFile extends FileType + case object AudioFile extends FileType + case object ArchiveFile extends FileType } diff --git a/webapi/src/test/scala/org/knora/webapi/models/filemodels/FileModels.scala b/webapi/src/test/scala/org/knora/webapi/models/filemodels/FileModels.scala index 1ae51cf1ec..3949d52912 100644 --- a/webapi/src/test/scala/org/knora/webapi/models/filemodels/FileModels.scala +++ b/webapi/src/test/scala/org/knora/webapi/models/filemodels/FileModels.scala @@ -40,8 +40,8 @@ sealed abstract case class UploadFileRequest private ( ontologyIRI: Option[String] = None ): String = { val fileValuePropertyName = FileModelUtil.getFileValuePropertyName(fileType) - val fileValueType = FileModelUtil.getFileValueType(fileType) - val context = FileModelUtil.getJsonLdContext(ontologyName, ontologyIRI) + val fileValueType = FileModelUtil.getFileValueType(fileType) + val context = FileModelUtil.getJsonLdContext(ontologyName, ontologyIRI) val classNameWithDefaults = className match { case Some(v) => v case None => FileModelUtil.getDefaultClassName(fileType) @@ -207,8 +207,8 @@ sealed abstract case class ChangeFileRequest private ( */ def toJsonLd: String = { val fileValuePropertyName = FileModelUtil.getFileValuePropertyName(fileType) - val fileValueType = FileModelUtil.getFileValueType(fileType) - val context = FileModelUtil.getJsonLdContext(ontologyName) + val fileValueType = FileModelUtil.getFileValueType(fileType) + val context = FileModelUtil.getJsonLdContext(ontologyName) s"""{ | "@id" : "$resourceIRI", diff --git a/webapi/src/test/scala/org/knora/webapi/models/filemodels/FileModelsSpec.scala b/webapi/src/test/scala/org/knora/webapi/models/filemodels/FileModelsSpec.scala index 775e563976..c9b0a179cb 100644 --- a/webapi/src/test/scala/org/knora/webapi/models/filemodels/FileModelsSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/models/filemodels/FileModelsSpec.scala @@ -20,12 +20,12 @@ import spray.json.DefaultJsonProtocol._ class FileModelsSpec extends CoreSpec { implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - private val fileNamePDF = "document-file.pdf" - private val fileNameImage = "image.jp2" - private val fileNameVideo = "video.mp4" - private val fileNameAudio = "audio.mpeg" - private val fileNameText = "text.txt" - private val fileNameArchive = "archive.zip" + private val fileNamePDF = "document-file.pdf" + private val fileNameImage = "image.jp2" + private val fileNameVideo = "video.mp4" + private val fileNameAudio = "audio.mpeg" + private val fileNameText = "text.txt" + private val fileNameArchive = "archive.zip" "FileModelsUtil," when { @@ -100,10 +100,10 @@ class FileModelsSpec extends CoreSpec { "create a valid representation of a DocumentRepresentation with custom values" in { val internalFilename = "document-file.doc" - val dimX = Some(20) - val dimY = Some(30) - val pageCount = Some(550) - val customLabel = "a custom label" + val dimX = Some(20) + val dimY = Some(30) + val pageCount = Some(550) + val customLabel = "a custom label" val documentRepresentation = UploadFileRequest.make( fileType = FileType.DocumentFile( pageCount = pageCount, @@ -233,7 +233,7 @@ class FileModelsSpec extends CoreSpec { val expectedJSON = Map( "@type" -> "knora-api:DocumentRepresentation".toJson, "knora-api:hasDocumentFileValue" -> Map( - "@type" -> "knora-api:DocumentFileValue", + "@type" -> "knora-api:DocumentFileValue", "knora-api:fileValueHasFilename" -> fileNamePDF ).toJson, "knora-api:attachedToProject" -> Map( @@ -241,21 +241,21 @@ class FileModelsSpec extends CoreSpec { ).toJson, "rdfs:label" -> "test label".toJson, "@context" -> Map( - "rdf" -> "http://www.w3.org/1999/02/22-rdf-syntax-ns#", + "rdf" -> "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "knora-api" -> "http://api.knora.org/ontology/knora-api/v2#", - "rdfs" -> "http://www.w3.org/2000/01/rdf-schema#", - "xsd" -> "http://www.w3.org/2001/XMLSchema#" + "rdfs" -> "http://www.w3.org/2000/01/rdf-schema#", + "xsd" -> "http://www.w3.org/2001/XMLSchema#" ).toJson ).toJson json should equal(expectedJSON) } "correctly serialize a DocumentRepresentation with custom values" in { - val className = Some("ThingDocument") + val className = Some("ThingDocument") val ontologyName = "biblio" - val shortcode = SharedTestDataADM.beolProject.shortcode - val ontologyIRI = SharedTestDataADM.beolProject.ontologies.find(_.endsWith(ontologyName)) - val label = "a custom label" + val shortcode = SharedTestDataADM.beolProject.shortcode + val ontologyIRI = SharedTestDataADM.beolProject.ontologies.find(_.endsWith(ontologyName)) + val label = "a custom label" val documentRepresentation = UploadFileRequest.make( fileType = FileType.DocumentFile(pageCount = None, dimX = Some(20), dimY = None), @@ -273,7 +273,7 @@ class FileModelsSpec extends CoreSpec { val expectedJSON = Map( "@type" -> s"$ontologyName:${className.get}".toJson, "knora-api:hasDocumentFileValue" -> Map( - "@type" -> "knora-api:DocumentFileValue", + "@type" -> "knora-api:DocumentFileValue", "knora-api:fileValueHasFilename" -> fileNamePDF ).toJson, "knora-api:attachedToProject" -> Map( @@ -281,10 +281,10 @@ class FileModelsSpec extends CoreSpec { ).toJson, "rdfs:label" -> label.toJson, "@context" -> Map( - "rdf" -> "http://www.w3.org/1999/02/22-rdf-syntax-ns#", - "knora-api" -> "http://api.knora.org/ontology/knora-api/v2#", - "rdfs" -> "http://www.w3.org/2000/01/rdf-schema#", - "xsd" -> "http://www.w3.org/2001/XMLSchema#", + "rdf" -> "http://www.w3.org/1999/02/22-rdf-syntax-ns#", + "knora-api" -> "http://api.knora.org/ontology/knora-api/v2#", + "rdfs" -> "http://www.w3.org/2000/01/rdf-schema#", + "xsd" -> "http://www.w3.org/2001/XMLSchema#", ontologyName -> ontologyIRI.get ).toJson ).toJson @@ -334,24 +334,24 @@ class FileModelsSpec extends CoreSpec { } "correctly serialize a DocumentRepresentation with custom values" in { - val pageCount = None - val dimX = Some(20) - val dimY = None - val project = SharedTestDataADM.beolProject - val shortcode = project.shortcode - val label = "a custom label" - val resourceIRI = stringFormatter.makeRandomResourceIri(shortcode) - val comment = Some("This is a custom comment") - val internalMimetype = Some("application/msword") - val originalFilename = Some("document-file.docm") - val originalMimeType = Some("application/vnd.ms-word.document.macroEnabled.12") - val customValueIRI = Some(stringFormatter.makeRandomResourceIri(shortcode).toSmartIri) - val customValueUUID = Some(UUID.randomUUID()) - val customValueCreationDate = Some(Instant.now()) - val valuePermissions = Some("V knora-admin:UnknownUser,knora-admin:KnownUser|M knora-admin:ProjectMember") - val resourcePermissions = Some("V knora-admin:UnknownUser|M knora-admin:ProjectMember,knora-admin:KnownUser") - val valuePropertyIRI = "http://www.knora.org/ontology/0801/biblio#hasThingDocumentValue".toSmartIri - val resourceClassIRI = "http://www.knora.org/ontology/0801/biblio#Book".toSmartIri + val pageCount = None + val dimX = Some(20) + val dimY = None + val project = SharedTestDataADM.beolProject + val shortcode = project.shortcode + val label = "a custom label" + val resourceIRI = stringFormatter.makeRandomResourceIri(shortcode) + val comment = Some("This is a custom comment") + val internalMimetype = Some("application/msword") + val originalFilename = Some("document-file.docm") + val originalMimeType = Some("application/vnd.ms-word.document.macroEnabled.12") + val customValueIRI = Some(stringFormatter.makeRandomResourceIri(shortcode).toSmartIri) + val customValueUUID = Some(UUID.randomUUID()) + val customValueCreationDate = Some(Instant.now()) + val valuePermissions = Some("V knora-admin:UnknownUser,knora-admin:KnownUser|M knora-admin:ProjectMember") + val resourcePermissions = Some("V knora-admin:UnknownUser|M knora-admin:ProjectMember,knora-admin:KnownUser") + val valuePropertyIRI = "http://www.knora.org/ontology/0801/biblio#hasThingDocumentValue".toSmartIri + val resourceClassIRI = "http://www.knora.org/ontology/0801/biblio#Book".toSmartIri val customResourceCreationDate = Some(Instant.now()) val documentRepresentation = UploadFileRequest.make( @@ -415,7 +415,7 @@ class FileModelsSpec extends CoreSpec { "create a valid representation of a DocumentRepresentation with default values" in { val resourceIRI = stringFormatter.makeRandomResourceIri("0000") - val valueIRI = stringFormatter.makeRandomResourceIri("0000") + val valueIRI = stringFormatter.makeRandomResourceIri("0000") val change = ChangeFileRequest.make( fileType = FileType.DocumentFile(), @@ -438,12 +438,12 @@ class FileModelsSpec extends CoreSpec { } "create a valid representation of a DocumentRepresentation with custom values" in { - val resourceIRI = stringFormatter.makeRandomResourceIri("0000") - val valueIRI = stringFormatter.makeRandomResourceIri("0000") - val pageCount = Some(33) - val dimX = Some(44) - val dimY = Some(55) - val className = "CustomDocumentResource" + val resourceIRI = stringFormatter.makeRandomResourceIri("0000") + val valueIRI = stringFormatter.makeRandomResourceIri("0000") + val pageCount = Some(33) + val dimX = Some(44) + val dimY = Some(55) + val className = "CustomDocumentResource" val ontologyName = "anything" val change = ChangeFileRequest.make( @@ -474,7 +474,7 @@ class FileModelsSpec extends CoreSpec { "create a valid representation of a StillImageRepresentation with default values" in { val resourceIRI = stringFormatter.makeRandomResourceIri("0000") - val valueIRI = stringFormatter.makeRandomResourceIri("0000") + val valueIRI = stringFormatter.makeRandomResourceIri("0000") val change = ChangeFileRequest.make( fileType = FileType.StillImageFile(), @@ -497,7 +497,7 @@ class FileModelsSpec extends CoreSpec { "create a valid representation of a MovingImageRepresentation with default values" in { val resourceIRI = stringFormatter.makeRandomResourceIri("0000") - val valueIRI = stringFormatter.makeRandomResourceIri("0000") + val valueIRI = stringFormatter.makeRandomResourceIri("0000") val change = ChangeFileRequest.make( fileType = FileType.MovingImageFile(), @@ -520,7 +520,7 @@ class FileModelsSpec extends CoreSpec { "create a valid representation of a AudioRepresentation with default values" in { val resourceIRI = stringFormatter.makeRandomResourceIri("0000") - val valueIRI = stringFormatter.makeRandomResourceIri("0000") + val valueIRI = stringFormatter.makeRandomResourceIri("0000") val change = ChangeFileRequest.make( fileType = FileType.AudioFile, @@ -538,7 +538,7 @@ class FileModelsSpec extends CoreSpec { "create a valid representation of a TextRepresentation with default values" in { val resourceIRI = stringFormatter.makeRandomResourceIri("0000") - val valueIRI = stringFormatter.makeRandomResourceIri("0000") + val valueIRI = stringFormatter.makeRandomResourceIri("0000") val change = ChangeFileRequest.make( fileType = FileType.TextFile, @@ -556,7 +556,7 @@ class FileModelsSpec extends CoreSpec { "create a valid representation of a ArchiveRepresentation with default values" in { val resourceIRI = stringFormatter.makeRandomResourceIri("0000") - val valueIRI = stringFormatter.makeRandomResourceIri("0000") + val valueIRI = stringFormatter.makeRandomResourceIri("0000") val change = ChangeFileRequest.make( fileType = FileType.ArchiveFile, @@ -578,7 +578,7 @@ class FileModelsSpec extends CoreSpec { "correctly serialize a DocumentRepresentation with default values" in { val resourceIRI = stringFormatter.makeRandomResourceIri("7777") - val valueIRI = stringFormatter.makeRandomResourceIri("7777") + val valueIRI = stringFormatter.makeRandomResourceIri("7777") val documentRepresentation = ChangeFileRequest.make( fileType = FileType.DocumentFile(), @@ -588,18 +588,18 @@ class FileModelsSpec extends CoreSpec { ) val json = documentRepresentation.toJsonLd.parseJson val expectedJSON = Map( - "@id" -> resourceIRI.toJson, + "@id" -> resourceIRI.toJson, "@type" -> "knora-api:DocumentRepresentation".toJson, "knora-api:hasDocumentFileValue" -> Map( - "@id" -> valueIRI, - "@type" -> "knora-api:DocumentFileValue", + "@id" -> valueIRI, + "@type" -> "knora-api:DocumentFileValue", "knora-api:fileValueHasFilename" -> fileNamePDF ).toJson, "@context" -> Map( - "rdf" -> "http://www.w3.org/1999/02/22-rdf-syntax-ns#", + "rdf" -> "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "knora-api" -> "http://api.knora.org/ontology/knora-api/v2#", - "rdfs" -> "http://www.w3.org/2000/01/rdf-schema#", - "xsd" -> "http://www.w3.org/2001/XMLSchema#" + "rdfs" -> "http://www.w3.org/2000/01/rdf-schema#", + "xsd" -> "http://www.w3.org/2001/XMLSchema#" ).toJson ).toJson json should equal(expectedJSON) @@ -607,9 +607,9 @@ class FileModelsSpec extends CoreSpec { "correctly serialize a DocumentRepresentation with custom values" in { val resourceIRI = stringFormatter.makeRandomResourceIri("7777") - val valueIRI = stringFormatter.makeRandomResourceIri("7777") - val className = "CustomDocumentRepresentation" - val prefix = "onto" + val valueIRI = stringFormatter.makeRandomResourceIri("7777") + val className = "CustomDocumentRepresentation" + val prefix = "onto" val documentRepresentation = ChangeFileRequest.make( fileType = FileType.DocumentFile(), @@ -621,18 +621,18 @@ class FileModelsSpec extends CoreSpec { ) val json = documentRepresentation.toJsonLd.parseJson val expectedJSON = Map( - "@id" -> resourceIRI.toJson, + "@id" -> resourceIRI.toJson, "@type" -> s"$prefix:$className".toJson, "knora-api:hasDocumentFileValue" -> Map( - "@id" -> valueIRI, - "@type" -> "knora-api:DocumentFileValue", + "@id" -> valueIRI, + "@type" -> "knora-api:DocumentFileValue", "knora-api:fileValueHasFilename" -> fileNamePDF ).toJson, "@context" -> Map( - "rdf" -> "http://www.w3.org/1999/02/22-rdf-syntax-ns#", + "rdf" -> "http://www.w3.org/1999/02/22-rdf-syntax-ns#", "knora-api" -> "http://api.knora.org/ontology/knora-api/v2#", - "rdfs" -> "http://www.w3.org/2000/01/rdf-schema#", - "xsd" -> "http://www.w3.org/2001/XMLSchema#" + "rdfs" -> "http://www.w3.org/2000/01/rdf-schema#", + "xsd" -> "http://www.w3.org/2001/XMLSchema#" ).toJson ).toJson json should equal(expectedJSON) @@ -643,7 +643,7 @@ class FileModelsSpec extends CoreSpec { "correctly serialize a DocumentRepresentation with default values" in { val resourceIRI = stringFormatter.makeRandomResourceIri("7777") - val valueIRI = stringFormatter.makeRandomResourceIri("7777") + val valueIRI = stringFormatter.makeRandomResourceIri("7777") val documentRepresentation = ChangeFileRequest.make( fileType = FileType.DocumentFile(), @@ -674,19 +674,19 @@ class FileModelsSpec extends CoreSpec { } "correctly serialize a DocumentRepresentation with custom values" in { - val resourceIRI = stringFormatter.makeRandomResourceIri("7777") - val valueIRI = stringFormatter.makeRandomResourceIri("7777") - val className = "CustomDocumentRepresentation" - val prefix = "onto" - val fileName = "wordfile.docx" - val internalMimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" - val originalFileName = "original-wordfile.doc" - val originalMimetype = "application/msword" - val customComment = "a comment on this word file" - val valuePermission = Some("V knora-admin:UnknownUser,knora-admin:KnownUser|M knora-admin:ProjectMember") + val resourceIRI = stringFormatter.makeRandomResourceIri("7777") + val valueIRI = stringFormatter.makeRandomResourceIri("7777") + val className = "CustomDocumentRepresentation" + val prefix = "onto" + val fileName = "wordfile.docx" + val internalMimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document" + val originalFileName = "original-wordfile.doc" + val originalMimetype = "application/msword" + val customComment = "a comment on this word file" + val valuePermission = Some("V knora-admin:UnknownUser,knora-admin:KnownUser|M knora-admin:ProjectMember") val customValueCreationDate = Some(Instant.now()) - val customValueVersionIRI = Some(stringFormatter.makeRandomResourceIri("7777").toSmartIri) - val resourceClassIRI = "http://www.knora.org/ontology/0801/biblio#Book".toSmartIri + val customValueVersionIRI = Some(stringFormatter.makeRandomResourceIri("7777").toSmartIri) + val resourceClassIRI = "http://www.knora.org/ontology/0801/biblio#Book".toSmartIri val documentRepresentation = ChangeFileRequest.make( fileType = FileType.DocumentFile(), diff --git a/webapi/src/test/scala/org/knora/webapi/models/standoffmodels/StandoffModels.scala b/webapi/src/test/scala/org/knora/webapi/models/standoffmodels/StandoffModels.scala index dd6dd76984..6a085e0803 100644 --- a/webapi/src/test/scala/org/knora/webapi/models/standoffmodels/StandoffModels.scala +++ b/webapi/src/test/scala/org/knora/webapi/models/standoffmodels/StandoffModels.scala @@ -41,7 +41,7 @@ sealed abstract case class DefineStandoffMapping private ( ).toJson, "rdfs:label" -> label.toJson, JsonLDKeywords.CONTEXT -> Map( - "rdfs" -> OntologyConstants.Rdfs.RdfsPrefixExpansion, + "rdfs" -> OntologyConstants.Rdfs.RdfsPrefixExpansion, "knora-api" -> OntologyConstants.KnoraApiV2Complex.KnoraApiV2PrefixExpansion ).toJson ).toJson.prettyPrint diff --git a/webapi/src/test/scala/org/knora/webapi/models/standoffmodels/StandoffModelsSpec.scala b/webapi/src/test/scala/org/knora/webapi/models/standoffmodels/StandoffModelsSpec.scala index 5fc5c49dda..0bbe0628de 100644 --- a/webapi/src/test/scala/org/knora/webapi/models/standoffmodels/StandoffModelsSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/models/standoffmodels/StandoffModelsSpec.scala @@ -20,7 +20,7 @@ class StandoffModelsSpec extends CoreSpec { "create a valid representation of the mapping with default values" in { val mappingName = "customMapping" - val mapping = DefineStandoffMapping.make(mappingName) + val mapping = DefineStandoffMapping.make(mappingName) mapping.mappingName should equal(mappingName) mapping.projectIRI should equal(ANYTHING_PROJECT_IRI) @@ -29,7 +29,7 @@ class StandoffModelsSpec extends CoreSpec { "create a valid representation of the mapping with custom values" in { val mappingName = "customMapping" - val projectIRI = INCUNABULA_PROJECT_IRI + val projectIRI = INCUNABULA_PROJECT_IRI val customLabel = "this is a custom mapping with a custom label" val mapping = DefineStandoffMapping.make( mappingName = mappingName, @@ -46,8 +46,8 @@ class StandoffModelsSpec extends CoreSpec { "serializing to JSON-LD," should { "create a valid serialization of a standoff mapping request with default values" in { val mappingName = "customMapping" - val mapping = DefineStandoffMapping.make(mappingName) - val json = mapping.toJSONLD().parseJson + val mapping = DefineStandoffMapping.make(mappingName) + val json = mapping.toJSONLD().parseJson val expectedJSON = s""" @@ -68,7 +68,7 @@ class StandoffModelsSpec extends CoreSpec { } "create a valid serialization of a standoff mapping request with custom values" in { val mappingName = "customMapping" - val projectIRI = INCUNABULA_PROJECT_IRI + val projectIRI = INCUNABULA_PROJECT_IRI val customLabel = "this is a custom mapping with a custom label" val mapping = DefineStandoffMapping.make( mappingName = mappingName, diff --git a/webapi/src/test/scala/org/knora/webapi/other/v1/DrawingsGodsV1E2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/other/v1/DrawingsGodsV1E2ESpec.scala index c7986fbf3e..b004e0e77c 100644 --- a/webapi/src/test/scala/org/knora/webapi/other/v1/DrawingsGodsV1E2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/other/v1/DrawingsGodsV1E2ESpec.scala @@ -65,12 +65,12 @@ class DrawingsGodsV1E2ESpec extends E2ESpec(DrawingsGodsV1E2ESpec.config) with T */ "issue: https://github.com/dhlab-basel/Knora/issues/408" should { - val drawingsOfGodsUserEmail = "ddd1@unil.ch" + val drawingsOfGodsUserEmail = "ddd1@unil.ch" val paroleReligieuseUserEmail = "parole@unil.ch" - val testPass = "test" - val thingIri = new MutableTestIri - val firstValueIri = new MutableTestIri - val secondValueIri = new MutableTestIri + val testPass = "test" + val thingIri = new MutableTestIri + val firstValueIri = new MutableTestIri + val secondValueIri = new MutableTestIri "allow parole-religieuse user to create a resource inside his own project (1a)" in { diff --git a/webapi/src/test/scala/org/knora/webapi/other/v1/DrawingsGodsV1Spec.scala b/webapi/src/test/scala/org/knora/webapi/other/v1/DrawingsGodsV1Spec.scala index bdf847f2fc..91f794807c 100644 --- a/webapi/src/test/scala/org/knora/webapi/other/v1/DrawingsGodsV1Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/other/v1/DrawingsGodsV1Spec.scala @@ -62,14 +62,14 @@ class DrawingsGodsV1Spec extends CoreSpec(DrawingsGodsV1Spec.config) with Triple */ "Using the DrawingsGods project data" should { - val drawingsGodsProjectIri = "http://rdfh.ch/projects/0105" + val drawingsGodsProjectIri = "http://rdfh.ch/projects/0105" val drawingsGodsOntologyIri = "http://www.knora.org/ontology/0105/drawings-gods" - val rootUserIri = "http://rdfh.ch/users/root" - val rootUser = new MutableUserADM - val ddd1UserIri = "http://rdfh.ch/users/drawings-gods-test-ddd1" - val ddd1 = new MutableUserADM - val ddd2UserIri = "http://rdfh.ch/users/drawings-gods-test-ddd2" - val ddd2 = new MutableUserADM + val rootUserIri = "http://rdfh.ch/users/root" + val rootUser = new MutableUserADM + val ddd1UserIri = "http://rdfh.ch/users/drawings-gods-test-ddd1" + val ddd1 = new MutableUserADM + val ddd2UserIri = "http://rdfh.ch/users/drawings-gods-test-ddd2" + val ddd2 = new MutableUserADM "retrieve the drawings gods user's profile" in { responderManager ! UserGetADM( @@ -149,7 +149,7 @@ class DrawingsGodsV1Spec extends CoreSpec(DrawingsGodsV1Spec.config) with Triple "return correct drawings-gods:DrawingPublic / knora-base:hasStillImageFileValue combination permissions string for drawings-gods-test-ddd1 user" in { val drawingPublicResourceClass = s"$drawingsGodsOntologyIri#DrawingPublic" - val hasStillImageFileValue = OntologyConstants.KnoraBase.HasStillImageFileValue + val hasStillImageFileValue = OntologyConstants.KnoraBase.HasStillImageFileValue responderManager ! DefaultObjectAccessPermissionsStringForPropertyGetADM( drawingsGodsProjectIri, drawingPublicResourceClass, @@ -166,7 +166,7 @@ class DrawingsGodsV1Spec extends CoreSpec(DrawingsGodsV1Spec.config) with Triple "return correct drawings-gods:DrawingPrivate / knora-base:hasStillImageFileValue combination permissions string for drawings-gods-test-ddd1 user" in { val drawingPrivateResourceClass = s"$drawingsGodsOntologyIri#DrawingPrivate" - val hasStillImageFileValue = OntologyConstants.KnoraBase.HasStillImageFileValue + val hasStillImageFileValue = OntologyConstants.KnoraBase.HasStillImageFileValue responderManager ! DefaultObjectAccessPermissionsStringForPropertyGetADM( drawingsGodsProjectIri, drawingPrivateResourceClass, @@ -208,7 +208,7 @@ class DrawingsGodsV1Spec extends CoreSpec(DrawingsGodsV1Spec.config) with Triple ) val createResponse = expectMsgType[ResourceCreateResponseV1](timeout) - val resourceIri = createResponse.res_id + val resourceIri = createResponse.res_id responderManager ! ResourceFullGetRequestV1( iri = resourceIri, diff --git a/webapi/src/test/scala/org/knora/webapi/other/v2/LumieresLausanneV2E2ESpec.scala b/webapi/src/test/scala/org/knora/webapi/other/v2/LumieresLausanneV2E2ESpec.scala index caea540372..5fdfe8e6df 100644 --- a/webapi/src/test/scala/org/knora/webapi/other/v2/LumieresLausanneV2E2ESpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/other/v2/LumieresLausanneV2E2ESpec.scala @@ -45,7 +45,7 @@ class LumieresLausanneV2E2ESpec extends E2ESpec(LumieresLausanneV2E2ESpec.config "For project Lumieres Lausanne" should { val gfUserEmail = "gilles.faucherand@unil.ch" - val testPass = "test" + val testPass = "test" "allow user 'gfaucherand' to create a resource using V2 API" in { diff --git a/webapi/src/test/scala/org/knora/webapi/responders/admin/GroupsResponderADMSpec.scala b/webapi/src/test/scala/org/knora/webapi/responders/admin/GroupsResponderADMSpec.scala index 8a82328253..98a4342903 100644 --- a/webapi/src/test/scala/org/knora/webapi/responders/admin/GroupsResponderADMSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/responders/admin/GroupsResponderADMSpec.scala @@ -36,10 +36,10 @@ object GroupsResponderADMSpec { * This spec is used to test the messages received by the [[org.knora.webapi.responders.admin.UsersResponderADM]] actor. */ class GroupsResponderADMSpec extends CoreSpec(GroupsResponderADMSpec.config) with ImplicitSender { - private val timeout = 5.seconds - private val imagesProject = SharedTestDataADM.imagesProject + private val timeout = 5.seconds + private val imagesProject = SharedTestDataADM.imagesProject private val imagesReviewerGroup = SharedTestDataADM.imagesReviewerGroup - private val rootUser = SharedTestDataADM.rootUser + private val rootUser = SharedTestDataADM.rootUser "The GroupsResponder " when { "asked about all groups" should { @@ -104,7 +104,7 @@ class GroupsResponderADMSpec extends CoreSpec(GroupsResponderADMSpec.config) wit ) val received: GroupOperationResponseADM = expectMsgType[GroupOperationResponseADM](timeout) - val newGroupInfo = received.group + val newGroupInfo = received.group newGroupInfo.name should equal("NewGroup") newGroupInfo.descriptions should equal( @@ -161,7 +161,7 @@ class GroupsResponderADMSpec extends CoreSpec(GroupsResponderADMSpec.config) wit ) val received: GroupOperationResponseADM = expectMsgType[GroupOperationResponseADM](timeout) - val updatedGroupInfo = received.group + val updatedGroupInfo = received.group updatedGroupInfo.name should equal("UpdatedGroupName") updatedGroupInfo.descriptions should equal( diff --git a/webapi/src/test/scala/org/knora/webapi/responders/admin/ListsResponderADMSpec.scala b/webapi/src/test/scala/org/knora/webapi/responders/admin/ListsResponderADMSpec.scala index 07d73dc89b..edac044f2a 100644 --- a/webapi/src/test/scala/org/knora/webapi/responders/admin/ListsResponderADMSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/responders/admin/ListsResponderADMSpec.scala @@ -41,7 +41,7 @@ object ListsResponderADMSpec { class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with ImplicitSender { // The default timeout for receiving reply messages from actors. - implicit private val timeout = 5.seconds + implicit private val timeout = 5.seconds private implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance override lazy val rdfDataObjects = List( @@ -156,10 +156,10 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with received.list.children.map(_.sorted) should be(treeListChildNodes.map(_.sorted)) } } - val newListIri = new MutableTestIri - val firstChildIri = new MutableTestIri + val newListIri = new MutableTestIri + val firstChildIri = new MutableTestIri val secondChildIri = new MutableTestIri - val thirdChildIri = new MutableTestIri + val thirdChildIri = new MutableTestIri "used to modify lists" should { "create a list" in { @@ -201,9 +201,9 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with } "create a list with special characters in its labels" in { - val labelWithSpecialCharacter = "Neue \\\"Liste\\\"" + val labelWithSpecialCharacter = "Neue \\\"Liste\\\"" val commentWithSpecialCharacter = "Neue \\\"Kommentar\\\"" - val nameWithSpecialCharacter = "a new \\\"name\\\"" + val nameWithSpecialCharacter = "a new \\\"name\\\"" responderManager ! ListRootNodeCreateRequestADM( createRootNode = ListRootNodeCreatePayloadADM( projectIri = ProjectIRI.make(IMAGES_PROJECT_IRI).fold(e => throw e.head, v => v), @@ -233,7 +233,7 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with givenLabel.value shouldEqual stringFormatter.fromSparqlEncodedString(labelWithSpecialCharacter) givenLabel.language shouldEqual Some("de") - val comments = received.list.listinfo.comments.stringLiterals + val comments = received.list.listinfo.comments.stringLiterals val givenComment = comments.head givenComment.language shouldEqual Some("de") givenComment.value shouldEqual stringFormatter.fromSparqlEncodedString(commentWithSpecialCharacter) @@ -301,7 +301,7 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with } "not update basic list information if name is duplicate" in { - val name = Some(ListName.make("sommer").fold(e => throw e.head, v => v)) + val name = Some(ListName.make("sommer").fold(e => throw e.head, v => v)) val projectIRI = ProjectIRI.make(IMAGES_PROJECT_IRI).fold(e => throw e.head, v => v) responderManager ! NodeInfoChangeRequestADM( listIri = newListIri.get, @@ -344,7 +344,7 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with ) val received: ChildNodeInfoGetResponseADM = expectMsgType[ChildNodeInfoGetResponseADM](timeout) - val nodeInfo = received.nodeinfo + val nodeInfo = received.nodeinfo // check correct node info val childNodeInfo = nodeInfo match { @@ -397,7 +397,7 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with ) val received: ChildNodeInfoGetResponseADM = expectMsgType[ChildNodeInfoGetResponseADM](timeout) - val nodeInfo = received.nodeinfo + val nodeInfo = received.nodeinfo // check correct node info val childNodeInfo = nodeInfo match { @@ -449,7 +449,7 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with ) val received: ChildNodeInfoGetResponseADM = expectMsgType[ChildNodeInfoGetResponseADM](timeout) - val nodeInfo = received.nodeinfo + val nodeInfo = received.nodeinfo // check correct node info val childNodeInfo = nodeInfo match { @@ -558,7 +558,7 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with } "reposition node List014 from position 3 to 1 (shift to right)" in { - val nodeIri = "http://rdfh.ch/lists/0001/notUsedList014" + val nodeIri = "http://rdfh.ch/lists/0001/notUsedList014" val parentIri = "http://rdfh.ch/lists/0001/notUsedList01" responderManager ! NodePositionChangeRequestADM( nodeIri = nodeIri, @@ -572,10 +572,10 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with ) val received: NodePositionChangeResponseADM = expectMsgType[NodePositionChangeResponseADM](timeout) - val parentNode = received.node + val parentNode = received.node parentNode.getNodeId should be(parentIri) - val children = parentNode.getChildren + val children = parentNode.getChildren val isNodeUpdated = children.exists(child => child.id == nodeIri && child.position == 1) isNodeUpdated should be(true) @@ -591,7 +591,7 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with } "reposition node List011 from position 0 to end (shift to left)" in { - val nodeIri = "http://rdfh.ch/lists/0001/notUsedList011" + val nodeIri = "http://rdfh.ch/lists/0001/notUsedList011" val parentIri = "http://rdfh.ch/lists/0001/notUsedList01" responderManager ! NodePositionChangeRequestADM( nodeIri = nodeIri, @@ -604,11 +604,11 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with apiRequestID = UUID.randomUUID ) val received: NodePositionChangeResponseADM = expectMsgType[NodePositionChangeResponseADM](timeout) - val parentNode = received.node + val parentNode = received.node /* check parent node */ parentNode.getNodeId should be(parentIri) - val children = parentNode.getChildren + val children = parentNode.getChildren val isNodeUpdated = children.exists(child => child.id == nodeIri && child.position == 4) isNodeUpdated should be(true) @@ -624,7 +624,7 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with } "reposition node List013 in position 2 of another parent" in { - val nodeIri = "http://rdfh.ch/lists/0001/notUsedList013" + val nodeIri = "http://rdfh.ch/lists/0001/notUsedList013" val newParentIri = "http://rdfh.ch/lists/0001/notUsedList" val oldParentIri = "http://rdfh.ch/lists/0001/notUsedList01" responderManager ! NodePositionChangeRequestADM( @@ -638,7 +638,7 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with apiRequestID = UUID.randomUUID ) val received: NodePositionChangeResponseADM = expectMsgType[NodePositionChangeResponseADM](timeout) - val parentNode = received.node + val parentNode = received.node parentNode.getNodeId should be(newParentIri) /* check children of new parent node */ @@ -675,7 +675,7 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with } "reposition node List015 to the end of another parent's children" in { - val nodeIri = "http://rdfh.ch/lists/0001/notUsedList015" + val nodeIri = "http://rdfh.ch/lists/0001/notUsedList015" val newParentIri = "http://rdfh.ch/lists/0001/notUsedList" val oldParentIri = "http://rdfh.ch/lists/0001/notUsedList01" responderManager ! NodePositionChangeRequestADM( @@ -689,7 +689,7 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with apiRequestID = UUID.randomUUID ) val received: NodePositionChangeResponseADM = expectMsgType[NodePositionChangeResponseADM](timeout) - val parentNode = received.node + val parentNode = received.node parentNode.getNodeId should be(newParentIri) /* check children of new parent node */ @@ -721,7 +721,7 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with } "put List015 back in end of its original parent node" in { - val nodeIri = "http://rdfh.ch/lists/0001/notUsedList015" + val nodeIri = "http://rdfh.ch/lists/0001/notUsedList015" val newParentIri = "http://rdfh.ch/lists/0001/notUsedList01" responderManager ! NodePositionChangeRequestADM( nodeIri = nodeIri, @@ -734,7 +734,7 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with apiRequestID = UUID.randomUUID ) val received: NodePositionChangeResponseADM = expectMsgType[NodePositionChangeResponseADM](timeout) - val parentNode = received.node + val parentNode = received.node parentNode.getNodeId should be(newParentIri) /* check children of new parent node */ @@ -746,7 +746,7 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with } "put List013 back in position 2 of its original parent node" in { - val nodeIri = "http://rdfh.ch/lists/0001/notUsedList013" + val nodeIri = "http://rdfh.ch/lists/0001/notUsedList013" val newParentIri = "http://rdfh.ch/lists/0001/notUsedList01" responderManager ! NodePositionChangeRequestADM( nodeIri = nodeIri, @@ -759,7 +759,7 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with apiRequestID = UUID.randomUUID ) val received: NodePositionChangeResponseADM = expectMsgType[NodePositionChangeResponseADM](timeout) - val parentNode = received.node + val parentNode = received.node parentNode.getNodeId should be(newParentIri) /* check children of new parent node */ @@ -771,7 +771,7 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with } "put List011 back in its original place" in { - val nodeIri = "http://rdfh.ch/lists/0001/notUsedList011" + val nodeIri = "http://rdfh.ch/lists/0001/notUsedList011" val parentIri = "http://rdfh.ch/lists/0001/notUsedList01" responderManager ! NodePositionChangeRequestADM( nodeIri = nodeIri, @@ -784,14 +784,14 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with apiRequestID = UUID.randomUUID ) val received: NodePositionChangeResponseADM = expectMsgType[NodePositionChangeResponseADM](timeout) - val parentNode = received.node + val parentNode = received.node parentNode.getNodeId should be(parentIri) val isNodeUpdated = parentNode.getChildren.exists(child => child.id == nodeIri && child.position == 0) isNodeUpdated should be(true) } "put List014 back in its original position" in { - val nodeIri = "http://rdfh.ch/lists/0001/notUsedList014" + val nodeIri = "http://rdfh.ch/lists/0001/notUsedList014" val parentIri = "http://rdfh.ch/lists/0001/notUsedList01" responderManager ! NodePositionChangeRequestADM( nodeIri = nodeIri, @@ -804,14 +804,14 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with apiRequestID = UUID.randomUUID ) val received: NodePositionChangeResponseADM = expectMsgType[NodePositionChangeResponseADM](timeout) - val parentNode = received.node + val parentNode = received.node parentNode.getNodeId should be(parentIri) val isNodeUpdated = parentNode.getChildren.exists(child => child.id == nodeIri && child.position == 3) isNodeUpdated should be(true) } "reposition node in a position equal to length of new parents children" in { - val nodeIri = "http://rdfh.ch/lists/0001/notUsedList03" + val nodeIri = "http://rdfh.ch/lists/0001/notUsedList03" val parentIri = "http://rdfh.ch/lists/0001/notUsedList01" responderManager ! NodePositionChangeRequestADM( nodeIri = nodeIri, @@ -824,14 +824,14 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with apiRequestID = UUID.randomUUID ) val received: NodePositionChangeResponseADM = expectMsgType[NodePositionChangeResponseADM](timeout) - val parentNode = received.node + val parentNode = received.node parentNode.getNodeId should be(parentIri) val isNodeUpdated = parentNode.getChildren.exists(child => child.id == nodeIri && child.position == 5) isNodeUpdated should be(true) } "reposition List014 in position 0 of its sibling which does not have a child" in { - val nodeIri = "http://rdfh.ch/lists/0001/notUsedList014" + val nodeIri = "http://rdfh.ch/lists/0001/notUsedList014" val parentIri = "http://rdfh.ch/lists/0001/notUsedList015" responderManager ! NodePositionChangeRequestADM( nodeIri = nodeIri, @@ -844,7 +844,7 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with apiRequestID = UUID.randomUUID ) val received: NodePositionChangeResponseADM = expectMsgType[NodePositionChangeResponseADM](timeout) - val parentNode = received.node + val parentNode = received.node parentNode.getNodeId should be(parentIri) val isNodeUpdated = parentNode.getChildren.exists(child => child.id == nodeIri && child.position == 0) isNodeUpdated should be(true) @@ -902,8 +902,8 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with apiRequestID = UUID.randomUUID ) val received: ChildNodeDeleteResponseADM = expectMsgType[ChildNodeDeleteResponseADM](timeout) - val parentNode = received.node - val remainingChildren = parentNode.getChildren + val parentNode = received.node + val remainingChildren = parentNode.getChildren remainingChildren.size should be(4) //Tailing children should be shifted to left remainingChildren.last.position should be(3) @@ -923,8 +923,8 @@ class ListsResponderADMSpec extends CoreSpec(ListsResponderADMSpec.config) with apiRequestID = UUID.randomUUID ) val received: ChildNodeDeleteResponseADM = expectMsgType[ChildNodeDeleteResponseADM](timeout) - val parentNode = received.node - val remainingChildren = parentNode.getChildren + val parentNode = received.node + val remainingChildren = parentNode.getChildren remainingChildren.size should be(1) val firstChild = remainingChildren.head firstChild.id should be("http://rdfh.ch/lists/0001/notUsedList01") diff --git a/webapi/src/test/scala/org/knora/webapi/responders/admin/PermissionsResponderADMSpec.scala b/webapi/src/test/scala/org/knora/webapi/responders/admin/PermissionsResponderADMSpec.scala index 3c55c6106c..bd64f8fcd5 100644 --- a/webapi/src/test/scala/org/knora/webapi/responders/admin/PermissionsResponderADMSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/responders/admin/PermissionsResponderADMSpec.scala @@ -43,7 +43,7 @@ class PermissionsResponderADMSpec with PrivateMethodTester { private val stringFormatter = StringFormatter.getGeneralInstance - private val rootUser = SharedTestDataADM.rootUser + private val rootUser = SharedTestDataADM.rootUser private val multiuserUser = SharedTestDataADM.multiuserUser private val responderUnderTest = new PermissionsResponderADM(responderData) @@ -1068,7 +1068,7 @@ class PermissionsResponderADMSpec apiRequestID = UUID.randomUUID() ) val received: AdministrativePermissionGetResponseADM = expectMsgType[AdministrativePermissionGetResponseADM] - val ap = received.administrativePermission + val ap = received.administrativePermission assert(ap.iri == permissionIri) ap.hasPermissions.size should be(1) val expectedSetOfPermissions = Set(PermissionADM.ProjectAdminAllPermission) @@ -1166,8 +1166,8 @@ class PermissionsResponderADMSpec "not update hasPermissions of a default object access permission, if both name and project code of a permission were missing" in { val permissionIri = "http://rdfh.ch/permissions/0803/003-d1" - val code = 1 - val name = OntologyConstants.KnoraBase.DeletePermission + val code = 1 + val name = OntologyConstants.KnoraBase.DeletePermission val hasPermissions = Set( PermissionADM( name = name, @@ -1192,7 +1192,7 @@ class PermissionsResponderADMSpec "not update hasPermissions of a default object access permission, if an invalid name was given for a permission" in { val permissionIri = "http://rdfh.ch/permissions/0803/003-d1" - val name = "invalidName" + val name = "invalidName" val hasPermissions = Set( PermissionADM( name = name, @@ -1222,7 +1222,7 @@ class PermissionsResponderADMSpec "not update hasPermissions of a default object access permission, if an invalid code was given for a permission" in { val permissionIri = "http://rdfh.ch/permissions/0803/003-d1" - val code = 10 + val code = 10 val hasPermissions = Set( PermissionADM( name = OntologyConstants.KnoraBase.DeletePermission, @@ -1280,7 +1280,7 @@ class PermissionsResponderADMSpec } "ask to update resource class of a permission" should { "throw ForbiddenException for PermissionChangeResourceClassRequestADM if requesting user is not system or project Admin" in { - val permissionIri = "http://rdfh.ch/permissions/0803/003-d2" + val permissionIri = "http://rdfh.ch/permissions/0803/003-d2" val resourceClassIri = SharedOntologyTestDataADM.INCUNABULA_PAGE_RESOURCE_CLASS responderManager ! PermissionChangeResourceClassRequestADM( @@ -1300,7 +1300,7 @@ class PermissionsResponderADMSpec ) } "update resource class of a default object access permission" in { - val permissionIri = "http://rdfh.ch/permissions/0803/003-d2" + val permissionIri = "http://rdfh.ch/permissions/0803/003-d2" val resourceClassIri = SharedOntologyTestDataADM.INCUNABULA_PAGE_RESOURCE_CLASS responderManager ! PermissionChangeResourceClassRequestADM( @@ -1319,7 +1319,7 @@ class PermissionsResponderADMSpec } "update resource class of a default object access permission, and delete group" in { - val permissionIri = "http://rdfh.ch/permissions/0803/003-d1" + val permissionIri = "http://rdfh.ch/permissions/0803/003-d1" val resourceClassIri = SharedOntologyTestDataADM.INCUNABULA_BOOK_RESOURCE_CLASS responderManager ! PermissionChangeResourceClassRequestADM( @@ -1339,7 +1339,7 @@ class PermissionsResponderADMSpec } "not update resource class of an administrative permission" in { - val permissionIri = "http://rdfh.ch/permissions/0803/003-a2" + val permissionIri = "http://rdfh.ch/permissions/0803/003-a2" val resourceClassIri = SharedOntologyTestDataADM.INCUNABULA_BOOK_RESOURCE_CLASS responderManager ! PermissionChangeResourceClassRequestADM( @@ -1363,7 +1363,7 @@ class PermissionsResponderADMSpec "ask to update property of a permission" should { "not update property of an administrative permission" in { val permissionIri = "http://rdfh.ch/permissions/0803/003-a2" - val propertyIri = SharedOntologyTestDataADM.IMAGES_TITEL_PROPERTY + val propertyIri = SharedOntologyTestDataADM.IMAGES_TITEL_PROPERTY responderManager ! PermissionChangePropertyRequestADM( permissionIri = permissionIri, @@ -1384,7 +1384,7 @@ class PermissionsResponderADMSpec } "throw ForbiddenException for PermissionChangePropertyRequestADM if requesting user is not system or project Admin" in { val permissionIri = "http://rdfh.ch/permissions/0000/001-d3" - val propertyIri = OntologyConstants.KnoraBase.TextFileValue + val propertyIri = OntologyConstants.KnoraBase.TextFileValue responderManager ! PermissionChangePropertyRequestADM( permissionIri = permissionIri, @@ -1404,7 +1404,7 @@ class PermissionsResponderADMSpec } "update property of a default object access permission" in { val permissionIri = "http://rdfh.ch/permissions/0000/001-d3" - val propertyIri = OntologyConstants.KnoraBase.TextFileValue + val propertyIri = OntologyConstants.KnoraBase.TextFileValue responderManager ! PermissionChangePropertyRequestADM( permissionIri = permissionIri, @@ -1423,7 +1423,7 @@ class PermissionsResponderADMSpec "update property of a default object access permission, delete group" in { val permissionIri = "http://rdfh.ch/permissions/00FF/d1" - val propertyIri = SharedOntologyTestDataADM.IMAGES_TITEL_PROPERTY + val propertyIri = SharedOntologyTestDataADM.IMAGES_TITEL_PROPERTY responderManager ! PermissionChangePropertyRequestADM( permissionIri = permissionIri, diff --git a/webapi/src/test/scala/org/knora/webapi/responders/admin/ProjectsResponderADMSpec.scala b/webapi/src/test/scala/org/knora/webapi/responders/admin/ProjectsResponderADMSpec.scala index 6f98a1375a..60ed078ac6 100644 --- a/webapi/src/test/scala/org/knora/webapi/responders/admin/ProjectsResponderADMSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/responders/admin/ProjectsResponderADMSpec.scala @@ -40,7 +40,7 @@ object ProjectsResponderADMSpec { class ProjectsResponderADMSpec extends CoreSpec(ProjectsResponderADMSpec.config) with ImplicitSender { private implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - private val timeout = 5.seconds + private val timeout = 5.seconds private val rootUser = SharedTestDataADM.rootUser @@ -310,9 +310,9 @@ class ProjectsResponderADMSpec extends CoreSpec(ProjectsResponderADMSpec.config) "CREATE a project that its info has special characters" in { - val longnameWithSpecialCharacter = "New \\\"Longname\\\"" + val longnameWithSpecialCharacter = "New \\\"Longname\\\"" val descriptionWithSpecialCharacter = "project \\\"description\\\"" - val keywordWithSpecialCharacter = "new \\\"keyword\\\"" + val keywordWithSpecialCharacter = "new \\\"keyword\\\"" responderManager ! ProjectCreateRequestADM( createRequest = ProjectCreatePayloadADM( shortname = Shortname.make("project_with_character").fold(error => throw error.head, value => value), @@ -497,7 +497,7 @@ class ProjectsResponderADMSpec extends CoreSpec(ProjectsResponderADMSpec.config) SharedTestDataADM.rootUser ) val received: ProjectMembersGetResponseADM = expectMsgType[ProjectMembersGetResponseADM](timeout) - val members = received.members + val members = received.members members.size should be(4) @@ -516,7 +516,7 @@ class ProjectsResponderADMSpec extends CoreSpec(ProjectsResponderADMSpec.config) requestingUser = SharedTestDataADM.rootUser ) val received: ProjectMembersGetResponseADM = expectMsgType[ProjectMembersGetResponseADM](timeout) - val members = received.members + val members = received.members members.size should be(4) @@ -535,7 +535,7 @@ class ProjectsResponderADMSpec extends CoreSpec(ProjectsResponderADMSpec.config) requestingUser = SharedTestDataADM.rootUser ) val received: ProjectMembersGetResponseADM = expectMsgType[ProjectMembersGetResponseADM](timeout) - val members = received.members + val members = received.members members.size should be(4) @@ -581,7 +581,7 @@ class ProjectsResponderADMSpec extends CoreSpec(ProjectsResponderADMSpec.config) SharedTestDataADM.rootUser ) val received: ProjectAdminMembersGetResponseADM = expectMsgType[ProjectAdminMembersGetResponseADM](timeout) - val members = received.members + val members = received.members members.size should be(2) @@ -598,7 +598,7 @@ class ProjectsResponderADMSpec extends CoreSpec(ProjectsResponderADMSpec.config) requestingUser = SharedTestDataADM.rootUser ) val received: ProjectAdminMembersGetResponseADM = expectMsgType[ProjectAdminMembersGetResponseADM](timeout) - val members = received.members + val members = received.members members.size should be(2) @@ -615,7 +615,7 @@ class ProjectsResponderADMSpec extends CoreSpec(ProjectsResponderADMSpec.config) requestingUser = SharedTestDataADM.rootUser ) val received: ProjectAdminMembersGetResponseADM = expectMsgType[ProjectAdminMembersGetResponseADM](timeout) - val members = received.members + val members = received.members members.size should be(2) diff --git a/webapi/src/test/scala/org/knora/webapi/responders/v1/ListsResponderV1Spec.scala b/webapi/src/test/scala/org/knora/webapi/responders/v1/ListsResponderV1Spec.scala index 296b5d53f3..8aab1f96d9 100644 --- a/webapi/src/test/scala/org/knora/webapi/responders/v1/ListsResponderV1Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/responders/v1/ListsResponderV1Spec.scala @@ -38,7 +38,7 @@ class ListsResponderV1Spec extends CoreSpec(ListsResponderV1Spec.config) with Im ) // A test UserProfileV1. - private val userProfile = SharedTestDataADM.incunabulaProjectAdminUser + private val userProfile = SharedTestDataADM.incunabulaProjectAdminUser private val userProfileV1 = userProfile.asUserProfileV1 private val hKeywords = HListGetResponseV1( diff --git a/webapi/src/test/scala/org/knora/webapi/responders/v1/OntologyResponderV1Spec.scala b/webapi/src/test/scala/org/knora/webapi/responders/v1/OntologyResponderV1Spec.scala index 53f488d1fb..ae504d1c88 100644 --- a/webapi/src/test/scala/org/knora/webapi/responders/v1/OntologyResponderV1Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/responders/v1/OntologyResponderV1Spec.scala @@ -434,7 +434,7 @@ class OntologyResponderV1Spec extends CoreSpec() with ImplicitSender { ) private def checkResourceTypeResponseV1(received: ResourceTypeResponseV1, expected: ResourceTypeResponseV1): Unit = { - val sortedReceivedProperties = received.restype_info.properties.toList.sortBy(_.id) + val sortedReceivedProperties = received.restype_info.properties.toList.sortBy(_.id) val sortedExpectedProperties: Seq[PropertyDefinitionV1] = expected.restype_info.properties.toList.sortBy(_.id) assert( diff --git a/webapi/src/test/scala/org/knora/webapi/responders/v1/ResourcesResponderV1Spec.scala b/webapi/src/test/scala/org/knora/webapi/responders/v1/ResourcesResponderV1Spec.scala index 3a8e853ad0..835dc7bc0b 100644 --- a/webapi/src/test/scala/org/knora/webapi/responders/v1/ResourcesResponderV1Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/responders/v1/ResourcesResponderV1Spec.scala @@ -734,7 +734,7 @@ class ResourcesResponderV1Spec extends CoreSpec(ResourcesResponderV1Spec.config) propValues.sortBy { valueObject: ResourceCreateValueResponseV1 => val stringValue = valueObject.value.textval.map { case (valType: LiteralValueType.Value, value: String) => value // get string and ignore value type - }.head // each value is represented by a map consisting of only one item (e.g. string -> "book title") + }.head // each value is represented by a map consisting of only one item (e.g. string -> "book title") stringValue } ) @@ -1184,7 +1184,7 @@ class ResourcesResponderV1Spec extends CoreSpec(ResourcesResponderV1Spec.config) val pubdate = DateUtilV1.createJDNValueV1FromDateString("GREGORIAN:2015-12-03") val valuesToBeCreated: Map[IRI, Seq[CreateValueV1WithComment]] = Map( - "http://www.knora.org/ontology/0803/incunabula#title" -> Vector(CreateValueV1WithComment(title1)), + "http://www.knora.org/ontology/0803/incunabula#title" -> Vector(CreateValueV1WithComment(title1)), "http://www.knora.org/ontology/0803/incunabula#pubdate" -> Vector(CreateValueV1WithComment(pubdate)), "http://www.knora.org/ontology/0803/incunabula#citation" -> Vector( CreateValueV1WithComment(citation1, None) @@ -1258,7 +1258,7 @@ class ResourcesResponderV1Spec extends CoreSpec(ResourcesResponderV1Spec.config) ) val valuesToBeCreated: Map[IRI, Seq[CreateValueV1WithComment]] = Map( - "http://www.knora.org/ontology/0803/incunabula#title" -> Vector(CreateValueV1WithComment(title1)), + "http://www.knora.org/ontology/0803/incunabula#title" -> Vector(CreateValueV1WithComment(title1)), "http://www.knora.org/ontology/0803/incunabula#pubdate" -> Vector(CreateValueV1WithComment(pubdateRequest)), "http://www.knora.org/ontology/0803/incunabula#citation" -> Vector( CreateValueV1WithComment(citation4, None), @@ -1270,10 +1270,10 @@ class ResourcesResponderV1Spec extends CoreSpec(ResourcesResponderV1Spec.config) ) val valuesExpected = Map( - "http://www.knora.org/ontology/0803/incunabula#title" -> Vector(title1), - "http://www.knora.org/ontology/0803/incunabula#pubdate" -> Vector(pubdateResponse), + "http://www.knora.org/ontology/0803/incunabula#title" -> Vector(title1), + "http://www.knora.org/ontology/0803/incunabula#pubdate" -> Vector(pubdateResponse), "http://www.knora.org/ontology/0803/incunabula#citation" -> Vector(citation3, citation1, citation4, citation2), - "http://www.knora.org/ontology/0803/incunabula#publoc" -> Vector(publoc) + "http://www.knora.org/ontology/0803/incunabula#publoc" -> Vector(publoc) ) responderManager ! ResourceCreateRequestV1( @@ -1309,9 +1309,9 @@ class ResourcesResponderV1Spec extends CoreSpec(ResourcesResponderV1Spec.config) } "create an incunabula:page with a resource pointer" in { - val recto = TextValueSimpleV1("recto") + val recto = TextValueSimpleV1("recto") val origname = TextValueSimpleV1("Blatt") - val seqnum = IntegerValueV1(1) + val seqnum = IntegerValueV1(1) val fileValue = StillImageFileValueV1( internalMimeType = "image/jp2", @@ -1329,10 +1329,10 @@ class ResourcesResponderV1Spec extends CoreSpec(ResourcesResponderV1Spec.config) "http://www.knora.org/ontology/0803/incunabula#hasRightSideband" -> Vector( CreateValueV1WithComment(LinkUpdateV1(targetResourceIri = "http://rdfh.ch/0803/482a33d65c36")) ), - "http://www.knora.org/ontology/0803/incunabula#pagenum" -> Vector(CreateValueV1WithComment(recto)), - "http://www.knora.org/ontology/0803/incunabula#partOf" -> Vector(CreateValueV1WithComment(LinkUpdateV1(book))), + "http://www.knora.org/ontology/0803/incunabula#pagenum" -> Vector(CreateValueV1WithComment(recto)), + "http://www.knora.org/ontology/0803/incunabula#partOf" -> Vector(CreateValueV1WithComment(LinkUpdateV1(book))), "http://www.knora.org/ontology/0803/incunabula#origname" -> Vector(CreateValueV1WithComment(origname)), - "http://www.knora.org/ontology/0803/incunabula#seqnum" -> Vector(CreateValueV1WithComment(seqnum)) + "http://www.knora.org/ontology/0803/incunabula#seqnum" -> Vector(CreateValueV1WithComment(seqnum)) ) val expected = Map( @@ -1342,11 +1342,11 @@ class ResourcesResponderV1Spec extends CoreSpec(ResourcesResponderV1Spec.config) valueResourceClass = Some("http://www.knora.org/ontology/0803/incunabula#Sideband") ) ), - "http://www.knora.org/ontology/0803/incunabula#pagenum" -> Vector(recto), - "http://www.knora.org/ontology/0803/incunabula#partOf" -> Vector(LinkV1(book)), + "http://www.knora.org/ontology/0803/incunabula#pagenum" -> Vector(recto), + "http://www.knora.org/ontology/0803/incunabula#partOf" -> Vector(LinkV1(book)), "http://www.knora.org/ontology/0803/incunabula#origname" -> Vector(origname), - "http://www.knora.org/ontology/0803/incunabula#seqnum" -> Vector(seqnum), - OntologyConstants.KnoraBase.HasStillImageFileValue -> Vector(fileValue) + "http://www.knora.org/ontology/0803/incunabula#seqnum" -> Vector(seqnum), + OntologyConstants.KnoraBase.HasStillImageFileValue -> Vector(fileValue) ) responderManager ! ResourceCreateRequestV1( @@ -1665,8 +1665,8 @@ class ResourcesResponderV1Spec extends CoreSpec(ResourcesResponderV1Spec.config) ) val response = expectMsgType[GraphDataGetResponseV1](timeout) - val edges = response.edges - val nodes = response.nodes + val edges = response.edges + val nodes = response.nodes edges should contain theSameElementsAs graphForAnythingUser1.edges nodes should contain theSameElementsAs graphForAnythingUser1.nodes @@ -1680,8 +1680,8 @@ class ResourcesResponderV1Spec extends CoreSpec(ResourcesResponderV1Spec.config) ) val response = expectMsgType[GraphDataGetResponseV1](timeout) - val edges = response.edges - val nodes = response.nodes + val edges = response.edges + val nodes = response.nodes edges should contain theSameElementsAs graphForIncunabulaUser.edges nodes should contain theSameElementsAs graphForIncunabulaUser.nodes diff --git a/webapi/src/test/scala/org/knora/webapi/responders/v1/UsersResponderV1Spec.scala b/webapi/src/test/scala/org/knora/webapi/responders/v1/UsersResponderV1Spec.scala index 2a1745bde9..1faeb1d458 100644 --- a/webapi/src/test/scala/org/knora/webapi/responders/v1/UsersResponderV1Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/responders/v1/UsersResponderV1Spec.scala @@ -34,15 +34,15 @@ class UsersResponderV1Spec extends CoreSpec(UsersResponderV1Spec.config) with Im private val timeout = 5.seconds - private val rootUser = SharedTestDataV1.rootUser - private val rootUserIri = rootUser.userData.user_id.get + private val rootUser = SharedTestDataV1.rootUser + private val rootUserIri = rootUser.userData.user_id.get private val rootUserEmail = rootUser.userData.email.get - private val normalUser = SharedTestDataV1.normalUser + private val normalUser = SharedTestDataV1.normalUser private val normalUserIri = normalUser.userData.user_id.get - private val incunabulaUser = SharedTestDataV1.incunabulaProjectAdminUser - private val incunabulaUserIri = incunabulaUser.userData.user_id.get + private val incunabulaUser = SharedTestDataV1.incunabulaProjectAdminUser + private val incunabulaUserIri = incunabulaUser.userData.user_id.get private val incunabulaUserEmail = incunabulaUser.userData.email.get private val imagesProjectIri = SharedTestDataV1.imagesProjectInfo.id diff --git a/webapi/src/test/scala/org/knora/webapi/responders/v1/ValuesResponderV1Spec.scala b/webapi/src/test/scala/org/knora/webapi/responders/v1/ValuesResponderV1Spec.scala index 0f51ec4147..c88278afba 100644 --- a/webapi/src/test/scala/org/knora/webapi/responders/v1/ValuesResponderV1Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/responders/v1/ValuesResponderV1Spec.scala @@ -43,8 +43,8 @@ object ValuesResponderV1Spec { """.stripMargin) private val zeitglöckleinIri = "http://rdfh.ch/0803/c5058f3a" - private val miscResourceIri = "http://rdfh.ch/0803/miscResource" - private val aThingIri = "http://rdfh.ch/0001/a-thing" + private val miscResourceIri = "http://rdfh.ch/0803/miscResource" + private val aThingIri = "http://rdfh.ch/0001/a-thing" private val incunabulaUser = SharedTestDataADM.incunabulaMemberUser @@ -80,17 +80,17 @@ class ValuesResponderV1Spec extends CoreSpec(ValuesResponderV1Spec.config) with private val timeout = 30.seconds // IRIs that are generated by tests and used by subsequent tests. - private val commentIri = new MutableTestIri - private val firstValueIriWithResourceRef = new MutableTestIri + private val commentIri = new MutableTestIri + private val firstValueIriWithResourceRef = new MutableTestIri private val secondValueIriWithResourceRef = new MutableTestIri - private val standoffLinkValueIri = new MutableTestIri - private val currentSeqnumValueIri = new MutableTestIri - private val currentTimeValueIri = new MutableTestIri - private val currentPubdateValueIri = new MutableTestIri - private val linkObjLinkValueIri = new MutableTestIri - private val currentColorValueIri = new MutableTestIri - private val currentGeomValueIri = new MutableTestIri - private val partOfLinkValueIri = new MutableTestIri + private val standoffLinkValueIri = new MutableTestIri + private val currentSeqnumValueIri = new MutableTestIri + private val currentTimeValueIri = new MutableTestIri + private val currentPubdateValueIri = new MutableTestIri + private val linkObjLinkValueIri = new MutableTestIri + private val currentColorValueIri = new MutableTestIri + private val currentGeomValueIri = new MutableTestIri + private val partOfLinkValueIri = new MutableTestIri // a sample set of standoff tags private val sampleStandoff: Vector[StandoffTagV2] = Vector( @@ -1453,7 +1453,7 @@ class ValuesResponderV1Spec extends CoreSpec(ValuesResponderV1Spec.config) with } "create a link between two resources" in { - val resourceIri = "http://rdfh.ch/0803/cb1a74e3e2f6" + val resourceIri = "http://rdfh.ch/0803/cb1a74e3e2f6" val lastModBeforeUpdate = getLastModificationDate(resourceIri) val createValueRequest = CreateValueRequestV1( @@ -1537,8 +1537,8 @@ class ValuesResponderV1Spec extends CoreSpec(ValuesResponderV1Spec.config) with } "change a link" in { - val linkSourceIri = "http://rdfh.ch/0803/cb1a74e3e2f6" - val linkTargetIri = "http://rdfh.ch/0803/21abac2162" + val linkSourceIri = "http://rdfh.ch/0803/cb1a74e3e2f6" + val linkTargetIri = "http://rdfh.ch/0803/21abac2162" val lastModBeforeUpdate = getLastModificationDate(linkSourceIri) val changeValueRequest = ChangeValueRequestV1( @@ -1608,8 +1608,8 @@ class ValuesResponderV1Spec extends CoreSpec(ValuesResponderV1Spec.config) with "delete a link between two resources" in { - val linkSourceIri = "http://rdfh.ch/0803/cb1a74e3e2f6" - val linkTargetIri = "http://rdfh.ch/0803/21abac2162" + val linkSourceIri = "http://rdfh.ch/0803/cb1a74e3e2f6" + val linkTargetIri = "http://rdfh.ch/0803/21abac2162" val lastModBeforeUpdate = getLastModificationDate(linkSourceIri) val comment = "This link is no longer needed" @@ -1712,7 +1712,7 @@ class ValuesResponderV1Spec extends CoreSpec(ValuesResponderV1Spec.config) with } "add a new text value with a comment" in { - val comment = "This is a comment" + val comment = "This is a comment" val metaComment = "This is a metacomment" responderManager ! CreateValueRequestV1( @@ -1947,9 +1947,9 @@ class ValuesResponderV1Spec extends CoreSpec(ValuesResponderV1Spec.config) with } "delete two text values containing the same standoff resource reference" in { - val thingWithTextValues = "http://rdfh.ch/0001/a-thing-with-text-values" - val firstTextValue = "http://rdfh.ch/0001/a-thing-with-text-values/values/1" - val secondTextValue = "http://rdfh.ch/0001/a-thing-with-text-values/values/2" + val thingWithTextValues = "http://rdfh.ch/0001/a-thing-with-text-values" + val firstTextValue = "http://rdfh.ch/0001/a-thing-with-text-values/values/1" + val secondTextValue = "http://rdfh.ch/0001/a-thing-with-text-values/values/2" val lastModBeforeFirstDelete = getLastModificationDate(thingWithTextValues) // Check that the link value has an initial reference count of 2. diff --git a/webapi/src/test/scala/org/knora/webapi/responders/v2/ListsResponderV2Spec.scala b/webapi/src/test/scala/org/knora/webapi/responders/v2/ListsResponderV2Spec.scala index a4ca27347f..16162bc662 100644 --- a/webapi/src/test/scala/org/knora/webapi/responders/v2/ListsResponderV2Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/responders/v2/ListsResponderV2Spec.scala @@ -31,7 +31,7 @@ class ListsResponderV2Spec extends CoreSpec() with ImplicitSender { import ListsResponderV2Spec._ private implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - private val listsResponderV2SpecFullData = new ListsResponderV2SpecFullData + private val listsResponderV2SpecFullData = new ListsResponderV2SpecFullData override lazy val rdfDataObjects = List( RdfDataObject(path = "test_data/all_data/incunabula-data.ttl", name = "http://www.knora.org/data/0803/incunabula"), diff --git a/webapi/src/test/scala/org/knora/webapi/responders/v2/OntologyResponderV2Spec.scala b/webapi/src/test/scala/org/knora/webapi/responders/v2/OntologyResponderV2Spec.scala index 8a0f61e3cd..d7f1805df1 100644 --- a/webapi/src/test/scala/org/knora/webapi/responders/v2/OntologyResponderV2Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/responders/v2/OntologyResponderV2Spec.scala @@ -40,11 +40,11 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { private implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance override lazy val rdfDataObjects: Seq[RdfDataObject] = List(exampleSharedOntology, anythingData, freeTestOntology, freeTestData) - private val imagesUser = SharedTestDataADM.imagesUser01 - private val imagesProjectIri = SharedTestDataADM.IMAGES_PROJECT_IRI.toSmartIri - private val anythingAdminUser = SharedTestDataADM.anythingAdminUser + private val imagesUser = SharedTestDataADM.imagesUser01 + private val imagesProjectIri = SharedTestDataADM.IMAGES_PROJECT_IRI.toSmartIri + private val anythingAdminUser = SharedTestDataADM.anythingAdminUser private val anythingNonAdminUser = SharedTestDataADM.anythingUser1 - private val anythingProjectIri = SharedTestDataADM.ANYTHING_PROJECT_IRI.toSmartIri + private val anythingProjectIri = SharedTestDataADM.ANYTHING_PROJECT_IRI.toSmartIri private val exampleSharedOntology = RdfDataObject( path = "test_data/ontologies/example-box.ttl", name = "http://www.knora.org/ontology/shared/example-box" @@ -56,48 +56,48 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { private val freeTestData = RdfDataObject(path = "test_data/all_data/freetest-data.ttl", name = "http://www.knora.org/data/0001/freetest") // The default timeout for receiving reply messages from actors. - private val timeout = 10.seconds - private val fooIri = new MutableTestIri - private val barIri = new MutableTestIri - private val chairIri = new MutableTestIri - private val ExampleSharedOntologyIri = "http://api.knora.org/ontology/shared/example-box/v2".toSmartIri - private val IncunabulaOntologyIri = "http://0.0.0.0:3333/ontology/0803/incunabula/v2".toSmartIri - private val AnythingOntologyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2".toSmartIri - private val FreeTestOntologyIri = "http://0.0.0.0:3333/ontology/0001/freetest/v2".toSmartIri - private val printErrorMessages = false - private var fooLastModDate: Instant = Instant.now - private var barLastModDate: Instant = Instant.now - private var chairLastModDate: Instant = Instant.now + private val timeout = 10.seconds + private val fooIri = new MutableTestIri + private val barIri = new MutableTestIri + private val chairIri = new MutableTestIri + private val ExampleSharedOntologyIri = "http://api.knora.org/ontology/shared/example-box/v2".toSmartIri + private val IncunabulaOntologyIri = "http://0.0.0.0:3333/ontology/0803/incunabula/v2".toSmartIri + private val AnythingOntologyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2".toSmartIri + private val FreeTestOntologyIri = "http://0.0.0.0:3333/ontology/0001/freetest/v2".toSmartIri + private val printErrorMessages = false + private var fooLastModDate: Instant = Instant.now + private var barLastModDate: Instant = Instant.now + private var chairLastModDate: Instant = Instant.now private var anythingLastModDate: Instant = Instant.parse("2017-12-19T15:23:42.166Z") private var freetestLastModDate: Instant = Instant.parse("2012-12-12T12:12:12.12Z") - val anythingOntology = "http://0.0.0.0:3333/ontology/0001/anything/v2#" - val anythingThing: IRI = anythingOntology + "Thing" - val anythingHasBoolean: IRI = anythingOntology + "hasBoolean" - val anythingHasColor: IRI = anythingOntology + "hasColor" - val anythingHasDate: IRI = anythingOntology + "hasDate" - val anythingHasDecimal: IRI = anythingOntology + "hasDecimal" - val anythingHasGeometry: IRI = anythingOntology + "hasGeometry" - val anythingHasGeoname: IRI = anythingOntology + "hasGeoname" - val anythingHasInteger: IRI = anythingOntology + "hasInteger" - val anythingHasInterval: IRI = anythingOntology + "hasInterval" - val anythingHasListItem: IRI = anythingOntology + "hasListItem" - val anythingHasName: IRI = anythingOntology + "hasName" - val anythingHasOtherListItem: IRI = anythingOntology + "hasOtherListItem" - val anythingHasOtherThing: IRI = anythingOntology + "hasOtherThing" - val anythingHasOtherThingValue: IRI = anythingOntology + "hasOtherThingValue" - val anythingHasRichtext: IRI = anythingOntology + "hasRichtext" - val anythingHasText: IRI = anythingOntology + "hasText" - val anythingHasThingDocument: IRI = anythingOntology + "hasThingDocument" - val anythingHasThingDocumentValue: IRI = anythingOntology + "hasThingDocumentValue" - val anythingHasThingPicture: IRI = anythingOntology + "hasThingPicture" - val anythingHasThingPictureValue: IRI = anythingOntology + "hasThingPictureValue" - val anythingHasTimeStamp: IRI = anythingOntology + "hasTimeStamp" - val anythingHasUri: IRI = anythingOntology + "hasUri" - val anythingIsPartOfOtherThing: IRI = anythingOntology + "isPartOfOtherThing" + val anythingOntology = "http://0.0.0.0:3333/ontology/0001/anything/v2#" + val anythingThing: IRI = anythingOntology + "Thing" + val anythingHasBoolean: IRI = anythingOntology + "hasBoolean" + val anythingHasColor: IRI = anythingOntology + "hasColor" + val anythingHasDate: IRI = anythingOntology + "hasDate" + val anythingHasDecimal: IRI = anythingOntology + "hasDecimal" + val anythingHasGeometry: IRI = anythingOntology + "hasGeometry" + val anythingHasGeoname: IRI = anythingOntology + "hasGeoname" + val anythingHasInteger: IRI = anythingOntology + "hasInteger" + val anythingHasInterval: IRI = anythingOntology + "hasInterval" + val anythingHasListItem: IRI = anythingOntology + "hasListItem" + val anythingHasName: IRI = anythingOntology + "hasName" + val anythingHasOtherListItem: IRI = anythingOntology + "hasOtherListItem" + val anythingHasOtherThing: IRI = anythingOntology + "hasOtherThing" + val anythingHasOtherThingValue: IRI = anythingOntology + "hasOtherThingValue" + val anythingHasRichtext: IRI = anythingOntology + "hasRichtext" + val anythingHasText: IRI = anythingOntology + "hasText" + val anythingHasThingDocument: IRI = anythingOntology + "hasThingDocument" + val anythingHasThingDocumentValue: IRI = anythingOntology + "hasThingDocumentValue" + val anythingHasThingPicture: IRI = anythingOntology + "hasThingPicture" + val anythingHasThingPictureValue: IRI = anythingOntology + "hasThingPictureValue" + val anythingHasTimeStamp: IRI = anythingOntology + "hasTimeStamp" + val anythingHasUri: IRI = anythingOntology + "hasUri" + val anythingIsPartOfOtherThing: IRI = anythingOntology + "isPartOfOtherThing" val anythingIsPartOfOtherThingValue: IRI = anythingOntology + "isPartOfOtherThingValue" - val anythingHasStandoffLinkTo: IRI = "http://api.knora.org/ontology/knora-api/v2#hasStandoffLinkTo" - val anythingHasStandoffLinkToValue: IRI = "http://api.knora.org/ontology/knora-api/v2#hasStandoffLinkToValue" + val anythingHasStandoffLinkTo: IRI = "http://api.knora.org/ontology/knora-api/v2#hasStandoffLinkTo" + val anythingHasStandoffLinkToValue: IRI = "http://api.knora.org/ontology/knora-api/v2#hasStandoffLinkToValue" private def loadInvalidTestData(rdfDataObjs: List[RdfDataObject]): Unit = { storeManager ! ResetRepositoryContent(rdfDataObjs) @@ -198,7 +198,7 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { } "change both the label and the comment of the 'foo' ontology" in { - val aLabel = "a changed label" + val aLabel = "a changed label" val aComment = "a changed comment" responderManager ! ChangeOntologyMetadataRequestV2( @@ -449,9 +449,9 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { cause.isInstanceOf[BadRequestException] should ===(true) val expectedSubjects = Set( - "", // rdf:type anything:Thing - "", // rdf:type anything:BlueThing, a subclass of anything:Thing - "", // a subclass of anything:Thing in another ontology + "", // rdf:type anything:Thing + "", // rdf:type anything:BlueThing, a subclass of anything:Thing + "", // a subclass of anything:Thing in another ontology "" // a subproperty of anything:hasOtherThing in another ontology ) @@ -781,7 +781,7 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { expectMsgPF(timeout) { case msg: ReadOntologyV2 => val externalOntology = msg.toOntologySchema(ApiV2Complex) - val property = externalOntology.properties(propertyIri) + val property = externalOntology.properties(propertyIri) property.entityInfoContent should ===(propertyInfoContent) val metadata = externalOntology.ontologyMetadata val newAnythingLastModDate = metadata.lastModificationDate.getOrElse( @@ -875,7 +875,7 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { expectMsgPF(timeout) { case msg: ReadOntologyV2 => val externalOntology = msg.toOntologySchema(ApiV2Complex) - val property = externalOntology.properties(propertyIri) + val property = externalOntology.properties(propertyIri) assert(property.isLinkProp) assert(!property.isLinkValueProp) externalOntology.properties(propertyIri).entityInfoContent should ===(propertyInfoContent) @@ -999,7 +999,7 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { expectMsgPF(timeout) { case msg: ReadOntologyV2 => val externalOntology = msg.toOntologySchema(ApiV2Complex) - val metadata = externalOntology.ontologyMetadata + val metadata = externalOntology.ontologyMetadata val newFreetestLastModDate = metadata.lastModificationDate.getOrElse( throw AssertionException(s"${metadata.ontologyIri} has no last modification date") ) @@ -1042,7 +1042,7 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { expectMsgPF(timeout) { case msg: ReadOntologyV2 => val externalOntology = msg.toOntologySchema(ApiV2Complex) - val metadata = externalOntology.ontologyMetadata + val metadata = externalOntology.ontologyMetadata val newFreetestLastModDate = metadata.lastModificationDate.getOrElse( throw AssertionException(s"${metadata.ontologyIri} has no last modification date") ) @@ -1096,7 +1096,7 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { expectMsgPF(timeout) { case msg: ReadOntologyV2 => val externalOntology = msg.toOntologySchema(ApiV2Complex) - val property = externalOntology.properties(comicAuthorPropertyIri) + val property = externalOntology.properties(comicAuthorPropertyIri) assert(property.isLinkProp) assert(!property.isLinkValueProp) externalOntology.properties(comicAuthorPropertyIri).entityInfoContent should ===( @@ -1137,7 +1137,7 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { expectMsgPF(timeout) { case msg: ReadOntologyV2 => val comicBookClass = msg.classes("http://www.knora.org/ontology/0001/freetest#ComicBook".toSmartIri) - val linkProperties = comicBookClass.linkProperties + val linkProperties = comicBookClass.linkProperties val linkValueProperties = comicBookClass.linkValueProperties assert( linkProperties.contains( @@ -2513,7 +2513,7 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { "delete the comment of a link property and remove the comment of the link value property as well" in { val linkPropertyIri: SmartIri = FreeTestOntologyIri.makeEntityIri("hasLinkPropertyWithComment") - val linkValueIri: SmartIri = linkPropertyIri.fromLinkPropToLinkValueProp + val linkValueIri: SmartIri = linkPropertyIri.fromLinkPropToLinkValueProp // delete the comment of the link property responderManager ! DeletePropertyCommentRequestV2( @@ -2549,7 +2549,7 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { ) expectMsgPF(timeout) { case msg: ReadOntologyV2 => - val externalOntology: ReadOntologyV2 = msg.toOntologySchema(ApiV2Complex) + val externalOntology: ReadOntologyV2 = msg.toOntologySchema(ApiV2Complex) val linkValueReadPropertyInfo: ReadPropertyInfoV2 = externalOntology.properties(linkValueIri) linkValueReadPropertyInfo.entityInfoContent.predicates.contains( @@ -2777,7 +2777,7 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { expectMsgPF(timeout) { case msg: ReadOntologyV2 => val externalOntology = msg.toOntologySchema(ApiV2Complex) - val metadata = externalOntology.ontologyMetadata + val metadata = externalOntology.ontologyMetadata val newAnythingLastModDate = metadata.lastModificationDate.getOrElse( throw AssertionException(s"${metadata.ontologyIri} has no last modification date") ) @@ -2818,7 +2818,7 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { expectMsgPF(timeout) { case msg: ReadOntologyV2 => val externalOntology = msg.toOntologySchema(ApiV2Complex) - val metadata = externalOntology.ontologyMetadata + val metadata = externalOntology.ontologyMetadata val newAnythingLastModDate = metadata.lastModificationDate.getOrElse( throw AssertionException(s"${metadata.ontologyIri} has no last modification date") ) @@ -3125,7 +3125,7 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { expectMsgPF(timeout) { case msg: ReadOntologyV2 => val externalOntology = msg.toOntologySchema(ApiV2Complex) - val readClassInfo = externalOntology.classes(classIri) + val readClassInfo = externalOntology.classes(classIri) readClassInfo.allBaseClasses should ===(expectedAllBaseClasses) readClassInfo.entityInfoContent should ===(classInfoContent) readClassInfo.inheritedCardinalities.keySet @@ -3246,7 +3246,7 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { expectMsgPF(timeout) { case msg: ReadOntologyV2 => val externalOntology = msg.toOntologySchema(ApiV2Complex) - val readClassInfo = externalOntology.classes(classIri) + val readClassInfo = externalOntology.classes(classIri) readClassInfo.allBaseClasses should ===(expectedAllBaseClasses) readClassInfo.entityInfoContent should ===(classInfoContent) readClassInfo.inheritedCardinalities.keySet @@ -4081,7 +4081,7 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { .get(stringFormatter.toSmartIri(OntologyConstants.SalsahGui.GuiElementProp)) match { case Some(predicateInfo) => val guiElementTypeFromMessage = predicateInfo.objects.head.asInstanceOf[SmartIriLiteralV2] - val guiElementTypeInternal = guiElementTypeFromMessage.toOntologySchema(InternalSchema) + val guiElementTypeInternal = guiElementTypeFromMessage.toOntologySchema(InternalSchema) guiElementTypeFromMessage should equal(guiElementTypeInternal) case None => () } @@ -4338,7 +4338,7 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { expectMsgPF(timeout) { case msg: ReadOntologyV2 => val externalOntology = msg.toOntologySchema(ApiV2Complex) - val metadata = externalOntology.ontologyMetadata + val metadata = externalOntology.ontologyMetadata val newAnythingLastModDate = metadata.lastModificationDate.getOrElse( throw AssertionException(s"${metadata.ontologyIri} has no last modification date") ) @@ -4421,7 +4421,7 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { } "create a link property, anything:hasOtherNothing, and add a cardinality for it to the class anything:Nothing" in { - val classIri = AnythingOntologyIri.makeEntityIri("Nothing") + val classIri = AnythingOntologyIri.makeEntityIri("Nothing") val propertyIri = AnythingOntologyIri.makeEntityIri("hasOtherNothing") val propertyInfoContent = PropertyInfoContentV2( @@ -4466,7 +4466,7 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { expectMsgPF(timeout) { case msg: ReadOntologyV2 => val externalOntology = msg.toOntologySchema(ApiV2Complex) - val metadata = externalOntology.ontologyMetadata + val metadata = externalOntology.ontologyMetadata val newAnythingLastModDate = metadata.lastModificationDate.getOrElse( throw AssertionException(s"${metadata.ontologyIri} has no last modification date") ) @@ -6530,7 +6530,7 @@ class OntologyResponderV2Spec extends CoreSpec() with ImplicitSender { // check if property was created correctly expectMsgPF(timeout) { case msg: ReadOntologyV2 => val externalOntology: ReadOntologyV2 = msg.toOntologySchema(ApiV2Complex) - val property: ReadPropertyInfoV2 = externalOntology.properties(propertyIri) + val property: ReadPropertyInfoV2 = externalOntology.properties(propertyIri) property.entityInfoContent should ===(propertyInfoContent) val metadata: OntologyMetadataV2 = externalOntology.ontologyMetadata val newAnythingLastModDate: Instant = metadata.lastModificationDate.getOrElse( diff --git a/webapi/src/test/scala/org/knora/webapi/responders/v2/ResourcesResponderV2Spec.scala b/webapi/src/test/scala/org/knora/webapi/responders/v2/ResourcesResponderV2Spec.scala index a331c5dae4..de73ee28c9 100644 --- a/webapi/src/test/scala/org/knora/webapi/responders/v2/ResourcesResponderV2Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/responders/v2/ResourcesResponderV2Spec.scala @@ -54,14 +54,14 @@ object ResourcesResponderV2Spec { private val zeitglöckleinIri = "http://rdfh.ch/0803/c5058f3a" - private val aThingIri = "http://rdfh.ch/0001/a-thing" + private val aThingIri = "http://rdfh.ch/0001/a-thing" private var aThingLastModificationDate = Instant.now - private val aThingCreationDate = Instant.parse("2016-03-02T15:05:10Z") + private val aThingCreationDate = Instant.parse("2016-03-02T15:05:10Z") - private val resourceIriToErase = new MutableTestIri - private val firstValueIriToErase = new MutableTestIri - private val secondValueIriToErase = new MutableTestIri - private val standoffTagIrisToErase = collection.mutable.Set.empty[IRI] + private val resourceIriToErase = new MutableTestIri + private val firstValueIriToErase = new MutableTestIri + private val secondValueIriToErase = new MutableTestIri + private val standoffTagIrisToErase = collection.mutable.Set.empty[IRI] private var resourceToEraseLastModificationDate = Instant.now } @@ -398,7 +398,7 @@ class ResourcesResponderV2Spec extends CoreSpec() with ImplicitSender { import ResourcesResponderV2Spec._ private implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - private val resourcesResponderV2SpecFullData = new ResourcesResponderV2SpecFullData + private val resourcesResponderV2SpecFullData = new ResourcesResponderV2SpecFullData private var standardMapping: Option[MappingXMLtoStandoff] = None @@ -795,8 +795,8 @@ class ResourcesResponderV2Spec extends CoreSpec() with ImplicitSender { "return the version history of a resource within a date range" in { val resourceIri = "http://rdfh.ch/0001/thing-with-history" - val startDate = Instant.parse("2019-02-08T15:05:11Z") - val endDate = Instant.parse("2019-02-13T09:05:10Z") + val startDate = Instant.parse("2019-02-08T15:05:11Z") + val endDate = Instant.parse("2019-02-13T09:05:10Z") responderManager ! ResourceVersionHistoryGetRequestV2( resourceIri = resourceIri, @@ -857,8 +857,8 @@ class ResourcesResponderV2Spec extends CoreSpec() with ImplicitSender { ) val response = expectMsgType[GraphDataGetResponseV2](timeout) - val edges = response.edges - val nodes = response.nodes + val edges = response.edges + val nodes = response.nodes edges should contain theSameElementsAs graphTestData.graphForAnythingUser1.edges nodes should contain theSameElementsAs graphTestData.graphForAnythingUser1.nodes @@ -875,8 +875,8 @@ class ResourcesResponderV2Spec extends CoreSpec() with ImplicitSender { ) val response = expectMsgType[GraphDataGetResponseV2](timeout) - val edges = response.edges - val nodes = response.nodes + val edges = response.edges + val nodes = response.nodes edges should contain theSameElementsAs graphTestData.graphForIncunabulaUser.edges nodes should contain theSameElementsAs graphTestData.graphForIncunabulaUser.nodes @@ -1790,8 +1790,8 @@ class ResourcesResponderV2Spec extends CoreSpec() with ImplicitSender { "update a resource's metadata when it doesn't have a knora-base:lastModificationDate" in { val dateTimeStampBeforeUpdate = Instant.now - val newLabel = "new test label" - val newPermissions = "CR knora-admin:Creator|M knora-admin:ProjectMember|V knora-admin:ProjectMember" + val newLabel = "new test label" + val newPermissions = "CR knora-admin:Creator|M knora-admin:ProjectMember|V knora-admin:ProjectMember" val updateRequest = UpdateResourceMetadataRequestV2( resourceIri = aThingIri, @@ -1919,7 +1919,7 @@ class ResourcesResponderV2Spec extends CoreSpec() with ImplicitSender { // Get the resource from the triplestore and check it. val outputResource: ReadResourceV2 = getResource(aThingIri, anythingUserProfile) - val updatedLastModificationDate = outputResource.lastModificationDate.get + val updatedLastModificationDate = outputResource.lastModificationDate.get assert(updatedLastModificationDate == newModificationDate) aThingLastModificationDate = updatedLastModificationDate } @@ -1978,7 +1978,7 @@ class ResourcesResponderV2Spec extends CoreSpec() with ImplicitSender { } "mark a resource as deleted, supplying a custom delete date" in { - val resourceIri = "http://rdfh.ch/0001/5IEswyQFQp2bxXDrOyEfEA" + val resourceIri = "http://rdfh.ch/0001/5IEswyQFQp2bxXDrOyEfEA" val deleteDate: Instant = Instant.now val deleteRequest = DeleteOrEraseResourceRequestV2( @@ -2191,8 +2191,8 @@ class ResourcesResponderV2Spec extends CoreSpec() with ImplicitSender { val resourceIri: IRI = stringFormatter.makeRandomResourceIri(SharedTestDataADM.anythingProject.shortcode) resourceIriToErase.set(resourceIri) val resourceClassIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#Thing".toSmartIri - val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasRichtext".toSmartIri - val standoffTagUUIDsToErase = collection.mutable.Set.empty[UUID] + val propertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasRichtext".toSmartIri + val standoffTagUUIDsToErase = collection.mutable.Set.empty[UUID] val inputValues: Map[SmartIri, Seq[CreateValueInNewResourceV2]] = Map( propertyIri -> Seq( @@ -2224,7 +2224,7 @@ class ResourcesResponderV2Spec extends CoreSpec() with ImplicitSender { ) expectMsgType[ReadResourcesSequenceV2](timeout) - val outputResource: ReadResourceV2 = getResource(resourceIri = resourceIri, requestingUser = anythingUserProfile) + val outputResource: ReadResourceV2 = getResource(resourceIri = resourceIri, requestingUser = anythingUserProfile) val firstTextValue: ReadTextValueV2 = outputResource.values(propertyIri).head.asInstanceOf[ReadTextValueV2] firstValueIriToErase.set(firstTextValue.valueIri) @@ -2257,7 +2257,7 @@ class ResourcesResponderV2Spec extends CoreSpec() with ImplicitSender { secondValueIriToErase.set(updateValueResponse.valueIri) } - val updatedResource = getResource(resourceIri = resourceIri, requestingUser = anythingUserProfile) + val updatedResource = getResource(resourceIri = resourceIri, requestingUser = anythingUserProfile) val secondTextValue: ReadTextValueV2 = updatedResource.values(propertyIri).head.asInstanceOf[ReadTextValueV2] secondValueIriToErase.set(secondTextValue.valueIri) @@ -2300,8 +2300,8 @@ class ResourcesResponderV2Spec extends CoreSpec() with ImplicitSender { "not erase a resource if another resource has a link to it" in { // Create a resource with a link to the resource that is to be deleted. - val resourceWithLinkIri: IRI = stringFormatter.makeRandomResourceIri(SharedTestDataADM.anythingProject.shortcode) - val resourceClassIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#Thing".toSmartIri + val resourceWithLinkIri: IRI = stringFormatter.makeRandomResourceIri(SharedTestDataADM.anythingProject.shortcode) + val resourceClassIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#Thing".toSmartIri val linkValuePropertyIri: SmartIri = "http://0.0.0.0:3333/ontology/0001/anything/v2#hasOtherThingValue".toSmartIri val inputValues: Map[SmartIri, Seq[CreateValueInNewResourceV2]] = Map( @@ -2604,7 +2604,7 @@ class ResourcesResponderV2Spec extends CoreSpec() with ImplicitSender { "create a new value to test create value history event" in { val resourceIri = "http://rdfh.ch/0001/thing-with-history" val newValueIri = "http://rdfh.ch/0001/thing-with-history/values/xZisRC3jPkcplt1hQQdb-A" - val testValue = "a test value" + val testValue = "a test value" // create new value. responderManager ! CreateValueRequestV2( @@ -2652,7 +2652,7 @@ class ResourcesResponderV2Spec extends CoreSpec() with ImplicitSender { } "delete the newly created value to check the delete value event of resource history" in { - val resourceIri = "http://rdfh.ch/0001/thing-with-history" + val resourceIri = "http://rdfh.ch/0001/thing-with-history" val valueToDelete = "http://rdfh.ch/0001/thing-with-history/values/xZisRC3jPkcplt1hQQdb-A" val deleteComment = "delete value test" // delete the new value. diff --git a/webapi/src/test/scala/org/knora/webapi/responders/v2/ResourcesResponseCheckerV2Spec.scala b/webapi/src/test/scala/org/knora/webapi/responders/v2/ResourcesResponseCheckerV2Spec.scala index 90a9d55330..8e63051c90 100644 --- a/webapi/src/test/scala/org/knora/webapi/responders/v2/ResourcesResponseCheckerV2Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/responders/v2/ResourcesResponseCheckerV2Spec.scala @@ -12,7 +12,7 @@ import org.knora.webapi.responders.v2.ResourcesResponseCheckerV2.compareReadReso class ResourcesResponseCheckerV2Spec extends CoreSpec() { private implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - private val resourcesResponderV2SpecFullData = new ResourcesResponderV2SpecFullData + private val resourcesResponderV2SpecFullData = new ResourcesResponderV2SpecFullData private val resourcesResponderCheckerV2SpecFullData = new ResourcesResponseCheckerV2SpecFullData "The ResourcesResponseCheckerV2" should { diff --git a/webapi/src/test/scala/org/knora/webapi/responders/v2/SearchResponderV2Spec.scala b/webapi/src/test/scala/org/knora/webapi/responders/v2/SearchResponderV2Spec.scala index 793f4248a5..6967411b3b 100644 --- a/webapi/src/test/scala/org/knora/webapi/responders/v2/SearchResponderV2Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/responders/v2/SearchResponderV2Spec.scala @@ -38,7 +38,7 @@ class SearchResponderV2Spec extends CoreSpec() with ImplicitSender { RdfDataObject(path = "test_data/all_data/books-data.ttl", name = "http://www.knora.org/data/0001/anything") ) private val searchResponderV2SpecFullData = new SearchResponderV2SpecFullData - private val anythingUserProfile = SharedTestDataADM.anythingUser2 + private val anythingUserProfile = SharedTestDataADM.anythingUser2 // The default timeout for receiving reply messages from actors. private val timeout = 10.seconds diff --git a/webapi/src/test/scala/org/knora/webapi/responders/v2/SearchResponderV2SpecFullData.scala b/webapi/src/test/scala/org/knora/webapi/responders/v2/SearchResponderV2SpecFullData.scala index 45318a32c7..984513cf01 100644 --- a/webapi/src/test/scala/org/knora/webapi/responders/v2/SearchResponderV2SpecFullData.scala +++ b/webapi/src/test/scala/org/knora/webapi/responders/v2/SearchResponderV2SpecFullData.scala @@ -18,10 +18,10 @@ class SearchResponderV2SpecFullData(implicit stringFormatter: StringFormatter) { implicit lazy val system: ActorSystem = ActorSystem("webapi") - val booksBookIri: String = "http://www.knora.org/ontology/0001/books#Book" + val booksBookIri: String = "http://www.knora.org/ontology/0001/books#Book" val booksHasTextType: String = "http://www.knora.org/ontology/0001/books#hasTextType" - val testUser1: String = "http://rdfh.ch/users/9XBCrDV3SRa7kS1WwynB4Q" - val testUser2: String = "http://rdfh.ch/users/BhkfBc3hTeS_IDo-JgXRbQ" + val testUser1: String = "http://rdfh.ch/users/9XBCrDV3SRa7kS1WwynB4Q" + val testUser2: String = "http://rdfh.ch/users/BhkfBc3hTeS_IDo-JgXRbQ" val bookTemplateReadResource: ReadResourceV2 = ReadResourceV2( label = "", resourceIri = "", diff --git a/webapi/src/test/scala/org/knora/webapi/responders/v2/StandoffResponderV2Spec.scala b/webapi/src/test/scala/org/knora/webapi/responders/v2/StandoffResponderV2Spec.scala index 56bdd70250..a10ba13f32 100644 --- a/webapi/src/test/scala/org/knora/webapi/responders/v2/StandoffResponderV2Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/responders/v2/StandoffResponderV2Spec.scala @@ -48,7 +48,7 @@ class StandoffResponderV2Spec extends CoreSpec() with ImplicitSender { "The standoff responder" should { "create a standoff mapping" in { val mappingName = "customMapping" - val mapping = DefineStandoffMapping.make(mappingName) + val mapping = DefineStandoffMapping.make(mappingName) val xmlContent = s""" | hasPageProperties) + + (hasPagePropertyIri -> hasPageProperties) + (hasPageValuePropertyIri -> hasPageValueProperties) val newBooks = previousBooks.copy( ontologyMetadata = previousBooks.ontologyMetadata.copy( diff --git a/webapi/src/test/scala/org/knora/webapi/responders/v2/ontology/DeleteCardinalitiesFromClassSpec.scala b/webapi/src/test/scala/org/knora/webapi/responders/v2/ontology/DeleteCardinalitiesFromClassSpec.scala index 14d94240a4..52e34a533d 100644 --- a/webapi/src/test/scala/org/knora/webapi/responders/v2/ontology/DeleteCardinalitiesFromClassSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/responders/v2/ontology/DeleteCardinalitiesFromClassSpec.scala @@ -52,7 +52,7 @@ class DeleteCardinalitiesFromClassSpec extends IntegrationSpec(TestContainerFuse "DeleteCardinalitiesFromClass" should { "detect that property is in use, when used in a resource" in { val internalPropertyIri = freetestOntologyIri.makeEntityIri("hasText").toOntologySchema(InternalSchema) - val internalClassIri = freetestOntologyIri.makeEntityIri("FreeTest").toOntologySchema(InternalSchema) + val internalClassIri = freetestOntologyIri.makeEntityIri("FreeTest").toOntologySchema(InternalSchema) println(s"internalPropertyIri: $internalPropertyIri") val resF = Cardinalities.isPropertyUsedInResources(settings, fusekiActor, internalClassIri, internalPropertyIri) @@ -61,7 +61,7 @@ class DeleteCardinalitiesFromClassSpec extends IntegrationSpec(TestContainerFuse "detect that property is not in use, when not used in a resource" in { val internalPropertyIri = freetestOntologyIri.makeEntityIri("hasText").toOntologySchema(InternalSchema) - val internalClassIri = freetestOntologyIri.makeEntityIri("FreeTestResourceClass").toOntologySchema(InternalSchema) + val internalClassIri = freetestOntologyIri.makeEntityIri("FreeTestResourceClass").toOntologySchema(InternalSchema) println(s"internalPropertyIri: $internalPropertyIri") val resF = Cardinalities.isPropertyUsedInResources(settings, fusekiActor, internalClassIri, internalPropertyIri) @@ -72,7 +72,7 @@ class DeleteCardinalitiesFromClassSpec extends IntegrationSpec(TestContainerFuse "detect that property is not in use, when not used in a resource of that class (even when used in another class)" in { val internalPropertyIri = freetestOntologyIri.makeEntityIri("hasIntegerProperty").toOntologySchema(InternalSchema) - val internalClassIri = freetestOntologyIri.makeEntityIri("FreeTest").toOntologySchema(InternalSchema) + val internalClassIri = freetestOntologyIri.makeEntityIri("FreeTest").toOntologySchema(InternalSchema) println(s"internalPropertyIri: $internalPropertyIri") val resF = Cardinalities.isPropertyUsedInResources(settings, fusekiActor, internalClassIri, internalPropertyIri) @@ -84,7 +84,7 @@ class DeleteCardinalitiesFromClassSpec extends IntegrationSpec(TestContainerFuse "detect that link property is in use, when used in a resource" in { val anythingOntologyIri = "http://0.0.0.0:3333/ontology/0001/anything/v2".toSmartIri val internalPropertyIri = anythingOntologyIri.makeEntityIri("isPartOfOtherThing").toOntologySchema(InternalSchema) - val internalClassIri = anythingOntologyIri.makeEntityIri("Thing").toOntologySchema(InternalSchema) + val internalClassIri = anythingOntologyIri.makeEntityIri("Thing").toOntologySchema(InternalSchema) println(s"internalPropertyIri: $internalPropertyIri") val resF = Cardinalities.isPropertyUsedInResources(settings, fusekiActor, internalClassIri, internalPropertyIri) @@ -93,7 +93,7 @@ class DeleteCardinalitiesFromClassSpec extends IntegrationSpec(TestContainerFuse "detect that property is in use, when used in a resource of a subclass" in { val internalPropertyIri = freetestOntologyIri.makeEntityIri("hasDecimal").toOntologySchema(InternalSchema) - val internalClassIri = freetestOntologyIri.makeEntityIri("FreeTest").toOntologySchema(InternalSchema) + val internalClassIri = freetestOntologyIri.makeEntityIri("FreeTest").toOntologySchema(InternalSchema) println(s"internalPropertyIri: $internalPropertyIri") val resF = Cardinalities.isPropertyUsedInResources(settings, fusekiActor, internalClassIri, internalPropertyIri) diff --git a/webapi/src/test/scala/org/knora/webapi/routing/AuthenticatorSpec.scala b/webapi/src/test/scala/org/knora/webapi/routing/AuthenticatorSpec.scala index 54dd130962..1c636b7332 100644 --- a/webapi/src/test/scala/org/knora/webapi/routing/AuthenticatorSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/routing/AuthenticatorSpec.scala @@ -23,8 +23,8 @@ import org.scalatest.PrivateMethodTester import scala.concurrent.Future object AuthenticatorSpec { - private val rootUser = SharedTestDataADM.rootUser - private val rootUserEmail = rootUser.email + private val rootUser = SharedTestDataADM.rootUser + private val rootUserEmail = rootUser.email private val rootUserPassword = "test" } @@ -34,7 +34,7 @@ class AuthenticatorSpec extends CoreSpec("AuthenticationTestSystem") with Implic implicit val stringFormatter: StringFormatter = StringFormatter.getGeneralInstance - private val getUserByIdentifier = PrivateMethod[Future[UserADM]](Symbol("getUserByIdentifier")) + private val getUserByIdentifier = PrivateMethod[Future[UserADM]](Symbol("getUserByIdentifier")) private val authenticateCredentialsV2 = PrivateMethod[Future[Boolean]](Symbol("authenticateCredentialsV2")) "During Authentication" when { diff --git a/webapi/src/test/scala/org/knora/webapi/sharedtestdata/SharedOntologyTestDataADM.scala b/webapi/src/test/scala/org/knora/webapi/sharedtestdata/SharedOntologyTestDataADM.scala index f6d8399441..eb29ef7bc0 100644 --- a/webapi/src/test/scala/org/knora/webapi/sharedtestdata/SharedOntologyTestDataADM.scala +++ b/webapi/src/test/scala/org/knora/webapi/sharedtestdata/SharedOntologyTestDataADM.scala @@ -12,60 +12,60 @@ object SharedOntologyTestDataADM { val LocalHost_Ontology = "http://0.0.0.0:3333/ontology" // anything - val ANYTHING_ONTOLOGY_IRI: IRI = OntologyConstants.KnoraInternal.InternalOntologyStart + "/0001/anything" - val ANYTHING_ONTOLOGY_IRI_LocalHost: IRI = LocalHost_Ontology + "/0001/anything/v2" - val ANYTHING_DATA_IRI: IRI = OntologyConstants.NamedGraphs.DataNamedGraphStart + "/0001/anything" + val ANYTHING_ONTOLOGY_IRI: IRI = OntologyConstants.KnoraInternal.InternalOntologyStart + "/0001/anything" + val ANYTHING_ONTOLOGY_IRI_LocalHost: IRI = LocalHost_Ontology + "/0001/anything/v2" + val ANYTHING_DATA_IRI: IRI = OntologyConstants.NamedGraphs.DataNamedGraphStart + "/0001/anything" val ANYTHING_THING_RESOURCE_CLASS_LocalHost: IRI = ANYTHING_ONTOLOGY_IRI_LocalHost + "#" + "Thing" val ANYTHING_HasListItem_PROPERTY_LocalHost: IRI = ANYTHING_ONTOLOGY_IRI_LocalHost + "#" + "hasListItem" - val ANYTHING_HasDate_PROPERTY_LocalHost: IRI = ANYTHING_ONTOLOGY_IRI_LocalHost + "#" + "hasDate" + val ANYTHING_HasDate_PROPERTY_LocalHost: IRI = ANYTHING_ONTOLOGY_IRI_LocalHost + "#" + "hasDate" // freetest - val FREETEST_ONTOLOGY_IRI: IRI = OntologyConstants.KnoraInternal.InternalOntologyStart + "/0001/freetest" + val FREETEST_ONTOLOGY_IRI: IRI = OntologyConstants.KnoraInternal.InternalOntologyStart + "/0001/freetest" val FREETEST_ONTOLOGY_IRI_LocalHost: IRI = LocalHost_Ontology + "/0001/freetest/v2" // minimal - val MINIMAL_ONTOLOGY_IRI: IRI = OntologyConstants.KnoraInternal.InternalOntologyStart + "/0001/minimal" + val MINIMAL_ONTOLOGY_IRI: IRI = OntologyConstants.KnoraInternal.InternalOntologyStart + "/0001/minimal" val MINIMAL_ONTOLOGY_IRI_LocalHost: IRI = LocalHost_Ontology + "/0001/minimal/v2" // images - val IMAGES_ONTOLOGY_IRI: IRI = OntologyConstants.KnoraInternal.InternalOntologyStart + "/00FF/images" - val IMAGES_ONTOLOGY_IRI_LocalHost: IRI = LocalHost_Ontology + "/00FF/images/v2" - val IMAGES_DATA_IRI: IRI = OntologyConstants.NamedGraphs.DataNamedGraphStart + "/00FF/images" - val IMAGES_TITEL_PROPERTY: IRI = IMAGES_ONTOLOGY_IRI + "#" + "titel" - val IMAGES_TITEL_PROPERTY_LocalHost: IRI = IMAGES_ONTOLOGY_IRI_LocalHost + "#" + "titel" - val IMAGES_BILD_RESOURCE_CLASS: IRI = IMAGES_ONTOLOGY_IRI + "#" + "bild" + val IMAGES_ONTOLOGY_IRI: IRI = OntologyConstants.KnoraInternal.InternalOntologyStart + "/00FF/images" + val IMAGES_ONTOLOGY_IRI_LocalHost: IRI = LocalHost_Ontology + "/00FF/images/v2" + val IMAGES_DATA_IRI: IRI = OntologyConstants.NamedGraphs.DataNamedGraphStart + "/00FF/images" + val IMAGES_TITEL_PROPERTY: IRI = IMAGES_ONTOLOGY_IRI + "#" + "titel" + val IMAGES_TITEL_PROPERTY_LocalHost: IRI = IMAGES_ONTOLOGY_IRI_LocalHost + "#" + "titel" + val IMAGES_BILD_RESOURCE_CLASS: IRI = IMAGES_ONTOLOGY_IRI + "#" + "bild" val IMAGES_BILD_RESOURCE_CLASS_LocalHost: IRI = IMAGES_ONTOLOGY_IRI_LocalHost + "#" + "bild" // beol - val BEOL_ONTOLOGY_IRI: IRI = OntologyConstants.KnoraInternal.InternalOntologyStart + "/0801/beol" + val BEOL_ONTOLOGY_IRI: IRI = OntologyConstants.KnoraInternal.InternalOntologyStart + "/0801/beol" val BEOL_ONTOLOGY_IRI_LocalHost: IRI = LocalHost_Ontology + "/0801/beol/v2" - val BEOL_DATA_IRI: IRI = OntologyConstants.NamedGraphs.DataNamedGraphStart + "/0801/beol" + val BEOL_DATA_IRI: IRI = OntologyConstants.NamedGraphs.DataNamedGraphStart + "/0801/beol" // biblio - val BIBLIO_ONTOLOGY_IRI: IRI = OntologyConstants.KnoraInternal.InternalOntologyStart + "/0801/biblio" + val BIBLIO_ONTOLOGY_IRI: IRI = OntologyConstants.KnoraInternal.InternalOntologyStart + "/0801/biblio" val BIBLIO_ONTOLOGY_IRI_LocalHost: IRI = LocalHost_Ontology + "/0801/biblio/v2" - val BIBLIO_DATA_IRI: IRI = OntologyConstants.NamedGraphs.DataNamedGraphStart + "/0801/biblio" + val BIBLIO_DATA_IRI: IRI = OntologyConstants.NamedGraphs.DataNamedGraphStart + "/0801/biblio" // incunabula - val INCUNABULA_ONTOLOGY_IRI: IRI = OntologyConstants.KnoraInternal.InternalOntologyStart + "/0803/incunabula" - val INCUNABULA_ONTOLOGY_IRI_LocalHost: IRI = LocalHost_Ontology + "/0803/incunabula/v2" - val INCUNABULA_DATA_IRI: IRI = OntologyConstants.NamedGraphs.DataNamedGraphStart + "/0803/incunabula" - val INCUNABULA_BOOK_RESOURCE_CLASS: IRI = INCUNABULA_ONTOLOGY_IRI + "#" + "book" + val INCUNABULA_ONTOLOGY_IRI: IRI = OntologyConstants.KnoraInternal.InternalOntologyStart + "/0803/incunabula" + val INCUNABULA_ONTOLOGY_IRI_LocalHost: IRI = LocalHost_Ontology + "/0803/incunabula/v2" + val INCUNABULA_DATA_IRI: IRI = OntologyConstants.NamedGraphs.DataNamedGraphStart + "/0803/incunabula" + val INCUNABULA_BOOK_RESOURCE_CLASS: IRI = INCUNABULA_ONTOLOGY_IRI + "#" + "book" val INCUNABULA_BOOK_RESOURCE_CLASS_LocalHost: IRI = INCUNABULA_ONTOLOGY_IRI_LocalHost + "#" + "book" - val INCUNABULA_PAGE_RESOURCE_CLASS: IRI = INCUNABULA_ONTOLOGY_IRI + "#" + "page" + val INCUNABULA_PAGE_RESOURCE_CLASS: IRI = INCUNABULA_ONTOLOGY_IRI + "#" + "page" val INCUNABULA_PAGE_RESOURCE_CLASS_LocalHost: IRI = INCUNABULA_ONTOLOGY_IRI_LocalHost + "#" + "page" - val INCUNABULA_PartOf_Property: IRI = INCUNABULA_ONTOLOGY_IRI + "#" + "partOfValue" - val INCUNABULA_PartOf_Property_LocalHost: IRI = INCUNABULA_ONTOLOGY_IRI_LocalHost + "#" + "partOfValue" + val INCUNABULA_PartOf_Property: IRI = INCUNABULA_ONTOLOGY_IRI + "#" + "partOfValue" + val INCUNABULA_PartOf_Property_LocalHost: IRI = INCUNABULA_ONTOLOGY_IRI_LocalHost + "#" + "partOfValue" // dokubib - val DOKUBIB_ONTOLOGY_IRI: IRI = OntologyConstants.KnoraInternal.InternalOntologyStart + "/0804/dokubib" + val DOKUBIB_ONTOLOGY_IRI: IRI = OntologyConstants.KnoraInternal.InternalOntologyStart + "/0804/dokubib" val DOKUBIB_ONTOLOGY_IRI_LocalHost: IRI = LocalHost_Ontology + "/0804/dokubib/v2" - val DOKUBIB_DATA_IRI: IRI = OntologyConstants.NamedGraphs.DataNamedGraphStart + "/0804/dokubib" + val DOKUBIB_DATA_IRI: IRI = OntologyConstants.NamedGraphs.DataNamedGraphStart + "/0804/dokubib" // webern - val WEBERN_ONTOLOGY_IRI: IRI = OntologyConstants.KnoraInternal.InternalOntologyStart + "/0806/webern" + val WEBERN_ONTOLOGY_IRI: IRI = OntologyConstants.KnoraInternal.InternalOntologyStart + "/0806/webern" val WEBERN_ONTOLOGY_IRI_LocalHost: IRI = LocalHost_Ontology + "/0806/webern/v2" - val WEBERN_DATA_IRI: IRI = OntologyConstants.NamedGraphs.DataNamedGraphStart + "/0806/webern" + val WEBERN_DATA_IRI: IRI = OntologyConstants.NamedGraphs.DataNamedGraphStart + "/0806/webern" //foo ontology val FOO_ONTOLOGY_IRI_LocalHost: IRI = LocalHost_Ontology + "/00FF/foo/v2" diff --git a/webapi/src/test/scala/org/knora/webapi/sharedtestdata/SharedTestDataADM.scala b/webapi/src/test/scala/org/knora/webapi/sharedtestdata/SharedTestDataADM.scala index efd4796029..9a5ec7f63e 100644 --- a/webapi/src/test/scala/org/knora/webapi/sharedtestdata/SharedTestDataADM.scala +++ b/webapi/src/test/scala/org/knora/webapi/sharedtestdata/SharedTestDataADM.scala @@ -477,14 +477,14 @@ object SharedTestDataADM { */ val ANYTHING_PROJECT_IRI = "http://rdfh.ch/projects/0001" - val customResourceIRI: IRI = "http://rdfh.ch/0001/rYAMw7wSTbGw3boYHefByg" + val customResourceIRI: IRI = "http://rdfh.ch/0001/rYAMw7wSTbGw3boYHefByg" val customResourceIRI_resourceWithValues: IRI = "http://rdfh.ch/0001/4PnSvolsTEa86KJ2EG76SQ" val customValueIRI_withResourceIriAndValueIRIAndValueUUID: IRI = "http://rdfh.ch/0001/5zCt1EMJKezFUOW_RCB0Gw/values/fdqCOaqT6dP19pWI84X1XQ" - val customValueUUID = "fdqCOaqT6dP19pWI84X1XQ" - val customValueIRI: IRI = "http://rdfh.ch/0001/5zCt1EMJKezFUOW_RCB0Gw/values/tdWAtnWK2qUC6tr4uQLAHA" + val customValueUUID = "fdqCOaqT6dP19pWI84X1XQ" + val customValueIRI: IRI = "http://rdfh.ch/0001/5zCt1EMJKezFUOW_RCB0Gw/values/tdWAtnWK2qUC6tr4uQLAHA" val customResourceCreationDate: Instant = Instant.parse("2019-01-09T15:45:54.502951Z") - val customValueCreationDate: Instant = Instant.parse("2020-06-09T17:04:54.502951Z") + val customValueCreationDate: Instant = Instant.parse("2020-06-09T17:04:54.502951Z") val customListIRI: IRI = "http://rdfh.ch/lists/0001/qq54wdGKR0S5zsbR5-9wtg" diff --git a/webapi/src/test/scala/org/knora/webapi/store/iiif/MockSipiConnector.scala b/webapi/src/test/scala/org/knora/webapi/store/iiif/MockSipiConnector.scala index 018b99b51f..e8dfc7fa8f 100644 --- a/webapi/src/test/scala/org/knora/webapi/store/iiif/MockSipiConnector.scala +++ b/webapi/src/test/scala/org/knora/webapi/store/iiif/MockSipiConnector.scala @@ -34,7 +34,7 @@ object MockSipiConnector { */ class MockSipiConnector extends Actor with ActorLogging { - implicit val system: ActorSystem = context.system + implicit val system: ActorSystem = context.system implicit val executionContext: ExecutionContext = system.dispatchers.lookup(KnoraDispatchers.KnoraActorDispatcher) def receive = { diff --git a/webapi/src/test/scala/org/knora/webapi/store/triplestore/AllTriplestoreSpec.scala b/webapi/src/test/scala/org/knora/webapi/store/triplestore/AllTriplestoreSpec.scala index b29be7f695..352e4d1466 100644 --- a/webapi/src/test/scala/org/knora/webapi/store/triplestore/AllTriplestoreSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/store/triplestore/AllTriplestoreSpec.scala @@ -45,7 +45,7 @@ class AllTriplestoreSpec extends CoreSpec(AllTriplestoreSpec.config) with Implic ) val countTriplesQuery: String = - """ + """ SELECT (COUNT(*) AS ?no) WHERE { @@ -147,8 +147,8 @@ class AllTriplestoreSpec extends CoreSpec(AllTriplestoreSpec.config) with Implic } """ - var afterLoadCount: Int = -1 - var afterChangeCount: Int = -1 + var afterLoadCount: Int = -1 + var afterChangeCount: Int = -1 var afterChangeRevertCount: Int = -1 /* diff --git a/webapi/src/test/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1307Spec.scala b/webapi/src/test/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1307Spec.scala index efaa281fb5..7e33f2518c 100644 --- a/webapi/src/test/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1307Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR1307Spec.scala @@ -37,7 +37,7 @@ class UpgradePluginPR1307Spec extends UpgradePluginSpec { val expectedResult1: SparqlSelectResultBody = expectedResult( Seq( Map( - "s" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ", + "s" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ", "maxStartIndex" -> "7" ) ) @@ -96,42 +96,42 @@ class UpgradePluginPR1307Spec extends UpgradePluginSpec { Seq( Map( "startIndex" -> "0", - "tag" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/0" + "tag" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/0" ), Map( - "startIndex" -> "1", + "startIndex" -> "1", "startParent" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/0", - "tag" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/1" + "tag" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/1" ), Map( - "startIndex" -> "2", + "startIndex" -> "2", "startParent" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/1", - "tag" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/2" + "tag" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/2" ), Map( - "startIndex" -> "3", + "startIndex" -> "3", "startParent" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/1", - "tag" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/3" + "tag" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/3" ), Map( - "startIndex" -> "4", + "startIndex" -> "4", "startParent" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/1", - "tag" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/4" + "tag" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/4" ), Map( - "startIndex" -> "5", + "startIndex" -> "5", "startParent" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/1", - "tag" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/5" + "tag" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/5" ), Map( - "startIndex" -> "6", + "startIndex" -> "6", "startParent" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/1", - "tag" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/6" + "tag" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/6" ), Map( - "startIndex" -> "7", + "startIndex" -> "7", "startParent" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/1", - "tag" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/7" + "tag" -> "http://rdfh.ch/0001/qN1igiDRSAemBBktbRHn6g/values/xyUIf8QHS5aFrlt7Q4F1FQ/standoff/7" ) ) ) diff --git a/webapi/src/test/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR2018Spec.scala b/webapi/src/test/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR2018Spec.scala index 7a1022f7ef..783dc68135 100644 --- a/webapi/src/test/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR2018Spec.scala +++ b/webapi/src/test/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginPR2018Spec.scala @@ -12,7 +12,7 @@ class UpgradePluginPR2018Spec extends UpgradePluginSpec with LazyLogging { "Upgrade plugin PR2018" should { "add lastModificationDate to ontology not attached to SystemProject" in { val model: RdfModel = trigFileToModel("../test_data/upgrade/pr2018.trig") - val plugin = new UpgradePluginPR2018(defaultFeatureFactoryConfig, logger) + val plugin = new UpgradePluginPR2018(defaultFeatureFactoryConfig, logger) plugin.transform(model) val repository: RdfRepository = model.asRepository diff --git a/webapi/src/test/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginSpec.scala b/webapi/src/test/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginSpec.scala index 494aa3b02f..3637be7977 100644 --- a/webapi/src/test/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/store/triplestore/upgrade/plugins/UpgradePluginSpec.scala @@ -24,7 +24,7 @@ abstract class UpgradePluginSpec extends CoreSpec() { * @return an [[RdfModel]]. */ def trigFileToModel(path: String): RdfModel = { - val fileInputStream = new BufferedInputStream(new FileInputStream(path)) + val fileInputStream = new BufferedInputStream(new FileInputStream(path)) val rdfModel: RdfModel = rdfFormatUtil.inputStreamToRdfModel(inputStream = fileInputStream, rdfFormat = TriG) fileInputStream.close() rdfModel diff --git a/webapi/src/test/scala/org/knora/webapi/util/ApacheLuceneSupportSpec.scala b/webapi/src/test/scala/org/knora/webapi/util/ApacheLuceneSupportSpec.scala index d9c5d22ee7..f423bf2076 100644 --- a/webapi/src/test/scala/org/knora/webapi/util/ApacheLuceneSupportSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/util/ApacheLuceneSupportSpec.scala @@ -13,7 +13,7 @@ class ApacheLuceneSupportSpec extends CoreSpec() { "leave a Lucene query unchanged" in { - val searchString = "Reise Land" + val searchString = "Reise Land" val searchExpression: String = ApacheLuceneSupport.LuceneQueryString(searchString).getQueryString assert(searchExpression == "Reise Land") @@ -21,7 +21,7 @@ class ApacheLuceneSupportSpec extends CoreSpec() { "leave a Lucene query unchanged (2)" in { - val searchString = "Reise ins Land" + val searchString = "Reise ins Land" val searchExpression: String = ApacheLuceneSupport.LuceneQueryString(searchString).getQueryString assert(searchExpression == "Reise ins Land") @@ -29,7 +29,7 @@ class ApacheLuceneSupportSpec extends CoreSpec() { "leave a Lucene query containing phrases and terms unchanged" in { - val searchString = "\"Leonhard Euler\" Bernoulli" + val searchString = "\"Leonhard Euler\" Bernoulli" val searchExpression: String = ApacheLuceneSupport.LuceneQueryString(searchString).getQueryString assert(searchExpression == "\"Leonhard Euler\" Bernoulli") @@ -38,7 +38,7 @@ class ApacheLuceneSupportSpec extends CoreSpec() { "leave a Lucene query containing two phrases and one term unchanged" in { - val searchString = "\"Leonhard Euler\" \"Daniel Bernoulli\" formula" + val searchString = "\"Leonhard Euler\" \"Daniel Bernoulli\" formula" val searchExpression: String = ApacheLuceneSupport.LuceneQueryString(searchString).getQueryString assert(searchExpression == "\"Leonhard Euler\" \"Daniel Bernoulli\" formula") @@ -47,7 +47,7 @@ class ApacheLuceneSupportSpec extends CoreSpec() { "leave a Lucene query containing two phrases and two terms unchanged" in { - val searchString = "\"Leonhard Euler\" \"Daniel Bernoulli\" formula geometria" + val searchString = "\"Leonhard Euler\" \"Daniel Bernoulli\" formula geometria" val searchExpression: String = ApacheLuceneSupport.LuceneQueryString(searchString).getQueryString assert(searchExpression == "\"Leonhard Euler\" \"Daniel Bernoulli\" formula geometria") @@ -56,7 +56,7 @@ class ApacheLuceneSupportSpec extends CoreSpec() { "get terms contained in a Lucene query" in { - val searchString = "Reise Land" + val searchString = "Reise Land" val singleTerms: Seq[String] = ApacheLuceneSupport.LuceneQueryString(searchString).getSingleTerms assert(singleTerms.size === 2) @@ -65,7 +65,7 @@ class ApacheLuceneSupportSpec extends CoreSpec() { "handle one phrase correctly" in { - val searchString = "\"Leonhard Euler\"" + val searchString = "\"Leonhard Euler\"" val searchExpression: String = ApacheLuceneSupport.LuceneQueryString(searchString).getQueryString assert(searchExpression == "\"Leonhard Euler\"") diff --git a/webapi/src/test/scala/org/knora/webapi/util/Base64UrlCheckDigitSpec.scala b/webapi/src/test/scala/org/knora/webapi/util/Base64UrlCheckDigitSpec.scala index b1b4fd3a66..5f437c6785 100644 --- a/webapi/src/test/scala/org/knora/webapi/util/Base64UrlCheckDigitSpec.scala +++ b/webapi/src/test/scala/org/knora/webapi/util/Base64UrlCheckDigitSpec.scala @@ -11,8 +11,8 @@ import org.knora.webapi.CoreSpec * Tests [[Base64UrlCheckDigit]]. */ class Base64UrlCheckDigitSpec extends CoreSpec { - private val base64UrlCheckDigit = new Base64UrlCheckDigit - private val correctResourceID = "cmfk1DMHRBiR4-_6HXpEFA" + private val base64UrlCheckDigit = new Base64UrlCheckDigit + private val correctResourceID = "cmfk1DMHRBiR4-_6HXpEFA" private val correctResourceIDCheckDigit = "n" "Base64UrlCheckDigit" should { diff --git a/webapi/src/test/scala/org/knora/webapi/util/MutableTestIri.scala b/webapi/src/test/scala/org/knora/webapi/util/MutableTestIri.scala index 801fb1e97c..6fe57c9bf4 100644 --- a/webapi/src/test/scala/org/knora/webapi/util/MutableTestIri.scala +++ b/webapi/src/test/scala/org/knora/webapi/util/MutableTestIri.scala @@ -12,7 +12,7 @@ import org.knora.webapi.messages.StringFormatter * Holds an optional, mutable IRI for use in tests. */ class MutableTestIri { - private val stringFormatter = StringFormatter.getGeneralInstance + private val stringFormatter = StringFormatter.getGeneralInstance private var maybeIri: Option[IRI] = None /** diff --git a/webapi/src/test/scala/org/knora/webapi/util/StartupUtils.scala b/webapi/src/test/scala/org/knora/webapi/util/StartupUtils.scala index e3f816dc44..d9be93bf9a 100644 --- a/webapi/src/test/scala/org/knora/webapi/util/StartupUtils.scala +++ b/webapi/src/test/scala/org/knora/webapi/util/StartupUtils.scala @@ -29,7 +29,7 @@ trait StartupUtils extends LazyLogging { def applicationStateRunning(): Unit = { implicit val timeout: Timeout = Timeout(5.second) - val state: AppState = Await.result(appActor ? GetAppState(), timeout.duration).asInstanceOf[AppState] + val state: AppState = Await.result(appActor ? GetAppState(), timeout.duration).asInstanceOf[AppState] if (state != AppStates.Running) { // not in running state