From 96930a99eb2179d068c6b9321568cd65f2f693cc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Marek=20Such=C3=A1nek?= Date: Fri, 24 Nov 2023 14:26:53 +0100 Subject: [PATCH] Migrate to PostgreSQL --- .github/workflows/build.yml | 37 +- .gitignore | 3 +- pom.xml | 59 +-- .../controller/apikey/ApiKeyController.java | 9 +- .../controller/config/ConfigController.java | 6 +- .../dashboard/DashboardController.java | 11 +- .../exception/ExceptionControllerAdvice.java | 10 + .../form/FormAutocompleteController.java | 6 +- .../index/IndexAdminController.java | 23 +- .../index/IndexEntryController.java | 31 +- .../controller/index/IndexPingController.java | 19 +- .../index/IndexSettingsController.java | 6 +- .../api/controller/label/LabelController.java | 7 +- .../membership/MembershipController.java | 6 +- .../metadata/GenericController.java | 46 +- .../metadata/GenericMemberController.java | 21 +- .../metadata/GenericMetaController.java | 29 +- .../controller/profile/ProfileController.java | 14 +- .../api/controller/reset/ResetController.java | 6 +- .../ResourceDefinitionController.java | 13 +- .../schema/MetadataSchemaController.java | 30 +- .../controller/search/SearchController.java | 6 +- .../search/SearchSavedQueryController.java | 18 +- .../controller/settings/SettingsDefaults.java | 79 +++ .../api/controller/token/TokenController.java | 6 +- .../api/controller/user/UserController.java | 19 +- .../api/dto/apikey/ApiKeyDTO.java | 5 +- .../api/dto/index/entry/IndexEntryDTO.java | 4 +- .../dto/index/entry/IndexEntryDetailDTO.java | 3 +- .../api/dto/index/event/EventDTO.java | 4 +- .../dto/index/webhook/WebhookPayloadDTO.java | 4 +- .../api/dto/membership/MembershipDTO.java | 3 +- .../resource/ResourceDefinitionChangeDTO.java | 18 +- .../resource/ResourceDefinitionChildDTO.java | 50 ++ .../ResourceDefinitionChildListViewDTO.java} | 18 +- ...rceDefinitionChildListViewMetadataDTO.java | 44 ++ .../dto/resource/ResourceDefinitionDTO.java | 17 +- .../resource/ResourceDefinitionLinkDTO.java} | 15 +- .../dto/schema/MetadataSchemaChangeDTO.java | 3 +- .../api/dto/schema/MetadataSchemaDTO.java | 7 +- .../dto/schema/MetadataSchemaDraftDTO.java | 5 +- .../MetadataSchemaPreviewRequestDTO.java | 3 +- .../dto/schema/MetadataSchemaVersionDTO.java | 13 +- .../api/dto/search/SearchSavedQueryDTO.java | 3 +- .../api/dto/settings/SettingsDTO.java | 3 +- .../dto/settings/SettingsMetricDTO.java} | 16 +- .../api/dto/settings/SettingsUpdateDTO.java | 3 +- .../api/dto/user/UserChangeDTO.java | 6 +- .../api/dto/user/UserCreateDTO.java | 6 +- .../fairdatapoint/api/dto/user/UserDTO.java | 4 +- .../api/dto/user/UserSimpleDTO.java | 4 +- .../api/filter/FilterConfigurer.java | 12 +- .../api/filter/JwtTokenFilter.java | 12 +- .../api/filter/LoggingFilter.java | 6 +- .../dtls/fairdatapoint/config/AclConfig.java | 63 ++- .../DatabaseConfig.java} | 49 +- .../fairdatapoint/config/MongoConfig.java | 77 --- .../config/RepositoryMigrationConfig.java | 2 - .../repository/ApiKeyRepository.java | 15 +- .../repository/IndexEntryRepository.java | 47 +- .../repository/IndexEventRepository.java} | 25 +- .../repository/IndexSettingsRepository.java | 11 +- .../db/repository/IndexWebhookRepository.java | 31 ++ .../MembershipPermissionRepository.java | 31 ++ .../repository/MembershipRepository.java | 13 +- .../MetadataSchemaExtensionRepository.java | 68 +++ .../repository/MetadataSchemaRepository.java | 39 +- .../MetadataSchemaUsageRepository.java | 59 +++ .../MetadataSchemaVersionRepository.java | 106 ++++ ...rceDefinitionChildMetadataRepository.java} | 19 +- .../ResourceDefinitionChildRepository.java | 49 ++ .../ResourceDefinitionLinkRepository.java | 31 ++ .../ResourceDefinitionRepository.java | 17 +- .../SearchSavedQueryRepository.java | 13 +- .../SettingsAutocompleteSourceRepository.java | 31 ++ .../repository/SettingsMetricRepository.java | 31 ++ .../repository/SettingsRepository.java | 11 +- .../SettingsSearchFilterItemRepository.java | 31 ++ .../SettingsSearchFilterRepository.java} | 23 +- .../repository/UserAccountRepository.java} | 16 +- .../repository/base/BaseRepository.java} | 11 +- .../development/MigrationRunner.java | 104 ---- .../development/apikey/ApiKeyMigration.java | 46 -- .../apikey/data/ApiKeyFixtures.java | 60 --- .../index/entry/IndexEntryMigration.java | 51 -- .../index/entry/data/IndexEntryFixtures.java | 191 ------- .../index/event/EventMigration.java | 39 -- .../membership/MembershipMigration.java | 46 -- .../membership/data/MembershipFixtures.java | 68 --- .../resource/ResourceDefinitionMigration.java | 64 --- .../data/ResourceDefinitionFixtures.java | 121 ----- .../schema/MetadataSchemaMigration.java | 51 -- .../schema/data/MetadataSchemaFixtures.java | 271 ---------- .../search/SearchSavedQueryFixtures.java | 96 ---- .../settings/data/SettingsFixtures.java | 113 ----- .../development/user/UserMigration.java | 47 -- .../development/user/data/UserFixtures.java | 92 ---- .../production/Migration_0001_Init.java | 110 ---- .../Migration_0002_CustomMetamodel.java | 137 ----- .../Migration_0003_ShapeDefinition.java | 84 --- .../Migration_0004_ResourceDefinition.java | 212 -------- .../Migration_0005_UpdateShapeDefinition.java | 94 ---- .../Migration_0007_RemoveMongobee.java | 40 -- .../Migration_0008_ShapesInternalChange.java | 62 --- .../Migration_0009_ShapeTargetClasses.java | 91 ---- .../Migration_0010_FixShapeXsdPrefix.java | 81 --- .../production/Migration_0011_ComplyFDPO.java | 138 ----- .../Migration_0012_MetadataSchemas.java | 259 ---------- .../Migration_0013_ComplexSearch.java | 78 --- .../Migration_0014_FormsAutocomplete.java | 86 ---- .../Migration_0015_FixMetadataVersion.java | 123 ----- ...igration_0016_IndexSettingsAutoPermit.java | 70 --- .../RdfDevelopmentMigrationRunner.java | 32 +- .../development/metadata}/AclMigration.java | 54 +- .../metadata/RdfMetadataMigration.java | 64 ++- .../production/Rdf_Migration_0001_Init.java | 14 +- .../Rdf_Migration_0002_Metadata_Draft.java | 29 +- .../production/Rdf_Migration_0003_FDPO.java | 124 +---- .../Rdf_Migration_0004_Cleanup_Index.java | 83 +-- ...Rdf_Migration_0005_FixMetadataVersion.java | 37 +- .../fairdatapoint/entity/apikey/ApiKey.java | 28 +- .../fairdatapoint/entity/base/BaseEntity.java | 78 +++ .../entity/base/BaseEntityCustomUUID.java | 79 +++ .../entity/index/entry/IndexEntry.java | 69 ++- .../entity/index/entry/IndexEntryState.java | 8 +- .../index/entry/RepositoryMetadata.java | 10 +- .../entity/index/event/Event.java | 125 ----- .../entity/index/event/IndexEvent.java | 134 +++++ .../index/event/IndexEventPayload.java} | 49 +- .../{EventType.java => IndexEventType.java} | 12 +- .../event/{ => payload}/AdminTrigger.java | 2 +- .../event/{ => payload}/IncomingPing.java | 2 +- .../{ => payload}/MetadataRetrieval.java | 2 +- .../event/{ => payload}/WebhookPing.java | 2 +- .../event/{ => payload}/WebhookTrigger.java | 13 +- .../entity/index/settings/IndexSettings.java | 89 +++- ...ttingsPing.java => SettingsIndexPing.java} | 13 +- ...ieval.java => SettingsIndexRetrieval.java} | 13 +- .../entity/index/webhook/IndexWebhook.java | 80 +++ ...bhookEvent.java => IndexWebhookEvent.java} | 16 +- .../entity/membership/Membership.java | 40 +- .../membership/MembershipPermission.java | 35 +- .../entity/metadata/Metadata.java | 11 - .../entity/resource/MetadataSchemaUsage.java | 62 +++ .../entity/resource/ResourceDefinition.java | 53 +- .../resource/ResourceDefinitionChild.java | 43 +- .../ResourceDefinitionChildMetadata.java} | 62 +-- .../resource/ResourceDefinitionLink.java | 21 +- .../entity/schema/MetadataSchema.java | 134 +---- .../MetadataSchemaExtension.java} | 48 +- .../entity/schema/MetadataSchemaState.java | 29 ++ .../entity/schema/MetadataSchemaVersion.java | 143 ++++++ .../entity/search/SearchSavedQuery.java | 55 +- .../entity/settings/Settings.java | 97 ++-- .../settings/SettingsAutocompleteSource.java | 26 +- .../entity/settings/SettingsMetric.java | 56 ++ .../entity/settings/SettingsSearchFilter.java | 37 +- .../settings/SettingsSearchFilterItem.java | 24 +- .../user/{User.java => UserAccount.java} | 54 +- .../fairdatapoint/entity/user/UserRole.java | 5 +- .../fairdatapoint/service/UtilityService.java | 6 +- .../service/apikey/ApiKeyMapper.java | 14 +- .../service/apikey/ApiKeyService.java | 40 +- .../service/dashboard/DashboardService.java | 4 +- .../autocomplete/FormsAutocompleteCache.java | 6 +- .../FormsAutocompleteService.java | 17 +- .../retrieval/RdfEntitiesSparqlRetriever.java | 4 +- .../index/common/IndexFeatureAspect.java | 6 +- .../service/index/entry/IndexEntryMapper.java | 37 +- .../index/entry/IndexEntryService.java | 94 ++-- .../service/index/event/EventMapper.java | 14 +- .../service/index/event/EventService.java | 130 +++-- .../index/event/IncomingPingUtils.java | 14 +- .../index/event/MetadataRetrievalUtils.java | 34 +- .../index/harvester/HarvesterService.java | 9 +- .../settings/IndexSettingsDefaults.java} | 27 +- .../index/settings/IndexSettingsMapper.java | 27 +- .../index/settings/IndexSettingsService.java | 37 +- .../service/index/webhook/WebhookMapper.java | 24 +- .../service/index/webhook/WebhookService.java | 77 ++- .../service/index/webhook/WebhookUtils.java | 24 +- .../fairdatapoint/service/jwt/JwtService.java | 35 +- .../service/member/MemberMapper.java | 17 +- .../service/member/MemberService.java | 124 ++--- .../service/membership/MembershipService.java | 24 +- .../catalog/CatalogMetadataService.java | 4 +- .../common/AbstractMetadataService.java | 11 +- .../metadata/enhance/MetadataEnhancer.java | 4 +- .../metric/MetricsMetadataService.java | 26 +- .../metadata/validator/MetadataValidator.java | 2 +- .../service/openapi/OpenApiService.java | 18 +- .../service/ping/PingService.java | 23 +- .../service/profile/ProfileService.java | 34 +- .../service/reset/FactoryDefaults.java | 375 -------------- .../service/reset/ResetService.java | 39 +- .../resource/ResourceDefinitionCache.java | 62 +-- .../resource/ResourceDefinitionMapper.java | 154 +++++- .../resource/ResourceDefinitionService.java | 172 +++++-- .../ResourceDefinitionTargetClassesCache.java | 103 ++-- .../resource/ResourceDefinitionValidator.java | 55 +- .../service/schema/MetadataSchemaMapper.java | 198 +++++--- .../service/schema/MetadataSchemaService.java | 477 +++++++++++------- .../schema/MetadataSchemaValidator.java | 71 +-- .../service/search/SearchFilterCache.java | 20 +- .../service/search/SearchMapper.java | 4 +- .../service/search/SearchService.java | 23 +- .../search/query/SearchSavedQueryMapper.java | 49 +- .../search/query/SearchSavedQueryService.java | 84 ++- ...ervice.java => AuthenticationService.java} | 8 +- ...rvice.java => UserDetailsServiceImpl.java} | 19 +- .../service/settings/SettingsCache.java | 27 +- .../service/settings/SettingsMapper.java | 272 ++++------ .../service/settings/SettingsService.java | 141 ++++-- .../service/user/CurrentUserService.java | 20 +- .../service/user/UserMapper.java | 30 +- .../service/user/UserService.java | 87 ++-- .../service/user/UserValidator.java | 16 +- .../dtls/fairdatapoint/util/KnownUUIDs.java | 159 ++++-- .../TimeUtils.java} | 17 +- .../resources/application-development.yml | 11 +- src/main/resources/application-production.yml | 4 + src/main/resources/application.yml | 18 +- .../db/migration/V0001.0__init-fdp-db.sql | 438 ++++++++++++++++ .../db/migration/V0001.1__dev-data-users.sql | 61 +++ .../migration/V0001.2__dev-data-schemas.sql | 473 +++++++++++++++++ .../db/migration/V0001.3__dev-data-rds.sql | 68 +++ .../V0001.4__dev-data-membership.sql | 43 ++ .../db/migration/V0001.5__dev-settings.sql | 73 +++ .../data => fixtures}/shape-catalog.ttl | 0 .../data => fixtures}/shape-custom-edited.ttl | 0 .../schema/data => fixtures}/shape-custom.ttl | 0 .../data => fixtures}/shape-data-service.ttl | 0 .../data => fixtures}/shape-dataset.ttl | 0 .../data => fixtures}/shape-distribution.ttl | 0 .../schema/data => fixtures}/shape-fdp.ttl | 0 .../shape-metadata-service.ttl | 0 .../data => fixtures}/shape-resource.ttl | 0 .../production/0003_shape-catalog.ttl | 24 - .../production/0003_shape-dataset.ttl | 36 -- .../production/0003_shape-distribution.ttl | 45 -- .../production/0003_shape-repository.ttl | 27 - .../production/0003_shape-resource.ttl | 59 --- .../production/0005_shape-catalog.ttl | 30 -- .../production/0005_shape-dataset.ttl | 44 -- .../production/0005_shape-distribution.ttl | 50 -- .../production/0005_shape-repository.ttl | 40 -- .../production/0005_shape-resource.ttl | 64 --- .../production/0011_shape-data-service.ttl | 20 - .../migration/production/0011_shape-fdp.ttl | 47 -- .../0011_shape-metadata-service.ttl | 6 - .../fairdatapoint/BaseIntegrationTest.java | 2 + .../fairdatapoint/WebIntegrationTest.java | 36 +- .../acceptance/apikey/Detail_DELETE.java | 20 +- .../acceptance/apikey/List_GET.java | 7 +- .../acceptance/dashboard/List_GET.java | 8 +- .../acceptance/general/SecurityTest.java | 11 +- .../index/admin/List_TriggerAll_POST.java | 17 +- .../index/admin/List_Trigger_POST.java | 20 +- .../acceptance/index/entry/List_All_GET.java | 2 +- .../acceptance/index/entry/List_GET.java | 2 +- .../acceptance/index/entry/List_Info_GET.java | 5 +- .../acceptance/index/ping/List_POST.java | 2 +- .../index/settings/List_DELETE.java | 66 +-- .../acceptance/index/settings/List_GET.java | 59 +-- .../acceptance/index/settings/List_PUT.java | 68 ++- .../acceptance/membership/List_GET.java | 8 +- .../metadata/catalog/List_POST.java | 8 - .../catalog/member/Detail_DELETE.java | 12 +- .../metadata/catalog/member/Detail_PUT.java | 30 +- .../metadata/catalog/member/List_GET.java | 21 +- .../metadata/catalog/meta/List_GET.java | 17 +- .../dataset/member/Detail_DELETE.java | 15 +- .../metadata/dataset/member/Detail_PUT.java | 30 +- .../metadata/dataset/member/List_GET.java | 20 +- .../metadata/dataset/meta/List_GET.java | 18 +- .../distribution/member/Detail_DELETE.java | 15 +- .../distribution/member/Detail_PUT.java | 30 +- .../distribution/member/List_GET.java | 20 +- .../metadata/distribution/meta/List_GET.java | 17 +- .../acceptance/openapi/SwaggerUI_GET.java | 2 - .../acceptance/resource/Detail_DELETE.java | 23 +- .../acceptance/resource/Detail_GET.java | 26 +- .../acceptance/resource/Detail_PUT.java | 31 +- .../acceptance/resource/List_GET.java | 20 +- .../acceptance/resource/List_POST.java | 18 +- .../acceptance/schema/Common.java | 46 +- .../acceptance/schema/Content_GET.java | 35 +- .../acceptance/schema/Detail_DELETE.java | 26 +- .../acceptance/schema/Detail_GET.java | 14 +- .../acceptance/schema/Draft_DELETE.java | 37 +- .../acceptance/schema/Draft_GET.java | 28 +- .../acceptance/schema/Draft_PUT.java | 73 +-- .../acceptance/schema/Import_POST.java | 83 +-- .../acceptance/schema/List_GET.java | 105 ++-- .../acceptance/schema/List_POST.java | 27 +- .../acceptance/schema/Public_GET.java | 53 +- .../acceptance/schema/Version_DELETE.java | 69 +-- .../acceptance/schema/Version_GET.java | 48 +- .../acceptance/schema/Version_PUT.java | 59 ++- .../acceptance/schema/Versions_POST.java | 63 +-- .../acceptance/search/Filters_GET.java | 9 +- .../acceptance/search/query/List_GET.java | 5 +- .../acceptance/search/query/List_POST.java | 5 +- .../search/query/saved/Detail_DELETE.java | 35 +- .../search/query/saved/Detail_GET.java | 41 +- .../search/query/saved/Detail_PUT.java | 23 +- .../search/query/saved/List_GET.java | 39 +- .../search/query/saved/List_POST.java | 5 +- .../acceptance/settings/List_DELETE.java | 72 +-- .../acceptance/settings/List_GET.java | 60 +-- .../acceptance/settings/List_PUT.java | 54 +- .../acceptance/token/List_POST.java | 2 - .../fairdatapoint/acceptance/user/Common.java | 4 +- .../acceptance/user/Current_GET.java | 14 +- .../acceptance/user/Detail_Current_PUT.java | 5 - .../user/Detail_Current_Password_PUT.java | 12 +- .../acceptance/user/Detail_DELETE.java | 28 +- .../acceptance/user/Detail_GET.java | 20 +- .../acceptance/user/Detail_PUT.java | 32 +- .../acceptance/user/Detail_Password_PUT.java | 22 +- .../acceptance/user/List_GET.java | 24 +- .../acceptance/user/List_POST.java | 33 +- .../fairdatapoint/config/DatabaseConfig.java} | 23 +- .../common/MetadataRepositoryTest.java | 11 + .../index/harvester/HarvesterServiceTest.java | 18 +- .../generic/GenericMetadataServiceTest.java | 24 +- .../metric/MetricsMetadataServiceTest.java | 2 - .../resource/ResourceDefinitionCacheTest.java | 28 +- .../ResourceDefinitionValidatorTest.java | 168 ++++-- .../dtls/fairdatapoint/utils/AuthHelper.java | 19 +- .../utils/TestIndexEntryFixtures.java | 57 ++- .../utils/TestRdfMetadataFixtures.java | 36 +- src/test/resources/application-testing.yml | 20 +- src/test/resources/log4j2.local.xml | 17 + src/test/resources/log4j2.xml | 2 +- .../db/migration/V0001.1__dev-data-users.sql | 61 +++ .../migration/V0001.2__dev-data-schemas.sql | 473 +++++++++++++++++ .../db/migration/V0001.3__dev-data-rds.sql | 68 +++ .../V0001.4__dev-data-membership.sql | 43 ++ .../db/migration/V0001.5__dev-settings.sql | 73 +++ .../db/migration/V0001.6__test-schemas.sql | 161 ++++++ 341 files changed, 7641 insertions(+), 8160 deletions(-) create mode 100644 src/main/java/nl/dtls/fairdatapoint/api/controller/settings/SettingsDefaults.java create mode 100644 src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionChildDTO.java rename src/main/java/nl/dtls/fairdatapoint/{entity/resource/ResourceDefinitionChildListView.java => api/dto/resource/ResourceDefinitionChildListViewDTO.java} (82%) create mode 100644 src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionChildListViewMetadataDTO.java rename src/main/java/nl/dtls/fairdatapoint/{entity/resource/ResourceDefinitionChildListViewMetadata.java => api/dto/resource/ResourceDefinitionLinkDTO.java} (86%) rename src/main/java/nl/dtls/fairdatapoint/{entity/settings/SettingsMetricsEntry.java => api/dto/settings/SettingsMetricDTO.java} (85%) rename src/main/java/nl/dtls/fairdatapoint/{database/mongo/migration/production/Migration_0006_ShapesSharing.java => config/DatabaseConfig.java} (51%) delete mode 100644 src/main/java/nl/dtls/fairdatapoint/config/MongoConfig.java rename src/main/java/nl/dtls/fairdatapoint/database/{mongo => db}/repository/ApiKeyRepository.java (79%) rename src/main/java/nl/dtls/fairdatapoint/database/{mongo => db}/repository/IndexEntryRepository.java (57%) rename src/main/java/nl/dtls/fairdatapoint/database/{mongo/repository/EventRepository.java => db/repository/IndexEventRepository.java} (62%) rename src/main/java/nl/dtls/fairdatapoint/database/{mongo => db}/repository/IndexSettingsRepository.java (80%) create mode 100644 src/main/java/nl/dtls/fairdatapoint/database/db/repository/IndexWebhookRepository.java create mode 100644 src/main/java/nl/dtls/fairdatapoint/database/db/repository/MembershipPermissionRepository.java rename src/main/java/nl/dtls/fairdatapoint/database/{mongo => db}/repository/MembershipRepository.java (80%) create mode 100644 src/main/java/nl/dtls/fairdatapoint/database/db/repository/MetadataSchemaExtensionRepository.java rename src/main/java/nl/dtls/fairdatapoint/database/{mongo => db}/repository/MetadataSchemaRepository.java (56%) create mode 100644 src/main/java/nl/dtls/fairdatapoint/database/db/repository/MetadataSchemaUsageRepository.java create mode 100644 src/main/java/nl/dtls/fairdatapoint/database/db/repository/MetadataSchemaVersionRepository.java rename src/main/java/nl/dtls/fairdatapoint/{entity/settings/SettingsFormsAutocomplete.java => database/db/repository/ResourceDefinitionChildMetadataRepository.java} (77%) create mode 100644 src/main/java/nl/dtls/fairdatapoint/database/db/repository/ResourceDefinitionChildRepository.java create mode 100644 src/main/java/nl/dtls/fairdatapoint/database/db/repository/ResourceDefinitionLinkRepository.java rename src/main/java/nl/dtls/fairdatapoint/database/{mongo => db}/repository/ResourceDefinitionRepository.java (76%) rename src/main/java/nl/dtls/fairdatapoint/database/{mongo => db}/repository/SearchSavedQueryRepository.java (79%) create mode 100644 src/main/java/nl/dtls/fairdatapoint/database/db/repository/SettingsAutocompleteSourceRepository.java create mode 100644 src/main/java/nl/dtls/fairdatapoint/database/db/repository/SettingsMetricRepository.java rename src/main/java/nl/dtls/fairdatapoint/database/{mongo => db}/repository/SettingsRepository.java (81%) create mode 100644 src/main/java/nl/dtls/fairdatapoint/database/db/repository/SettingsSearchFilterItemRepository.java rename src/main/java/nl/dtls/fairdatapoint/{entity/settings/SettingsPing.java => database/db/repository/SettingsSearchFilterRepository.java} (76%) rename src/main/java/nl/dtls/fairdatapoint/database/{mongo/repository/UserRepository.java => db/repository/UserAccountRepository.java} (75%) rename src/main/java/nl/dtls/fairdatapoint/database/{mongo/repository/WebhookRepository.java => db/repository/base/BaseRepository.java} (79%) delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/MigrationRunner.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/apikey/ApiKeyMigration.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/apikey/data/ApiKeyFixtures.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/index/entry/IndexEntryMigration.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/index/entry/data/IndexEntryFixtures.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/index/event/EventMigration.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/membership/MembershipMigration.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/membership/data/MembershipFixtures.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/resource/ResourceDefinitionMigration.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/resource/data/ResourceDefinitionFixtures.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/MetadataSchemaMigration.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/MetadataSchemaFixtures.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/search/SearchSavedQueryFixtures.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/settings/data/SettingsFixtures.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/user/UserMigration.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/user/data/UserFixtures.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0001_Init.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0002_CustomMetamodel.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0003_ShapeDefinition.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0004_ResourceDefinition.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0005_UpdateShapeDefinition.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0007_RemoveMongobee.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0008_ShapesInternalChange.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0009_ShapeTargetClasses.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0010_FixShapeXsdPrefix.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0011_ComplyFDPO.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0012_MetadataSchemas.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0013_ComplexSearch.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0014_FormsAutocomplete.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0015_FixMetadataVersion.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0016_IndexSettingsAutoPermit.java rename src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/{development => }/RdfDevelopmentMigrationRunner.java (59%) rename src/main/java/nl/dtls/fairdatapoint/database/{mongo/migration/development/acl => rdf/migration/development/metadata}/AclMigration.java (62%) create mode 100644 src/main/java/nl/dtls/fairdatapoint/entity/base/BaseEntity.java create mode 100644 src/main/java/nl/dtls/fairdatapoint/entity/base/BaseEntityCustomUUID.java delete mode 100644 src/main/java/nl/dtls/fairdatapoint/entity/index/event/Event.java create mode 100644 src/main/java/nl/dtls/fairdatapoint/entity/index/event/IndexEvent.java rename src/main/java/nl/dtls/fairdatapoint/{service/metadata/validator/MetadataStateValidator.java => entity/index/event/IndexEventPayload.java} (52%) rename src/main/java/nl/dtls/fairdatapoint/entity/index/event/{EventType.java => IndexEventType.java} (90%) rename src/main/java/nl/dtls/fairdatapoint/entity/index/event/{ => payload}/AdminTrigger.java (95%) rename src/main/java/nl/dtls/fairdatapoint/entity/index/event/{ => payload}/IncomingPing.java (96%) rename src/main/java/nl/dtls/fairdatapoint/entity/index/event/{ => payload}/MetadataRetrieval.java (96%) rename src/main/java/nl/dtls/fairdatapoint/entity/index/event/{ => payload}/WebhookPing.java (96%) rename src/main/java/nl/dtls/fairdatapoint/entity/index/event/{ => payload}/WebhookTrigger.java (81%) rename src/main/java/nl/dtls/fairdatapoint/entity/index/settings/{IndexSettingsPing.java => SettingsIndexPing.java} (82%) rename src/main/java/nl/dtls/fairdatapoint/entity/index/settings/{IndexSettingsRetrieval.java => SettingsIndexRetrieval.java} (82%) create mode 100644 src/main/java/nl/dtls/fairdatapoint/entity/index/webhook/IndexWebhook.java rename src/main/java/nl/dtls/fairdatapoint/entity/index/webhook/{WebhookEvent.java => IndexWebhookEvent.java} (88%) create mode 100644 src/main/java/nl/dtls/fairdatapoint/entity/resource/MetadataSchemaUsage.java rename src/main/java/nl/dtls/fairdatapoint/entity/{schema/MetadataSchemaDraft.java => resource/ResourceDefinitionChildMetadata.java} (61%) rename src/main/java/nl/dtls/fairdatapoint/entity/{index/webhook/Webhook.java => schema/MetadataSchemaExtension.java} (62%) create mode 100644 src/main/java/nl/dtls/fairdatapoint/entity/schema/MetadataSchemaState.java create mode 100644 src/main/java/nl/dtls/fairdatapoint/entity/schema/MetadataSchemaVersion.java create mode 100644 src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsMetric.java rename src/main/java/nl/dtls/fairdatapoint/entity/user/{User.java => UserAccount.java} (54%) rename src/main/java/nl/dtls/fairdatapoint/{database/mongo/migration/development/settings/SettingsMigration.java => service/index/settings/IndexSettingsDefaults.java} (56%) rename src/main/java/nl/dtls/fairdatapoint/service/security/{MongoAuthenticationService.java => AuthenticationService.java} (91%) rename src/main/java/nl/dtls/fairdatapoint/service/security/{MongoUserDetailsService.java => UserDetailsServiceImpl.java} (78%) rename src/main/java/nl/dtls/fairdatapoint/{entity/settings/SettingsForms.java => util/TimeUtils.java} (82%) create mode 100644 src/main/resources/db/migration/V0001.0__init-fdp-db.sql create mode 100644 src/main/resources/dev/db/migration/V0001.1__dev-data-users.sql create mode 100644 src/main/resources/dev/db/migration/V0001.2__dev-data-schemas.sql create mode 100644 src/main/resources/dev/db/migration/V0001.3__dev-data-rds.sql create mode 100644 src/main/resources/dev/db/migration/V0001.4__dev-data-membership.sql create mode 100644 src/main/resources/dev/db/migration/V0001.5__dev-settings.sql rename src/main/resources/nl/dtls/fairdatapoint/database/{mongo/migration/development/schema/data => fixtures}/shape-catalog.ttl (100%) rename src/main/resources/nl/dtls/fairdatapoint/database/{mongo/migration/development/schema/data => fixtures}/shape-custom-edited.ttl (100%) rename src/main/resources/nl/dtls/fairdatapoint/database/{mongo/migration/development/schema/data => fixtures}/shape-custom.ttl (100%) rename src/main/resources/nl/dtls/fairdatapoint/database/{mongo/migration/development/schema/data => fixtures}/shape-data-service.ttl (100%) rename src/main/resources/nl/dtls/fairdatapoint/database/{mongo/migration/development/schema/data => fixtures}/shape-dataset.ttl (100%) rename src/main/resources/nl/dtls/fairdatapoint/database/{mongo/migration/development/schema/data => fixtures}/shape-distribution.ttl (100%) rename src/main/resources/nl/dtls/fairdatapoint/database/{mongo/migration/development/schema/data => fixtures}/shape-fdp.ttl (100%) rename src/main/resources/nl/dtls/fairdatapoint/database/{mongo/migration/development/schema/data => fixtures}/shape-metadata-service.ttl (100%) rename src/main/resources/nl/dtls/fairdatapoint/database/{mongo/migration/development/schema/data => fixtures}/shape-resource.ttl (100%) delete mode 100644 src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-catalog.ttl delete mode 100644 src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-dataset.ttl delete mode 100644 src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-distribution.ttl delete mode 100644 src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-repository.ttl delete mode 100644 src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-resource.ttl delete mode 100644 src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-catalog.ttl delete mode 100644 src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-dataset.ttl delete mode 100644 src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-distribution.ttl delete mode 100644 src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-repository.ttl delete mode 100644 src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-resource.ttl delete mode 100644 src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0011_shape-data-service.ttl delete mode 100644 src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0011_shape-fdp.ttl delete mode 100644 src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0011_shape-metadata-service.ttl rename src/{main/java/nl/dtls/fairdatapoint/database/mongo/repository/MetadataSchemaDraftRepository.java => test/java/nl/dtls/fairdatapoint/config/DatabaseConfig.java} (72%) create mode 100644 src/test/resources/log4j2.local.xml create mode 100644 src/test/resources/test/db/migration/V0001.1__dev-data-users.sql create mode 100644 src/test/resources/test/db/migration/V0001.2__dev-data-schemas.sql create mode 100644 src/test/resources/test/db/migration/V0001.3__dev-data-rds.sql create mode 100644 src/test/resources/test/db/migration/V0001.4__dev-data-membership.sql create mode 100644 src/test/resources/test/db/migration/V0001.5__dev-settings.sql create mode 100644 src/test/resources/test/db/migration/V0001.6__test-schemas.sql diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 326a788cf..d844cd063 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -8,13 +8,29 @@ jobs: test: name: Test strategy: + fail-fast: false matrix: os: - - ubuntu-20.04 - # - windows-2022 (MongoDB issues in CI) - - macos-12 + - ubuntu-22.04 + # - windows-2022 (cannot use Docker for postgres) + # - macos-12 (cannot use Docker for postgres) runs-on: ${{ matrix.os }} + services: + postgres: + image: postgres:16 + env: + POSTGRES_DB: fdp_test + POSTGRES_USER: fdp + POSTGRES_PASSWORD: fdp + options: >- + --health-cmd pg_isready + --health-interval 10s + --health-timeout 5s + --health-retries 5 + ports: + - 54321:5432 + env: JAVA_DISTRIBUTION: temurin JAVA_VERSION: 21 @@ -25,15 +41,6 @@ jobs: with: fetch-depth: 0 - - name: Set up MongoDB - uses: ankane/setup-mongodb@v1 - with: - mongodb-version: '5.0' - - - name: Check MongoDB - run: | - mongo --eval "db.version()" - - name: Setup Java uses: actions/setup-java@v3 with: @@ -48,6 +55,12 @@ jobs: - name: Test run: | mvn -q -U -B test + env: + FDP_POSTGRES_HOST: localhost + FDP_POSTGRES_PORT: 54321 + FDP_POSTGRES_DB: fdp_test + FDP_POSTGRES_USERNAME: fdp + FDP_POSTGRES_PASSWORD: fdp - name: Package run: | diff --git a/.gitignore b/.gitignore index a5f3c7517..a31dd09b1 100644 --- a/.gitignore +++ b/.gitignore @@ -3,4 +3,5 @@ target/ # Netbeans nb-configuration\.xml -/nbproject/ \ No newline at end of file +/nbproject/ +*.iml diff --git a/pom.xml b/pom.xml index 9cb0d1a5e..c49070c7e 100644 --- a/pom.xml +++ b/pom.xml @@ -5,7 +5,7 @@ org.springframework.boot spring-boot-starter-parent - 3.1.5 + 3.2.3 nl.dtls @@ -52,16 +52,15 @@ 1.2.0.RELEASE - 5.2.4.RELEASE 2.2.0 - 5.3.5 - 4.1.5 + 42.7.2 4.3.8 0.12.3 1.18.30 0.1.2-SNAPSHOT + 3.7.3 5.2.2 @@ -104,18 +103,6 @@ - - - - io.mongock - mongock-bom - ${mongock.version} - pom - import - - - - @@ -154,7 +141,7 @@ org.springframework.boot - spring-boot-starter-data-mongodb + spring-boot-starter-data-jpa org.springframework.security @@ -172,28 +159,6 @@ org.springframework.boot spring-boot-starter-validation - - org.springframework.security - spring-security-acl-mongodb - ${spring.security.acl.mongo.version} - - - - - - - io.mongock - mongock-springboot - - - io.mongock - mongodb-springdata-v4-driver - - - org.springframework.data - spring-data-mongodb - ${mongodb.spring-data.version} - @@ -257,6 +222,22 @@ rdf-resource-resolver-api ${rdf-resolver.version} + + org.flywaydb + flyway-core + + + io.hypersistence + hypersistence-utils-hibernate-63 + ${hypersistence.version} + + + + org.postgresql + postgresql + ${postgresql.version} + runtime + diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/apikey/ApiKeyController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/apikey/ApiKeyController.java index 7db4eb6f3..c5d6ce8a9 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/apikey/ApiKeyController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/apikey/ApiKeyController.java @@ -23,26 +23,27 @@ package nl.dtls.fairdatapoint.api.controller.apikey; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.apikey.ApiKeyDTO; import nl.dtls.fairdatapoint.entity.exception.ResourceNotFoundException; import nl.dtls.fairdatapoint.service.apikey.ApiKeyService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; +import java.util.UUID; import static java.lang.String.format; @Tag(name = "Authentication and Authorization") @RestController @RequestMapping("/api-keys") +@RequiredArgsConstructor public class ApiKeyController { - @Autowired - private ApiKeyService apiKeyService; + private final ApiKeyService apiKeyService; @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity> getApiKeys() { @@ -59,7 +60,7 @@ public ResponseEntity createApiKey() { @DeleteMapping("/{uuid}") @ResponseStatus(HttpStatus.NO_CONTENT) public ResponseEntity deleteApiKey( - @PathVariable final String uuid + @PathVariable final UUID uuid ) throws ResourceNotFoundException { final boolean result = apiKeyService.delete(uuid); if (result) { diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/config/ConfigController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/config/ConfigController.java index c1d28c43a..e4932f5ad 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/config/ConfigController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/config/ConfigController.java @@ -23,9 +23,9 @@ package nl.dtls.fairdatapoint.api.controller.config; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.config.BootstrapConfigDTO; import nl.dtls.fairdatapoint.service.config.ConfigService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -36,10 +36,10 @@ @Tag(name = "Client") @RestController @RequestMapping("/configs") +@RequiredArgsConstructor public class ConfigController { - @Autowired - private ConfigService configService; + private final ConfigService configService; @GetMapping(path = "/bootstrap", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity getBootstrapConfig() { diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/dashboard/DashboardController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/dashboard/DashboardController.java index 4ba66cfea..57f9446ed 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/dashboard/DashboardController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/dashboard/DashboardController.java @@ -24,12 +24,11 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.dashboard.DashboardItemDTO; import nl.dtls.fairdatapoint.service.dashboard.DashboardService; import nl.dtls.fairdatapoint.service.metadata.exception.MetadataServiceException; import org.eclipse.rdf4j.model.IRI; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -46,14 +45,12 @@ @Tag(name = "Client") @RestController @RequestMapping("/dashboard") +@RequiredArgsConstructor public class DashboardController { - @Autowired - @Qualifier("persistentUrl") - private String persistentUrl; + private final String persistentUrl; - @Autowired - private DashboardService dashboardService; + private final DashboardService dashboardService; @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity> getDashboard( diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/exception/ExceptionControllerAdvice.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/exception/ExceptionControllerAdvice.java index e836f148f..5853681b1 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/exception/ExceptionControllerAdvice.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/exception/ExceptionControllerAdvice.java @@ -78,6 +78,7 @@ public class ExceptionControllerAdvice { public ErrorDTO handleConstraintViolation(Exception exception) { log.warn(exception.getMessage()); log.debug("Handling bad request (ConstraintViolation)", exception); + exception.printStackTrace(); return new ErrorDTO(HttpStatus.BAD_REQUEST, exception.getMessage()); } @@ -95,6 +96,7 @@ public ErrorDTO handleConstraintViolation(Exception exception) { public ErrorDTO handleValidationException(Exception exception) { log.warn(exception.getMessage()); log.debug("Handling bad request (ValidationException)", exception); + exception.printStackTrace(); return new ErrorDTO(HttpStatus.BAD_REQUEST, exception.getMessage()); } @@ -112,6 +114,7 @@ public ErrorDTO handleValidationException(Exception exception) { public Model handleRdfValidationException(RdfValidationException exception) { final Model validationReportModel = exception.getModel(); log.debug("Handling bad request (RdfValidationException)", exception); + exception.printStackTrace(); // Log number of errors final IRI validationResultIri = i("http://www.w3.org/ns/shacl#ValidationResult"); @@ -140,6 +143,7 @@ public Model handleRdfValidationException(RdfValidationException exception) { ) ) public ErrorDTO handleInvalidQuery(MalformedQueryException exception) { + exception.printStackTrace(); return handleInvalidSparqlQuery(exception); } @@ -155,6 +159,7 @@ public ErrorDTO handleInvalidQuery(MalformedQueryException exception) { ) ) public ErrorDTO handleInvalidQuery(QueryEvaluationException exception) { + exception.printStackTrace(); return handleInvalidSparqlQuery(exception); } @@ -172,6 +177,7 @@ public ErrorDTO handleInvalidQuery(QueryEvaluationException exception) { public ErrorDTO handleUnauthorized(Exception exception) { log.error(exception.getMessage()); log.debug("Handling unauthorized", exception); + exception.printStackTrace(); return new ErrorDTO(HttpStatus.UNAUTHORIZED, exception.getMessage()); } @@ -189,6 +195,7 @@ public ErrorDTO handleUnauthorized(Exception exception) { public ErrorDTO handleForbidden(Exception exception) { log.error(exception.getMessage()); log.debug("Handling forbidden", exception); + exception.printStackTrace(); return new ErrorDTO(HttpStatus.FORBIDDEN, exception.getMessage()); } @@ -206,6 +213,7 @@ public ErrorDTO handleForbidden(Exception exception) { public ErrorDTO handleResourceNotFound(ResourceNotFoundException exception) { log.error(exception.getMessage()); log.debug("Handling resource not found", exception); + exception.printStackTrace(); return new ErrorDTO(HttpStatus.NOT_FOUND, exception.getMessage()); } @@ -223,12 +231,14 @@ public ErrorDTO handleResourceNotFound(ResourceNotFoundException exception) { public ErrorDTO handleInternalServerError(Exception exception) { log.error(exception.getMessage()); log.debug("Handling internal server error (MetadataServiceException)", exception); + exception.printStackTrace(); return new ErrorDTO(HttpStatus.INTERNAL_SERVER_ERROR, exception.getMessage()); } @ExceptionHandler(AbstractIndexException.class) public ResponseEntity handleIndexException(AbstractIndexException exception) { log.debug("Handling index exception", exception); + exception.printStackTrace(); return new ResponseEntity<>(exception.getErrorDTO(), exception.getStatus()); } diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/form/FormAutocompleteController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/form/FormAutocompleteController.java index 3d991c2a3..aaa7f50cb 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/form/FormAutocompleteController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/form/FormAutocompleteController.java @@ -24,10 +24,10 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.form.FormAutocompleteItemDTO; import nl.dtls.fairdatapoint.api.dto.form.FormAutocompleteRequestDTO; import nl.dtls.fairdatapoint.service.form.autocomplete.FormsAutocompleteService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -41,10 +41,10 @@ @Tag(name = "Client") @RestController @RequestMapping("/forms") +@RequiredArgsConstructor public class FormAutocompleteController { - @Autowired - private FormsAutocompleteService autocompleteService; + private final FormsAutocompleteService autocompleteService; @PostMapping( path = "/autocomplete", diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/index/IndexAdminController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/index/IndexAdminController.java index 7f71acca9..c1d1560fc 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/index/IndexAdminController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/index/IndexAdminController.java @@ -26,15 +26,15 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import nl.dtls.fairdatapoint.api.dto.index.ping.PingDTO; import nl.dtls.fairdatapoint.database.rdf.repository.exception.MetadataRepositoryException; -import nl.dtls.fairdatapoint.entity.index.event.Event; +import nl.dtls.fairdatapoint.entity.index.event.IndexEvent; import nl.dtls.fairdatapoint.service.UtilityService; import nl.dtls.fairdatapoint.service.index.entry.IndexEntryService; import nl.dtls.fairdatapoint.service.index.event.EventService; import nl.dtls.fairdatapoint.service.index.webhook.WebhookService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; @@ -45,19 +45,16 @@ @Slf4j @RestController @RequestMapping("/index/admin") +@RequiredArgsConstructor public class IndexAdminController { - @Autowired - private UtilityService utilityService; + private final UtilityService utilityService; - @Autowired - private EventService eventService; + private final EventService eventService; - @Autowired - private WebhookService webhookService; + private final WebhookService webhookService; - @Autowired - private IndexEntryService indexEntryService; + private final IndexEntryService indexEntryService; @Operation(hidden = true) @PostMapping("/trigger") @@ -69,7 +66,7 @@ public void triggerMetadataRetrieve( ) throws MetadataRepositoryException { log.info("Received ping trigger request from {}", utilityService.getRemoteAddr(request)); - final Event event = eventService.acceptAdminTrigger(request, reqDto); + final IndexEvent event = eventService.acceptAdminTrigger(request, reqDto); webhookService.triggerWebhooks(event); eventService.triggerMetadataRetrieval(event); indexEntryService.harvest(reqDto.getClientUrl()); @@ -82,7 +79,7 @@ public void triggerMetadataRetrieve( public void triggerMetadataRetrieveAll(HttpServletRequest request) { log.info("Received ping trigger all request from {}", utilityService.getRemoteAddr(request)); - final Event event = eventService.acceptAdminTriggerAll(request); + final IndexEvent event = eventService.acceptAdminTriggerAll(request); webhookService.triggerWebhooks(event); eventService.triggerMetadataRetrieval(event); } @@ -94,7 +91,7 @@ public void triggerMetadataRetrieveAll(HttpServletRequest request) { public void webhookPing(@RequestParam UUID webhook, HttpServletRequest request) { log.info("Received webhook {} ping trigger from {}", webhook, utilityService.getRemoteAddr(request)); - final Event event = webhookService.handleWebhookPing(request, webhook); + final IndexEvent event = webhookService.handleWebhookPing(request, webhook); webhookService.triggerWebhooks(event); } } diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/index/IndexEntryController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/index/IndexEntryController.java index ff5d8f510..b0a4d11ed 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/index/IndexEntryController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/index/IndexEntryController.java @@ -24,6 +24,7 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.index.entry.IndexEntryDTO; import nl.dtls.fairdatapoint.api.dto.index.entry.IndexEntryDetailDTO; import nl.dtls.fairdatapoint.api.dto.index.entry.IndexEntryInfoDTO; @@ -31,13 +32,12 @@ import nl.dtls.fairdatapoint.api.dto.index.ping.PingDTO; import nl.dtls.fairdatapoint.database.rdf.repository.exception.MetadataRepositoryException; import nl.dtls.fairdatapoint.entity.index.entry.IndexEntryPermit; -import nl.dtls.fairdatapoint.entity.index.event.Event; +import nl.dtls.fairdatapoint.entity.index.event.IndexEvent; import nl.dtls.fairdatapoint.service.index.entry.IndexEntryService; import nl.dtls.fairdatapoint.service.index.event.EventService; import nl.dtls.fairdatapoint.service.index.harvester.HarvesterService; import nl.dtls.fairdatapoint.service.index.webhook.WebhookService; import org.eclipse.rdf4j.model.Model; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; @@ -47,26 +47,23 @@ import java.util.List; import java.util.Optional; +import java.util.UUID; @Tag(name = "Index") @RestController @RequestMapping("/index/entries") +@RequiredArgsConstructor public class IndexEntryController { - @Autowired - private IndexEntryService service; + private final IndexEntryService service; - @Autowired - private HarvesterService harvesterService; + private final HarvesterService harvesterService; - @Autowired - private EventService eventService; + private final EventService eventService; - @Autowired - private WebhookService webhookService; + private final WebhookService webhookService; - @Autowired - private IndexEntryService indexEntryService; + private final IndexEntryService indexEntryService; @GetMapping(path = "", produces = MediaType.APPLICATION_JSON_VALUE) public Page getEntriesPage( @@ -78,14 +75,14 @@ public Page getEntriesPage( } @GetMapping(path = "/{uuid}", produces = MediaType.APPLICATION_JSON_VALUE) - public Optional getEntry(@PathVariable final String uuid) { + public Optional getEntry(@PathVariable final UUID uuid) { return service.getEntryDetailDTO(uuid); } @PutMapping(path = "/{uuid}", produces = MediaType.APPLICATION_JSON_VALUE) @PreAuthorize("hasRole('ADMIN')") public Optional updateEntry( - @PathVariable final String uuid, + @PathVariable final UUID uuid, @RequestBody IndexEntryUpdateDTO reqDto, HttpServletRequest request ) throws MetadataRepositoryException { @@ -93,7 +90,7 @@ public Optional updateEntry( if (resDto.isPresent()) { final String clientUrl = resDto.get().getClientUrl(); if (resDto.get().getPermit().equals(IndexEntryPermit.ACCEPTED)) { - final Event event = eventService.acceptAdminTrigger(request, new PingDTO(clientUrl)); + final IndexEvent event = eventService.acceptAdminTrigger(request, new PingDTO(clientUrl)); webhookService.triggerWebhooks(event); eventService.triggerMetadataRetrieval(event); indexEntryService.harvest(clientUrl); @@ -106,13 +103,13 @@ public Optional updateEntry( } @GetMapping(path = "/{uuid}/data", produces = "!application/json") - public Model getEntryData(@PathVariable final String uuid) throws MetadataRepositoryException { + public Model getEntryData(@PathVariable final UUID uuid) throws MetadataRepositoryException { return service.getEntryHarvestedData(uuid); } @DeleteMapping("/{uuid}") @ResponseStatus(HttpStatus.NO_CONTENT) - public void deleteEntry(@PathVariable final String uuid) throws MetadataRepositoryException { + public void deleteEntry(@PathVariable final UUID uuid) throws MetadataRepositoryException { service.deleteEntry(uuid); } diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/index/IndexPingController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/index/IndexPingController.java index 2030845df..7751e39d1 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/index/IndexPingController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/index/IndexPingController.java @@ -30,15 +30,15 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import nl.dtls.fairdatapoint.api.dto.index.ping.PingDTO; import nl.dtls.fairdatapoint.database.rdf.repository.exception.MetadataRepositoryException; -import nl.dtls.fairdatapoint.entity.index.event.Event; +import nl.dtls.fairdatapoint.entity.index.event.IndexEvent; import nl.dtls.fairdatapoint.service.UtilityService; import nl.dtls.fairdatapoint.service.index.entry.IndexEntryService; import nl.dtls.fairdatapoint.service.index.event.EventService; import nl.dtls.fairdatapoint.service.index.webhook.WebhookService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -48,19 +48,16 @@ @Slf4j @RestController @RequestMapping("/") +@RequiredArgsConstructor public class IndexPingController { - @Autowired - private EventService eventService; + private final EventService eventService; - @Autowired - private WebhookService webhookService; + private final WebhookService webhookService; - @Autowired - private IndexEntryService indexEntryService; + private final IndexEntryService indexEntryService; - @Autowired - private UtilityService utilityService; + private final UtilityService utilityService; @Operation( description = "Inform about running FAIR Data Point. It is expected to " @@ -97,7 +94,7 @@ public ResponseEntity receivePing( HttpServletRequest request ) throws MetadataRepositoryException { log.info("Received ping from {}", utilityService.getRemoteAddr(request)); - final Event event = eventService.acceptIncomingPing(reqDto, request); + final IndexEvent event = eventService.acceptIncomingPing(reqDto, request); log.info("Triggering metadata retrieval for {}", event.getRelatedTo().getClientUrl()); eventService.triggerMetadataRetrieval(event); indexEntryService.harvest(reqDto.getClientUrl()); diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/index/IndexSettingsController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/index/IndexSettingsController.java index 397cabb59..61fa1b600 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/index/IndexSettingsController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/index/IndexSettingsController.java @@ -24,10 +24,10 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.index.settings.IndexSettingsDTO; import nl.dtls.fairdatapoint.api.dto.index.settings.IndexSettingsUpdateDTO; import nl.dtls.fairdatapoint.service.index.settings.IndexSettingsService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; @@ -35,10 +35,10 @@ @Tag(name = "Index") @RestController @RequestMapping("/index/settings") +@RequiredArgsConstructor public class IndexSettingsController { - @Autowired - private IndexSettingsService indexSettingsService; + private final IndexSettingsService indexSettingsService; @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) @PreAuthorize("hasRole('ADMIN')") diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/label/LabelController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/label/LabelController.java index 66edccc47..962f2e83d 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/label/LabelController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/label/LabelController.java @@ -22,9 +22,9 @@ */ package nl.dtls.fairdatapoint.api.controller.label; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.label.LabelDTO; import nl.dtls.fairdatapoint.service.label.LabelService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -37,9 +37,10 @@ @RestController @RequestMapping("/label") +@RequiredArgsConstructor public class LabelController { - @Autowired - private LabelService labelService; + + private final LabelService labelService; @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity getLabel( diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/membership/MembershipController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/membership/MembershipController.java index 4ecc55aea..43797367b 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/membership/MembershipController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/membership/MembershipController.java @@ -23,9 +23,9 @@ package nl.dtls.fairdatapoint.api.controller.membership; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.membership.MembershipDTO; import nl.dtls.fairdatapoint.service.membership.MembershipService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -38,10 +38,10 @@ @Tag(name = "Authentication and Authorization") @RestController @RequestMapping("/memberships") +@RequiredArgsConstructor public class MembershipController { - @Autowired - private MembershipService membershipService; + private final MembershipService membershipService; @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity> getUsers() { diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/metadata/GenericController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/metadata/GenericController.java index 71a55ced1..87ac3b514 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/metadata/GenericController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/metadata/GenericController.java @@ -24,6 +24,7 @@ import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.database.rdf.repository.RepositoryMode; import nl.dtls.fairdatapoint.database.rdf.repository.exception.MetadataRepositoryException; import nl.dtls.fairdatapoint.database.rdf.repository.generic.GenericMetadataRepository; @@ -31,7 +32,7 @@ import nl.dtls.fairdatapoint.entity.exception.ValidationException; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinitionChild; -import nl.dtls.fairdatapoint.entity.user.User; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import nl.dtls.fairdatapoint.service.metadata.common.MetadataService; import nl.dtls.fairdatapoint.service.metadata.enhance.MetadataEnhancer; import nl.dtls.fairdatapoint.service.metadata.exception.MetadataServiceException; @@ -47,8 +48,6 @@ import org.eclipse.rdf4j.model.impl.LinkedHashModel; import org.eclipse.rdf4j.model.vocabulary.DCTERMS; import org.eclipse.rdf4j.rio.RDFFormat; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; @@ -70,35 +69,26 @@ @Tag(name = "Metadata") @RestController @RequestMapping("/") +@RequiredArgsConstructor public class GenericController { - @Autowired - @Qualifier("persistentUrl") - private String persistentUrl; + private final String persistentUrl; - @Autowired - private MetadataServiceFactory metadataServiceFactory; + private final MetadataServiceFactory metadataServiceFactory; - @Autowired - private ResourceDefinitionService resourceDefinitionService; + private final ResourceDefinitionService resourceDefinitionService; - @Autowired - private MetadataSchemaService metadataSchemaService; + private final MetadataSchemaService metadataSchemaService; - @Autowired - private MetadataEnhancer metadataEnhancer; + private final MetadataEnhancer metadataEnhancer; - @Autowired - private CurrentUserService currentUserService; + private final CurrentUserService currentUserService; - @Autowired - private GenericMetadataRepository metadataRepository; + private final GenericMetadataRepository metadataRepository; - @Autowired - private MetadataStateService metadataStateService; + private final MetadataStateService metadataStateService; - @Autowired - private SearchFilterCache searchFilterCache; + private final SearchFilterCache searchFilterCache; @Operation(hidden = true) @GetMapping(path = {"/spec", "{oUrlPrefix:[^.]+}/spec"}, produces = "!application/json") @@ -107,7 +97,7 @@ public Model getFormMetadata( ) { final String urlPrefix = oUrlPrefix.orElse(""); final ResourceDefinition rd = resourceDefinitionService.getByUrlPrefix(urlPrefix); - return metadataSchemaService.getShaclFromSchemas(rd.getMetadataSchemaUuids()); + return metadataSchemaService.getShaclFromSchemaUsages(rd.getMetadataSchemaUsages()); } @Operation(hidden = true, deprecated = true) @@ -127,7 +117,7 @@ public Model getMetaDataExpanded( final ResourceDefinition rd = resourceDefinitionService.getByUrlPrefix(urlPrefix); // 2. Get entity (from repository based on permissions) - final Optional oCurrentUser = currentUserService.getCurrentUser(); + final Optional oCurrentUser = currentUserService.getCurrentUser(); IRI entityUri = getMetadataIRI(persistentUrl, urlPrefix, recordId); final RepositoryMode mode = oCurrentUser.isEmpty() ? RepositoryMode.MAIN : RepositoryMode.COMBINED; Model entity = metadataService.retrieve(entityUri, mode); @@ -171,7 +161,7 @@ public Model getMetaData( final ResourceDefinition rd = resourceDefinitionService.getByUrlPrefix(urlPrefix); // 3. Get entity (from repository based on permissions) - final Optional oCurrentUser = currentUserService.getCurrentUser(); + final Optional oCurrentUser = currentUserService.getCurrentUser(); final IRI entityUri = getMetadataIRI(persistentUrl, urlPrefix, recordId); final RepositoryMode mode = oCurrentUser.isEmpty() ? RepositoryMode.MAIN : RepositoryMode.COMBINED; final Model entity = metadataService.retrieve(entityUri, mode); @@ -194,7 +184,7 @@ public ResponseEntity storeMetaData( ) throws MetadataServiceException { // 1. Check if user is authenticated // - it can't be in SecurityConfig because the authentication is done based on content-type - final Optional oUser = currentUserService.getCurrentUser(); + final Optional oUser = currentUserService.getCurrentUser(); if (oUser.isEmpty()) { throw new ForbiddenException("You have to be login at first"); } @@ -316,7 +306,7 @@ public ResponseEntity getMetaDataChildren( final MetadataService metadataService = metadataServiceFactory.getMetadataServiceByUrlPrefix(urlPrefix); // 2. Get entity (from repository based on permissions) - final Optional oCurrentUser = currentUserService.getCurrentUser(); + final Optional oCurrentUser = currentUserService.getCurrentUser(); final IRI entityUri = getMetadataIRI(persistentUrl, urlPrefix, recordId); final RepositoryMode mode = oCurrentUser.isEmpty() ? RepositoryMode.MAIN : RepositoryMode.COMBINED; final Model entity = metadataService.retrieve(entityUri, mode); @@ -327,7 +317,7 @@ public ResponseEntity getMetaDataChildren( final MetadataService childMetadataService = metadataServiceFactory.getMetadataServiceByUrlPrefix(childPrefix); for (ResourceDefinitionChild rdChild : rd.getChildren()) { - if (rdChild.getResourceDefinitionUuid().equals(currentChildRd.getUuid())) { + if (rdChild.getTarget().getUuid().equals(currentChildRd.getUuid())) { final IRI relationUri = i(rdChild.getRelationUri()); // 3.1 Get all titles for sort diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/metadata/GenericMemberController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/metadata/GenericMemberController.java index dc11e8fcf..f172a0cb7 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/metadata/GenericMemberController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/metadata/GenericMemberController.java @@ -25,6 +25,7 @@ import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.member.MemberCreateDTO; import nl.dtls.fairdatapoint.api.dto.member.MemberDTO; import nl.dtls.fairdatapoint.entity.exception.ResourceNotFoundException; @@ -35,31 +36,27 @@ import nl.dtls.fairdatapoint.service.metadata.factory.MetadataServiceFactory; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.List; +import java.util.UUID; import static nl.dtls.fairdatapoint.entity.metadata.MetadataGetter.getMetadataIdentifier; import static nl.dtls.fairdatapoint.util.HttpUtil.getMetadataIRI; @Tag(name = "Authentication and Authorization") @RestController +@RequiredArgsConstructor public class GenericMemberController { - @Autowired - @Qualifier("persistentUrl") - private String persistentUrl; + private final String persistentUrl; - @Autowired - private MemberService memberService; + private final MemberService memberService; - @Autowired - private MetadataServiceFactory metadataServiceFactory; + private final MetadataServiceFactory metadataServiceFactory; @Operation(hidden = true) @GetMapping(path = "{urlPrefix:[^.]+}/{recordId:[^.]+}/members", produces = MediaType.APPLICATION_JSON_VALUE) @@ -88,7 +85,7 @@ public ResponseEntity> getMembers( public ResponseEntity putMember( @PathVariable final String urlPrefix, @PathVariable final String recordId, - @PathVariable final String userUuid, + @PathVariable final UUID userUuid, @RequestBody @Valid MemberCreateDTO reqBody ) throws MetadataServiceException { // 1. Init @@ -101,7 +98,7 @@ public ResponseEntity putMember( // 3. Create / Update member final String entityId = getMetadataIdentifier(metadata).getIdentifier().getLabel(); final MemberDTO dto = memberService.createOrUpdateMember(entityId, Metadata.class, userUuid, - reqBody.getMembershipUuid()); + UUID.fromString(reqBody.getMembershipUuid())); return new ResponseEntity<>(dto, HttpStatus.OK); } @@ -111,7 +108,7 @@ public ResponseEntity putMember( public ResponseEntity deleteMember( @PathVariable final String urlPrefix, @PathVariable final String recordId, - @PathVariable final String userUuid + @PathVariable final UUID userUuid ) throws ResourceNotFoundException, MetadataServiceException { // 1. Init final MetadataService metadataService = metadataServiceFactory.getMetadataServiceByUrlPrefix(urlPrefix); diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/metadata/GenericMetaController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/metadata/GenericMetaController.java index f2413c885..269bdb064 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/metadata/GenericMetaController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/metadata/GenericMetaController.java @@ -25,6 +25,7 @@ import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.member.MemberDTO; import nl.dtls.fairdatapoint.api.dto.metadata.MetaDTO; import nl.dtls.fairdatapoint.api.dto.metadata.MetaPathDTO; @@ -33,7 +34,7 @@ import nl.dtls.fairdatapoint.database.rdf.repository.RepositoryMode; import nl.dtls.fairdatapoint.entity.metadata.Metadata; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; -import nl.dtls.fairdatapoint.entity.user.User; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import nl.dtls.fairdatapoint.service.member.MemberService; import nl.dtls.fairdatapoint.service.metadata.common.MetadataService; import nl.dtls.fairdatapoint.service.metadata.exception.MetadataServiceException; @@ -44,8 +45,6 @@ import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.vocabulary.DCTERMS; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.web.bind.annotation.*; import java.util.HashMap; @@ -60,28 +59,22 @@ @Tag(name = "Metadata") @RestController +@RequiredArgsConstructor public class GenericMetaController { private static final int SUPPORTED_URL_FRAGMENTS = 3; - @Autowired - @Qualifier("persistentUrl") - private String persistentUrl; + private final String persistentUrl; - @Autowired - private MemberService memberService; + private final MemberService memberService; - @Autowired - private MetadataServiceFactory metadataServiceFactory; + private final MetadataServiceFactory metadataServiceFactory; - @Autowired - private MetadataStateService metadataStateService; + private final MetadataStateService metadataStateService; - @Autowired - private ResourceDefinitionService resourceDefinitionService; + private final ResourceDefinitionService resourceDefinitionService; - @Autowired - private CurrentUserService currentUserService; + private final CurrentUserService currentUserService; @Operation(hidden = true) @GetMapping(path = {"meta", "{oUrlPrefix:[^.]+}/{oRecordId:[^.]+}/meta"}) @@ -99,7 +92,7 @@ public MetaDTO getMeta( ResourceDefinition definition = resourceDefinitionService.getByUrlPrefix(urlPrefix); // 3. Get and check existence entity - final Optional oCurrentUser = currentUserService.getCurrentUser(); + final Optional oCurrentUser = currentUserService.getCurrentUser(); final RepositoryMode mode = oCurrentUser.isEmpty() ? RepositoryMode.MAIN : RepositoryMode.COMBINED; IRI entityUri = getMetadataIRI(persistentUrl, urlPrefix, recordId); Model entity = metadataService.retrieve(entityUri, mode); @@ -117,7 +110,7 @@ public MetaDTO getMeta( final Map pathMap = new HashMap<>(); while (true) { final MetaPathDTO entry = new MetaPathDTO(); - entry.setResourceDefinitionUuid(definition.getUuid()); + entry.setResourceDefinitionUuid(definition.getUuid().toString()); entry.setTitle(getTitle(entity).stringValue()); final IRI parentUri = i(getStringObjectBy(entity, entityUri, DCTERMS.IS_PART_OF)); Optional.ofNullable(parentUri).map(IRI::toString).ifPresent(entry::setParent); diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/profile/ProfileController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/profile/ProfileController.java index d95c3ddd2..e453414be 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/profile/ProfileController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/profile/ProfileController.java @@ -24,17 +24,17 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.entity.exception.ResourceNotFoundException; import nl.dtls.fairdatapoint.service.profile.ProfileService; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import java.util.Optional; +import java.util.UUID; import static java.lang.String.format; import static nl.dtls.fairdatapoint.util.HttpUtil.getRequestURL; @@ -43,14 +43,12 @@ @Tag(name = "Client") @RestController @RequestMapping("/profile") +@RequiredArgsConstructor public class ProfileController { - @Autowired - @Qualifier("persistentUrl") - private String persistentUrl; + private final String persistentUrl; - @Autowired - private ProfileService profileService; + private final ProfileService profileService; @GetMapping(path = "/{uuid}", produces = { "text/turtle", @@ -64,7 +62,7 @@ public class ProfileController { }) public ResponseEntity getSchemaContent( HttpServletRequest request, - @PathVariable final String uuid + @PathVariable final UUID uuid ) throws ResourceNotFoundException { final IRI uri = i(getRequestURL(request, persistentUrl)); final Optional oDto = profileService.getProfileByUuid(uuid, uri); diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/reset/ResetController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/reset/ResetController.java index 9a90afa80..d9de2f2ea 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/reset/ResetController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/reset/ResetController.java @@ -24,9 +24,9 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.reset.ResetDTO; import nl.dtls.fairdatapoint.service.reset.ResetService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; @@ -37,10 +37,10 @@ @Tag(name = "Client") @RestController +@RequiredArgsConstructor public class ResetController { - @Autowired - private ResetService resetService; + private final ResetService resetService; @PostMapping("/reset") @PreAuthorize("hasRole('ADMIN')") diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/resource/ResourceDefinitionController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/resource/ResourceDefinitionController.java index a06177e45..2854781db 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/resource/ResourceDefinitionController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/resource/ResourceDefinitionController.java @@ -24,11 +24,11 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.resource.ResourceDefinitionChangeDTO; import nl.dtls.fairdatapoint.api.dto.resource.ResourceDefinitionDTO; import nl.dtls.fairdatapoint.entity.exception.ResourceNotFoundException; import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -37,18 +37,19 @@ import java.util.List; import java.util.Optional; +import java.util.UUID; import static java.lang.String.format; @Tag(name = "Metadata Model") @RestController @RequestMapping("/resource-definitions") +@RequiredArgsConstructor public class ResourceDefinitionController { private static final String NOT_FOUND_MSG = "Resource Definition '%s' doesn't exist"; - @Autowired - private ResourceDefinitionService resourceDefinitionService; + private final ResourceDefinitionService resourceDefinitionService; @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity> getResourceDefinitions() { @@ -66,7 +67,7 @@ public ResponseEntity createResourceDefinitions( @GetMapping(path = "/{uuid}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity getResourceDefinition( - @PathVariable final String uuid + @PathVariable final UUID uuid ) throws ResourceNotFoundException { final Optional oDto = resourceDefinitionService.getDTOByUuid(uuid); if (oDto.isPresent()) { @@ -79,7 +80,7 @@ public ResponseEntity getResourceDefinition( @PutMapping(path = "/{uuid}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity putResourceDefinitions( - @PathVariable final String uuid, + @PathVariable final UUID uuid, @RequestBody @Valid ResourceDefinitionChangeDTO reqDto ) throws ResourceNotFoundException, BindException { final Optional oDto = resourceDefinitionService.update(uuid, reqDto); @@ -93,7 +94,7 @@ public ResponseEntity putResourceDefinitions( @DeleteMapping(path = "/{uuid}") @ResponseStatus(HttpStatus.NO_CONTENT) - public ResponseEntity deleteResourceDefinitions(@PathVariable final String uuid) + public ResponseEntity deleteResourceDefinitions(@PathVariable final UUID uuid) throws ResourceNotFoundException { final boolean result = resourceDefinitionService.deleteByUuid(uuid); if (result) { diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/schema/MetadataSchemaController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/schema/MetadataSchemaController.java index b673af403..5ad03b110 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/schema/MetadataSchemaController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/schema/MetadataSchemaController.java @@ -24,13 +24,13 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.schema.*; import nl.dtls.fairdatapoint.entity.exception.ResourceNotFoundException; import nl.dtls.fairdatapoint.entity.exception.UnauthorizedException; import nl.dtls.fairdatapoint.service.schema.MetadataSchemaService; import nl.dtls.fairdatapoint.service.user.CurrentUserService; import org.eclipse.rdf4j.model.Model; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -39,12 +39,14 @@ import java.util.List; import java.util.Optional; +import java.util.UUID; import static java.lang.String.format; @Tag(name = "Metadata Model") @RestController @RequestMapping("/metadata-schemas") +@RequiredArgsConstructor public class MetadataSchemaController { private static final String NOT_FOUND_MSG = @@ -52,11 +54,9 @@ public class MetadataSchemaController { private static final String NOT_FOUND_VERSION_MSG = "Metadata Schema '%s' doesn't exist with version '%s'"; - @Autowired - private MetadataSchemaService metadataSchemaService; + private final MetadataSchemaService metadataSchemaService; - @Autowired - private CurrentUserService currentUserService; + private final CurrentUserService currentUserService; @GetMapping(path = "", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity> getSchemas( @@ -81,7 +81,7 @@ else if (includeDrafts) { } @GetMapping(path = "/{uuid}", produces = MediaType.APPLICATION_JSON_VALUE) - public ResponseEntity getSchema(@PathVariable final String uuid) + public ResponseEntity getSchema(@PathVariable final UUID uuid) throws ResourceNotFoundException { final Optional oDto = metadataSchemaService.getSchemaByUuid(uuid); if (oDto.isPresent()) { @@ -102,7 +102,7 @@ public ResponseEntity getSchema(@PathVariable final String uu "application/xml", "text/xml" }) - public ResponseEntity getSchemaContent(@PathVariable final String uuid) + public ResponseEntity getSchemaContent(@PathVariable final UUID uuid) throws ResourceNotFoundException { final Optional oDto = metadataSchemaService.getSchemaContentByUuid(uuid); if (oDto.isPresent()) { @@ -116,7 +116,7 @@ public ResponseEntity getSchemaContent(@PathVariable final String uuid) @DeleteMapping(path = "/{uuid}") @ResponseStatus(HttpStatus.NO_CONTENT) public ResponseEntity deleteSchemaFull( - @PathVariable final String uuid + @PathVariable final UUID uuid ) throws ResourceNotFoundException { final boolean result = metadataSchemaService.deleteSchemaFull(uuid); if (result) { @@ -139,7 +139,7 @@ public ResponseEntity createSchemaDraft( @PreAuthorize("hasRole('ADMIN')") @GetMapping(path = "/{uuid}/draft", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity getSchemaDraft( - @PathVariable final String uuid + @PathVariable final UUID uuid ) throws ResourceNotFoundException { final Optional oDto = metadataSchemaService.getSchemaDraft(uuid); if (oDto.isPresent()) { @@ -153,7 +153,7 @@ public ResponseEntity getSchemaDraft( @PreAuthorize("hasRole('ADMIN')") @PutMapping(path = "/{uuid}/draft", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity updateSchemaDraft( - @PathVariable final String uuid, + @PathVariable final UUID uuid, @RequestBody @Valid MetadataSchemaChangeDTO reqDto ) throws ResourceNotFoundException { final Optional oDto = @@ -169,7 +169,7 @@ public ResponseEntity updateSchemaDraft( @PreAuthorize("hasRole('ADMIN')") @DeleteMapping(path = "/{uuid}/draft") @ResponseStatus(HttpStatus.NO_CONTENT) - public ResponseEntity deleteSchemaDraft(@PathVariable final String uuid) + public ResponseEntity deleteSchemaDraft(@PathVariable final UUID uuid) throws ResourceNotFoundException { final boolean result = metadataSchemaService.deleteSchemaDraft(uuid); if (result) { @@ -184,7 +184,7 @@ public ResponseEntity deleteSchemaDraft(@PathVariable final String uuid) @PostMapping(path = "/{uuid}/versions") @ResponseStatus(HttpStatus.NO_CONTENT) public ResponseEntity releaseSchemaVersion( - @PathVariable final String uuid, + @PathVariable final UUID uuid, @RequestBody @Valid MetadataSchemaReleaseDTO reqDto ) throws ResourceNotFoundException { final Optional oDto = metadataSchemaService.releaseDraft(uuid, reqDto); @@ -199,7 +199,7 @@ public ResponseEntity releaseSchemaVersion( @PreAuthorize("hasRole('ADMIN')") @GetMapping(path = "/{uuid}/versions/{version}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity getSchemaVersion( - @PathVariable final String uuid, + @PathVariable final UUID uuid, @PathVariable final String version ) throws ResourceNotFoundException { final Optional oDto = @@ -215,7 +215,7 @@ public ResponseEntity getSchemaVersion( @PreAuthorize("hasRole('ADMIN')") @PutMapping(path = "/{uuid}/versions/{version}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity updateSchemaVersion( - @PathVariable final String uuid, + @PathVariable final UUID uuid, @PathVariable final String version, @RequestBody @Valid MetadataSchemaUpdateDTO reqDto ) throws ResourceNotFoundException { @@ -233,7 +233,7 @@ public ResponseEntity updateSchemaVersion( @DeleteMapping(path = "/{uuid}/versions/{version}") @ResponseStatus(HttpStatus.NO_CONTENT) public ResponseEntity deleteSchemaVersion( - @PathVariable final String uuid, + @PathVariable final UUID uuid, @PathVariable final String version ) throws ResourceNotFoundException { final boolean result = metadataSchemaService.deleteVersion(uuid, version); diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/search/SearchController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/search/SearchController.java index e0eda44d4..9dab294a8 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/search/SearchController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/search/SearchController.java @@ -24,11 +24,11 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.search.*; import nl.dtls.fairdatapoint.database.rdf.repository.exception.MetadataRepositoryException; import nl.dtls.fairdatapoint.service.search.SearchService; import org.eclipse.rdf4j.query.MalformedQueryException; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.security.access.prepost.PreAuthorize; @@ -39,10 +39,10 @@ @Tag(name = "Search") @RestController @RequestMapping("/search") +@RequiredArgsConstructor public class SearchController { - @Autowired - private SearchService searchService; + private final SearchService searchService; @PostMapping( path = "", diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/search/SearchSavedQueryController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/search/SearchSavedQueryController.java index f9c3fd837..d27fa8fb5 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/search/SearchSavedQueryController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/search/SearchSavedQueryController.java @@ -24,6 +24,7 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.search.SearchResultDTO; import nl.dtls.fairdatapoint.api.dto.search.SearchSavedQueryChangeDTO; import nl.dtls.fairdatapoint.api.dto.search.SearchSavedQueryDTO; @@ -31,7 +32,6 @@ import nl.dtls.fairdatapoint.entity.exception.ResourceNotFoundException; import nl.dtls.fairdatapoint.service.search.SearchService; import nl.dtls.fairdatapoint.service.search.query.SearchSavedQueryService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -40,21 +40,21 @@ import java.util.List; import java.util.Optional; +import java.util.UUID; import static java.lang.String.format; @Tag(name = "Search") @RestController @RequestMapping("/search/query/saved") +@RequiredArgsConstructor public class SearchSavedQueryController { private static final String NOT_FOUND_MSG = "Saved query '%s' doesn't exist"; - @Autowired - private SearchSavedQueryService searchSavedQueryService; + private final SearchSavedQueryService searchSavedQueryService; - @Autowired - private SearchService searchService; + private final SearchService searchService; @GetMapping(path = "", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity> getAll() { @@ -63,7 +63,7 @@ public ResponseEntity> getAll() { @GetMapping(path = "/{uuid}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity getSingle( - @PathVariable final String uuid + @PathVariable final UUID uuid ) throws ResourceNotFoundException { final Optional oDto = searchSavedQueryService.getSingle(uuid); if (oDto.isPresent()) { @@ -76,7 +76,7 @@ public ResponseEntity getSingle( @PostMapping(path = "/{uuid}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity> search( - @PathVariable final String uuid + @PathVariable final UUID uuid ) throws ResourceNotFoundException, MetadataRepositoryException { final Optional oDto = searchSavedQueryService.getSingle(uuid); if (oDto.isPresent()) { @@ -99,7 +99,7 @@ public ResponseEntity create( @PreAuthorize("isAuthenticated()") @PutMapping(path = "/{uuid}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity update( - @PathVariable final String uuid, + @PathVariable final UUID uuid, @RequestBody @Valid SearchSavedQueryChangeDTO reqDto ) { final Optional oDto = searchSavedQueryService.update(uuid, reqDto); @@ -115,7 +115,7 @@ public ResponseEntity update( @DeleteMapping(path = "/{uuid}") @ResponseStatus(HttpStatus.NO_CONTENT) public ResponseEntity delete( - @PathVariable final String uuid + @PathVariable final UUID uuid ) throws ResourceNotFoundException { final boolean result = searchSavedQueryService.delete(uuid); if (result) { diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/settings/SettingsDefaults.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/settings/SettingsDefaults.java new file mode 100644 index 000000000..ce47b9054 --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/settings/SettingsDefaults.java @@ -0,0 +1,79 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.api.controller.settings; + +import lombok.RequiredArgsConstructor; +import nl.dtls.fairdatapoint.config.properties.PingProperties; +import nl.dtls.fairdatapoint.entity.settings.Settings; +import nl.dtls.fairdatapoint.entity.settings.SettingsMetric; +import nl.dtls.fairdatapoint.util.KnownUUIDs; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.UUID; + +@Component +@RequiredArgsConstructor +public class SettingsDefaults { + + private final PingProperties pingProperties; + + public Settings getDefaults() { + final Settings settings = defaultSettings(); + settings.setMetrics(defaultMetrics(settings)); + return settings; + } + + public Settings defaultSettings() { + return Settings.builder() + .uuid(KnownUUIDs.SETTINGS_UUID) + .appTitle(null) + .appSubtitle(null) + .pingEnabled(pingProperties.isEnabled()) + .pingEndpoints(List.of()) + .autocompleteSearchNamespace(true) + .autocompleteSources(List.of()) + .metrics(List.of()) + .searchFilters(List.of()) + .build(); + } + + public List defaultMetrics(Settings settings) { + return List.of( + SettingsMetric.builder() + .uuid(UUID.randomUUID()) + .metricUri("https://purl.org/fair-metrics/FM_F1A") + .resourceUri("https://www.ietf.org/rfc/rfc3986.txt") + .settings(settings) + .orderPriority(1) + .build(), + SettingsMetric.builder() + .uuid(UUID.randomUUID()) + .metricUri("https://purl.org/fair-metrics/FM_A1.1") + .resourceUri("https://www.wikidata.org/wiki/Q8777") + .settings(settings) + .orderPriority(2) + .build() + ); + } +} diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/token/TokenController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/token/TokenController.java index e1cbe6c2c..b4b2e71fc 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/token/TokenController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/token/TokenController.java @@ -24,10 +24,10 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.auth.AuthDTO; import nl.dtls.fairdatapoint.api.dto.auth.TokenDTO; import nl.dtls.fairdatapoint.service.jwt.JwtService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -38,10 +38,10 @@ @Tag(name = "Authentication and Authorization") @RestController @RequestMapping("/tokens") +@RequiredArgsConstructor public class TokenController { - @Autowired - private JwtService jwtService; + private final JwtService jwtService; @PostMapping(produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity generateToken(@RequestBody @Valid AuthDTO reqDto) { diff --git a/src/main/java/nl/dtls/fairdatapoint/api/controller/user/UserController.java b/src/main/java/nl/dtls/fairdatapoint/api/controller/user/UserController.java index e61bd9b41..0dae24c62 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/controller/user/UserController.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/controller/user/UserController.java @@ -24,11 +24,11 @@ import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.user.*; import nl.dtls.fairdatapoint.entity.exception.ForbiddenException; import nl.dtls.fairdatapoint.entity.exception.ResourceNotFoundException; import nl.dtls.fairdatapoint.service.user.UserService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; @@ -36,20 +36,21 @@ import java.util.List; import java.util.Optional; +import java.util.UUID; import static java.lang.String.format; @Tag(name = "User Management") @RestController @RequestMapping("/users") +@RequiredArgsConstructor public class UserController { private static final String LOGIN_FIRST_MSG = "You have to be login at first"; private static final String NOT_FOUND_MSG = "User '%s' doesn't exist"; - @Autowired - private UserService userService; + private final UserService userService; @GetMapping(produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity> getUsers() { @@ -66,7 +67,7 @@ public ResponseEntity createUser(@RequestBody @Valid UserCreateDTO reqD @Tag(name = "Authentication and Authorization") @GetMapping(path = "/current", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity getUserCurrent() throws ResourceNotFoundException { - final Optional oDto = userService.getCurrentUser(); + final Optional oDto = userService.getCurrentUserDto(); if (oDto.isPresent()) { return new ResponseEntity<>(oDto.get(), HttpStatus.OK); } @@ -77,9 +78,9 @@ public ResponseEntity getUserCurrent() throws ResourceNotFoundException @GetMapping(path = "/{uuid}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity getUser( - @PathVariable final String uuid + @PathVariable final UUID uuid ) throws ResourceNotFoundException { - final Optional oDto = userService.getUserByUuid(uuid); + final Optional oDto = userService.getUserDtoByUuid(uuid); if (oDto.isPresent()) { return new ResponseEntity<>(oDto.get(), HttpStatus.OK); } @@ -103,7 +104,7 @@ public ResponseEntity putUserCurrent( @PutMapping(path = "/{uuid}", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity putUser( - @PathVariable final String uuid, + @PathVariable final UUID uuid, @RequestBody @Valid UserChangeDTO reqDto ) throws ResourceNotFoundException { final Optional oDto = userService.updateUser(uuid, reqDto); @@ -130,7 +131,7 @@ public ResponseEntity putUserCurrentPassword( @PutMapping(path = "/{uuid}/password", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity putUserPassword( - @PathVariable final String uuid, + @PathVariable final UUID uuid, @RequestBody @Valid UserPasswordDTO reqDto ) throws ResourceNotFoundException { final Optional oDto = userService.updatePassword(uuid, reqDto); @@ -145,7 +146,7 @@ public ResponseEntity putUserPassword( @DeleteMapping("/{uuid}") @ResponseStatus(HttpStatus.NO_CONTENT) public ResponseEntity deleteUser( - @PathVariable final String uuid + @PathVariable final UUID uuid ) throws ResourceNotFoundException { final boolean result = userService.deleteUser(uuid); if (result) { diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/apikey/ApiKeyDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/apikey/ApiKeyDTO.java index 171c09f78..e81c1e452 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/apikey/ApiKeyDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/apikey/ApiKeyDTO.java @@ -24,6 +24,8 @@ import lombok.*; +import java.util.UUID; + @NoArgsConstructor @AllArgsConstructor @Getter @@ -31,8 +33,7 @@ @EqualsAndHashCode public class ApiKeyDTO { - private String uuid; + private UUID uuid; private String token; - } diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/index/entry/IndexEntryDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/index/entry/IndexEntryDTO.java index ba6c9dac7..8f3dc6cf2 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/index/entry/IndexEntryDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/index/entry/IndexEntryDTO.java @@ -30,6 +30,8 @@ import nl.dtls.fairdatapoint.entity.index.entry.IndexEntryPermit; import org.hibernate.validator.constraints.URL; +import java.util.UUID; + @NoArgsConstructor @AllArgsConstructor @Getter @@ -37,7 +39,7 @@ public class IndexEntryDTO { @NotNull - private String uuid; + private UUID uuid; @NotNull @URL diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/index/entry/IndexEntryDetailDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/index/entry/IndexEntryDetailDTO.java index 67bf2865c..2b65e23b1 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/index/entry/IndexEntryDetailDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/index/entry/IndexEntryDetailDTO.java @@ -33,6 +33,7 @@ import org.hibernate.validator.constraints.URL; import java.util.List; +import java.util.UUID; @NoArgsConstructor @AllArgsConstructor @@ -41,7 +42,7 @@ public class IndexEntryDetailDTO { @NotNull - private String uuid; + private UUID uuid; @NotNull @URL diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/index/event/EventDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/index/event/EventDTO.java index 3b5ab5891..718b44f60 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/index/event/EventDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/index/event/EventDTO.java @@ -27,7 +27,7 @@ import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; -import nl.dtls.fairdatapoint.entity.index.event.EventType; +import nl.dtls.fairdatapoint.entity.index.event.IndexEventType; import java.util.UUID; @@ -41,7 +41,7 @@ public class EventDTO { private UUID uuid; @NotNull - private EventType type; + private IndexEventType type; @NotNull private String created; diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/index/webhook/WebhookPayloadDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/index/webhook/WebhookPayloadDTO.java index bd2a68200..531ea5d75 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/index/webhook/WebhookPayloadDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/index/webhook/WebhookPayloadDTO.java @@ -24,12 +24,12 @@ import lombok.Data; import lombok.NoArgsConstructor; -import nl.dtls.fairdatapoint.entity.index.webhook.WebhookEvent; +import nl.dtls.fairdatapoint.entity.index.webhook.IndexWebhookEvent; @Data @NoArgsConstructor public class WebhookPayloadDTO { - private WebhookEvent event; + private IndexWebhookEvent event; private String uuid; private String clientUrl; private String timestamp; diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/membership/MembershipDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/membership/MembershipDTO.java index 69798d0d5..60dfe160a 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/membership/MembershipDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/membership/MembershipDTO.java @@ -26,12 +26,13 @@ import lombok.Data; import java.util.List; +import java.util.UUID; @Data @AllArgsConstructor public class MembershipDTO { - private String uuid; + private UUID uuid; private String name; diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionChangeDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionChangeDTO.java index 0e597bbda..083b16b4c 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionChangeDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionChangeDTO.java @@ -25,19 +25,15 @@ import jakarta.validation.Valid; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import nl.dtls.fairdatapoint.entity.resource.ResourceDefinitionChild; -import nl.dtls.fairdatapoint.entity.resource.ResourceDefinitionLink; +import lombok.*; import java.util.List; +import java.util.UUID; +@Data @NoArgsConstructor @AllArgsConstructor -@Getter -@Setter +@Builder public class ResourceDefinitionChangeDTO { @NotBlank @@ -47,13 +43,13 @@ public class ResourceDefinitionChangeDTO { private String urlPrefix; @NotNull - private List metadataSchemaUuids; + private List metadataSchemaUuids; @NotNull @Valid - private List children; + private List children; @NotNull @Valid - private List externalLinks; + private List externalLinks; } diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionChildDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionChildDTO.java new file mode 100644 index 000000000..fd052204a --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionChildDTO.java @@ -0,0 +1,50 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.api.dto.resource; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.NotBlank; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import nl.dtls.fairdatapoint.api.validator.ValidIri; + +import java.util.UUID; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class ResourceDefinitionChildDTO { + + @NotBlank + private UUID resourceDefinitionUuid; + + @NotBlank + @ValidIri + private String relationUri; + + @Valid + private ResourceDefinitionChildListViewDTO listView; +} diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinitionChildListView.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionChildListViewDTO.java similarity index 82% rename from src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinitionChildListView.java rename to src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionChildListViewDTO.java index 0bc74d203..c15ad0d50 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinitionChildListView.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionChildListViewDTO.java @@ -20,22 +20,23 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.entity.resource; +package nl.dtls.fairdatapoint.api.dto.resource; import jakarta.validation.Valid; import jakarta.validation.constraints.NotBlank; -import lombok.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; import nl.dtls.fairdatapoint.api.validator.ValidIri; import java.util.List; +@Data @NoArgsConstructor @AllArgsConstructor -@Getter -@Setter -@EqualsAndHashCode -@Builder(toBuilder = true) -public class ResourceDefinitionChildListView { +@Builder +public class ResourceDefinitionChildListViewDTO { @NotBlank private String title; @@ -44,6 +45,5 @@ public class ResourceDefinitionChildListView { private String tagsUri; @Valid - private List metadata; - + private List metadata; } diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionChildListViewMetadataDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionChildListViewMetadataDTO.java new file mode 100644 index 000000000..e3189655c --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionChildListViewMetadataDTO.java @@ -0,0 +1,44 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.api.dto.resource; + +import jakarta.validation.constraints.NotBlank; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; +import nl.dtls.fairdatapoint.api.validator.ValidIri; + +@Data +@NoArgsConstructor +@AllArgsConstructor +@Builder +public class ResourceDefinitionChildListViewMetadataDTO { + + @NotBlank + private String title; + + @NotBlank + @ValidIri + private String propertyUri; +} diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionDTO.java index f05724cde..2f1480832 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionDTO.java @@ -25,23 +25,20 @@ import jakarta.validation.Valid; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; -import nl.dtls.fairdatapoint.entity.resource.ResourceDefinitionChild; -import nl.dtls.fairdatapoint.entity.resource.ResourceDefinitionLink; +import lombok.*; import java.util.List; +import java.util.UUID; @NoArgsConstructor @AllArgsConstructor @Getter @Setter +@Builder public class ResourceDefinitionDTO { @NotBlank - private String uuid; + private UUID uuid; @NotBlank private String name; @@ -50,16 +47,16 @@ public class ResourceDefinitionDTO { private String urlPrefix; @NotNull - private List metadataSchemaUuids; + private List metadataSchemaUuids; @NotNull private List targetClassUris; @NotNull @Valid - private List children; + private List children; @NotNull @Valid - private List externalLinks; + private List externalLinks; } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinitionChildListViewMetadata.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionLinkDTO.java similarity index 86% rename from src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinitionChildListViewMetadata.java rename to src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionLinkDTO.java index 983eb78c2..e107d529d 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinitionChildListViewMetadata.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/resource/ResourceDefinitionLinkDTO.java @@ -20,18 +20,20 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.entity.resource; +package nl.dtls.fairdatapoint.api.dto.resource; import jakarta.validation.constraints.NotBlank; -import lombok.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; import nl.dtls.fairdatapoint.api.validator.ValidIri; +@Data @NoArgsConstructor @AllArgsConstructor -@Getter -@Setter -@EqualsAndHashCode -public class ResourceDefinitionChildListViewMetadata { +@Builder +public class ResourceDefinitionLinkDTO { @NotBlank private String title; @@ -39,5 +41,4 @@ public class ResourceDefinitionChildListViewMetadata { @NotBlank @ValidIri private String propertyUri; - } diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaChangeDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaChangeDTO.java index 3d7cb4763..fa91645b6 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaChangeDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaChangeDTO.java @@ -27,6 +27,7 @@ import lombok.*; import java.util.List; +import java.util.UUID; @NoArgsConstructor @AllArgsConstructor @@ -48,7 +49,7 @@ public class MetadataSchemaChangeDTO { private String definition; @NotNull - private List extendsSchemaUuids; + private List extendsSchemaUuids; private String suggestedResourceName; diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaDTO.java index c35e8427a..6c99b6767 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaDTO.java @@ -28,6 +28,7 @@ import lombok.*; import java.util.List; +import java.util.UUID; @NoArgsConstructor @AllArgsConstructor @@ -38,7 +39,7 @@ public class MetadataSchemaDTO { @NotNull @NotBlank - private String uuid; + private UUID uuid; @NotNull @NotBlank @@ -54,8 +55,8 @@ public class MetadataSchemaDTO { private List versions; @NotNull - private List extendSchemaUuids; + private List extendSchemaUuids; @NotNull - private List childSchemaUuids; + private List childSchemaUuids; } diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaDraftDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaDraftDTO.java index 5a6734ef8..4812e4f85 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaDraftDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaDraftDTO.java @@ -28,6 +28,7 @@ import lombok.*; import java.util.List; +import java.util.UUID; @NoArgsConstructor @AllArgsConstructor @@ -38,7 +39,7 @@ public class MetadataSchemaDraftDTO { @NotNull @NotBlank - private String uuid; + private UUID uuid; @NotNull @NotBlank @@ -53,7 +54,7 @@ public class MetadataSchemaDraftDTO { private String definition; @NotNull - private List extendsSchemaUuids; + private List extendsSchemaUuids; @JsonInclude(JsonInclude.Include.ALWAYS) private String suggestedResourceName; diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaPreviewRequestDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaPreviewRequestDTO.java index a22287a1f..7dfc039d5 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaPreviewRequestDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaPreviewRequestDTO.java @@ -29,6 +29,7 @@ import lombok.Setter; import java.util.List; +import java.util.UUID; @NoArgsConstructor @AllArgsConstructor @@ -37,5 +38,5 @@ public class MetadataSchemaPreviewRequestDTO { @NotNull - private List metadataSchemaUuids; + private List metadataSchemaUuids; } diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaVersionDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaVersionDTO.java index 99943e32d..6e4b81739 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaVersionDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/schema/MetadataSchemaVersionDTO.java @@ -29,7 +29,7 @@ import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaType; import java.util.List; -import java.util.Set; +import java.util.UUID; @NoArgsConstructor @AllArgsConstructor @@ -39,17 +39,16 @@ public class MetadataSchemaVersionDTO { @NotNull - @NotBlank - private String uuid; + private UUID uuid; @JsonInclude(JsonInclude.Include.ALWAYS) private String version; @JsonInclude(JsonInclude.Include.ALWAYS) - private String versionUuid; + private UUID versionUuid; @JsonInclude(JsonInclude.Include.ALWAYS) - private String previousVersionUuid; + private UUID previousVersionUuid; @NotNull @NotBlank @@ -77,10 +76,10 @@ public class MetadataSchemaVersionDTO { private String description; @NotNull - private Set targetClasses; + private List targetClasses; @NotNull - private List extendsSchemaUuids; + private List extendsSchemaUuids; @JsonInclude(JsonInclude.Include.ALWAYS) private String suggestedResourceName; diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/search/SearchSavedQueryDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/search/SearchSavedQueryDTO.java index 423ee724f..0d4928838 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/search/SearchSavedQueryDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/search/SearchSavedQueryDTO.java @@ -31,6 +31,7 @@ import nl.dtls.fairdatapoint.entity.search.SearchSavedQueryType; import java.time.Instant; +import java.util.UUID; @NoArgsConstructor @AllArgsConstructor @@ -40,7 +41,7 @@ public class SearchSavedQueryDTO { @NotBlank - private String uuid; + private UUID uuid; @NotBlank private String name; diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/settings/SettingsDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/settings/SettingsDTO.java index cdba5d5d4..e8d10b073 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/settings/SettingsDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/settings/SettingsDTO.java @@ -24,7 +24,6 @@ import com.fasterxml.jackson.annotation.JsonInclude; import lombok.*; -import nl.dtls.fairdatapoint.entity.settings.SettingsMetricsEntry; import java.util.List; @@ -49,7 +48,7 @@ public class SettingsDTO { private String appSubtitleFromConfig; - private List metadataMetrics; + private List metadataMetrics; private SettingsPingDTO ping; diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsMetricsEntry.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/settings/SettingsMetricDTO.java similarity index 85% rename from src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsMetricsEntry.java rename to src/main/java/nl/dtls/fairdatapoint/api/dto/settings/SettingsMetricDTO.java index 552afaae6..e37c61480 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsMetricsEntry.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/settings/SettingsMetricDTO.java @@ -20,20 +20,16 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.entity.settings; +package nl.dtls.fairdatapoint.api.dto.settings; -import lombok.*; +import lombok.Builder; +import lombok.Data; -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -@EqualsAndHashCode -@Builder(toBuilder = true) -public class SettingsMetricsEntry { +@Data +@Builder +public class SettingsMetricDTO { private String metricUri; private String resourceUri; - } diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/settings/SettingsUpdateDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/settings/SettingsUpdateDTO.java index 7607b9906..e14675a89 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/settings/SettingsUpdateDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/settings/SettingsUpdateDTO.java @@ -24,7 +24,6 @@ import jakarta.validation.constraints.NotNull; import lombok.*; -import nl.dtls.fairdatapoint.entity.settings.SettingsMetricsEntry; import java.util.List; @@ -40,7 +39,7 @@ public class SettingsUpdateDTO { private String appSubtitle; @NotNull - private List metadataMetrics; + private List metadataMetrics; @NotNull private SettingsPingUpdateDTO ping; diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/user/UserChangeDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/user/UserChangeDTO.java index c8dd11e92..838f878ef 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/user/UserChangeDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/user/UserChangeDTO.java @@ -24,16 +24,14 @@ import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; +import lombok.*; import nl.dtls.fairdatapoint.entity.user.UserRole; @NoArgsConstructor @AllArgsConstructor @Getter @Setter +@Builder public class UserChangeDTO { @NotBlank diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/user/UserCreateDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/user/UserCreateDTO.java index 4e2dc15ba..610d7d428 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/user/UserCreateDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/user/UserCreateDTO.java @@ -24,16 +24,14 @@ import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; -import lombok.AllArgsConstructor; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Setter; +import lombok.*; import nl.dtls.fairdatapoint.entity.user.UserRole; @NoArgsConstructor @AllArgsConstructor @Getter @Setter +@Builder public class UserCreateDTO { @NotBlank diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/user/UserDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/user/UserDTO.java index 2f05583fe..5fa423b72 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/user/UserDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/user/UserDTO.java @@ -28,13 +28,15 @@ import lombok.Setter; import nl.dtls.fairdatapoint.entity.user.UserRole; +import java.util.UUID; + @NoArgsConstructor @AllArgsConstructor @Getter @Setter public class UserDTO { - private String uuid; + private UUID uuid; private String firstName; diff --git a/src/main/java/nl/dtls/fairdatapoint/api/dto/user/UserSimpleDTO.java b/src/main/java/nl/dtls/fairdatapoint/api/dto/user/UserSimpleDTO.java index 9d0259e46..88ae23c31 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/dto/user/UserSimpleDTO.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/dto/user/UserSimpleDTO.java @@ -25,11 +25,13 @@ import lombok.AllArgsConstructor; import lombok.Data; +import java.util.UUID; + @Data @AllArgsConstructor public class UserSimpleDTO { - private String uuid; + private UUID uuid; private String firstName; diff --git a/src/main/java/nl/dtls/fairdatapoint/api/filter/FilterConfigurer.java b/src/main/java/nl/dtls/fairdatapoint/api/filter/FilterConfigurer.java index f2ff2e561..22cb74f82 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/filter/FilterConfigurer.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/filter/FilterConfigurer.java @@ -22,7 +22,7 @@ */ package nl.dtls.fairdatapoint.api.filter; -import org.springframework.beans.factory.annotation.Autowired; +import lombok.RequiredArgsConstructor; import org.springframework.security.config.annotation.SecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.web.DefaultSecurityFilterChain; @@ -30,17 +30,15 @@ import org.springframework.stereotype.Component; @Component +@RequiredArgsConstructor public class FilterConfigurer extends SecurityConfigurerAdapter { - @Autowired - private JwtTokenFilter jwtTokenFilter; + private final JwtTokenFilter jwtTokenFilter; - @Autowired - private CORSFilter corsFilter; + private final CORSFilter corsFilter; - @Autowired - private LoggingFilter loggingFilter; + private final LoggingFilter loggingFilter; @Override public void configure(HttpSecurity http) { diff --git a/src/main/java/nl/dtls/fairdatapoint/api/filter/JwtTokenFilter.java b/src/main/java/nl/dtls/fairdatapoint/api/filter/JwtTokenFilter.java index 9bb8b0981..a36fa7739 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/filter/JwtTokenFilter.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/filter/JwtTokenFilter.java @@ -27,11 +27,11 @@ import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.error.ErrorDTO; import nl.dtls.fairdatapoint.entity.exception.UnauthorizedException; import nl.dtls.fairdatapoint.service.apikey.ApiKeyService; import nl.dtls.fairdatapoint.service.jwt.JwtService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.security.core.Authentication; @@ -44,16 +44,14 @@ import static nl.dtls.fairdatapoint.util.HttpUtil.getToken; @Component +@RequiredArgsConstructor public class JwtTokenFilter extends OncePerRequestFilter { - @Autowired - private JwtService jwtService; + private final JwtService jwtService; - @Autowired - private ApiKeyService apiKeyService; + private final ApiKeyService apiKeyService; - @Autowired - private ObjectMapper objectMapper; + private final ObjectMapper objectMapper; @Override public void doFilterInternal( diff --git a/src/main/java/nl/dtls/fairdatapoint/api/filter/LoggingFilter.java b/src/main/java/nl/dtls/fairdatapoint/api/filter/LoggingFilter.java index dea6a1f1c..3bbbcbbc4 100644 --- a/src/main/java/nl/dtls/fairdatapoint/api/filter/LoggingFilter.java +++ b/src/main/java/nl/dtls/fairdatapoint/api/filter/LoggingFilter.java @@ -31,9 +31,9 @@ import jakarta.servlet.ServletException; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.service.UtilityService; import org.apache.logging.log4j.ThreadContext; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; @@ -41,10 +41,10 @@ import java.io.IOException; @Component +@RequiredArgsConstructor public class LoggingFilter extends OncePerRequestFilter { - @Autowired - private UtilityService utilityService; + private final UtilityService utilityService; @Override public void doFilterInternal( diff --git a/src/main/java/nl/dtls/fairdatapoint/config/AclConfig.java b/src/main/java/nl/dtls/fairdatapoint/config/AclConfig.java index 2638b5472..61f2ed39d 100644 --- a/src/main/java/nl/dtls/fairdatapoint/config/AclConfig.java +++ b/src/main/java/nl/dtls/fairdatapoint/config/AclConfig.java @@ -22,39 +22,36 @@ */ package nl.dtls.fairdatapoint.config; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.entity.user.UserRole; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.Cache; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.security.access.expression.method.DefaultMethodSecurityExpressionHandler; import org.springframework.security.access.expression.method.MethodSecurityExpressionHandler; import org.springframework.security.acls.AclPermissionCacheOptimizer; import org.springframework.security.acls.AclPermissionEvaluator; -import org.springframework.security.acls.dao.AclRepository; import org.springframework.security.acls.domain.*; +import org.springframework.security.acls.jdbc.BasicLookupStrategy; +import org.springframework.security.acls.jdbc.JdbcMutableAclService; import org.springframework.security.acls.jdbc.LookupStrategy; import org.springframework.security.acls.model.AclCache; -import org.springframework.security.acls.model.AclService; +import org.springframework.security.acls.model.MutableAclService; import org.springframework.security.acls.model.PermissionGrantingStrategy; -import org.springframework.security.acls.mongodb.BasicLookupStrategy; -import org.springframework.security.acls.mongodb.MongoDBMutableAclService; import org.springframework.security.core.authority.SimpleGrantedAuthority; +import javax.sql.DataSource; + import static java.lang.String.format; @Configuration +@RequiredArgsConstructor public class AclConfig { public static final String ACL_CACHE = "ACL_CACHE"; - @Autowired - private MongoTemplate mongoTemplate; - - @Autowired - private AclRepository aclRepository; + private final DataSource dataSource; @Bean public AclCache aclCache(ConcurrentMapCacheManager cacheManager) { @@ -65,8 +62,38 @@ springCache, permissionGrantingStrategy(), aclAuthorizationStrategy() } @Bean - public AclService aclService(AclCache aclCache) { - return new MongoDBMutableAclService(aclRepository, lookupStrategy(aclCache), aclCache); + public MutableAclService aclService(AclCache aclCache) { + final JdbcMutableAclService jdbcMutableAclService = + new JdbcMutableAclService(dataSource, lookupStrategy(aclCache), aclCache); + + // from documentation + jdbcMutableAclService.setClassIdentityQuery("select currval(pg_get_serial_sequence('acl_class', 'id'))"); + jdbcMutableAclService.setSidIdentityQuery("select currval(pg_get_serial_sequence('acl_sid', 'id'))"); + + // additional adjustments + jdbcMutableAclService.setObjectIdentityPrimaryKeyQuery( + """ + SELECT acl_object_identity.id + FROM acl_object_identity, acl_class + WHERE acl_object_identity.object_id_class = acl_class.id + AND acl_class.class = ? + AND acl_object_identity.object_id_identity = CAST(? AS varchar); + """ + ); + jdbcMutableAclService.setFindChildrenQuery( + """ + SELECT obj.object_id_identity AS obj_id, class.class AS class + FROM acl_object_identity obj, acl_object_identity parent, acl_class class + WHERE obj.parent_object = parent.id + AND obj.object_id_class = class.id + AND parent.object_id_identity = CAST(? AS varchar) + AND parent.object_id_class = (SELECT id FROM acl_class WHERE acl_class.class = ?) + """ + ); + + jdbcMutableAclService.setAclClassIdSupported(true); + + return jdbcMutableAclService; } @Bean @@ -98,8 +125,14 @@ public MethodSecurityExpressionHandler defaultMethodSecurityExpressionHandler( @Bean public LookupStrategy lookupStrategy(AclCache aclCache) { - return new BasicLookupStrategy(mongoTemplate, aclCache, aclAuthorizationStrategy(), - permissionGrantingStrategy()); + final BasicLookupStrategy basicLookupStrategy = new BasicLookupStrategy( + dataSource, aclCache, + aclAuthorizationStrategy(), new ConsoleAuditLogger()); + final String lookupObjectIdentitiesWhereClause = + "(acl_object_identity.object_id_identity::varchar = ? and acl_class.class = ?)"; + basicLookupStrategy.setLookupObjectIdentitiesWhereClause(lookupObjectIdentitiesWhereClause); + basicLookupStrategy.setAclClassIdSupported(true); + return basicLookupStrategy; } } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0006_ShapesSharing.java b/src/main/java/nl/dtls/fairdatapoint/config/DatabaseConfig.java similarity index 51% rename from src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0006_ShapesSharing.java rename to src/main/java/nl/dtls/fairdatapoint/config/DatabaseConfig.java index 3b3fcb53b..8d7866855 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0006_ShapesSharing.java +++ b/src/main/java/nl/dtls/fairdatapoint/config/DatabaseConfig.java @@ -20,34 +20,37 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.database.mongo.migration.production; +package nl.dtls.fairdatapoint.config; -import com.github.cloudyrock.mongock.ChangeLog; -import com.github.cloudyrock.mongock.ChangeSet; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.model.Filters; -import com.mongodb.client.model.Updates; +import lombok.extern.slf4j.Slf4j; import nl.dtls.fairdatapoint.Profiles; -import org.bson.Document; -import org.springframework.context.annotation.Profile; +import org.flywaydb.core.Flyway; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; -@ChangeLog(order = "0006") -@Profile(Profiles.PRODUCTION) -public class Migration_0006_ShapesSharing { +@Slf4j +@Configuration +public class DatabaseConfig { - private static final String FIELD_PUBLISHED = "published"; + @Bean + public FlywayMigrationStrategy flywayMigrationStrategy(@Value("${spring.profiles.active}") String activeProfile) { + return flywayOld -> { + final Flyway flyway = Flyway.configure() + .configuration(flywayOld.getConfiguration()) + .load(); - @ChangeSet(order = "0006", id = "Migration_0006_ShapesSharing", author = "migrationBot") - public void run(MongoDatabase database) { - addShapeDefinitions(database); - } + if (activeProfile.equals(Profiles.DEVELOPMENT)) { + log.info("Development mode - cleaning up database"); + flyway.clean(); + } - private void addShapeDefinitions(MongoDatabase database) { - final MongoCollection shapeCol = database.getCollection("shape"); - shapeCol.updateMany( - Filters.exists(FIELD_PUBLISHED, false), - Updates.set(FIELD_PUBLISHED, false) - ); + if (activeProfile.equals(Profiles.TESTING)) { + log.info("Testing mode - not migrating database"); + return; + } + flyway.migrate(); + }; } } diff --git a/src/main/java/nl/dtls/fairdatapoint/config/MongoConfig.java b/src/main/java/nl/dtls/fairdatapoint/config/MongoConfig.java deleted file mode 100644 index 07c835de4..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/config/MongoConfig.java +++ /dev/null @@ -1,77 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.config; - -import io.mongock.api.config.LegacyMigration; -import io.mongock.driver.mongodb.springdata.v4.SpringDataMongoV4Driver; -import io.mongock.runner.springboot.MongockSpringboot; -import io.mongock.runner.springboot.base.MongockInitializingBeanRunner; -import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionCache; -import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionTargetClassesCache; -import nl.dtls.fairdatapoint.service.settings.SettingsCache; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.data.mongodb.config.EnableMongoAuditing; -import org.springframework.data.mongodb.core.MongoTemplate; -import org.springframework.data.mongodb.repository.config.EnableMongoRepositories; - -@Configuration -@EnableMongoAuditing -@EnableMongoRepositories( - basePackages = { - "nl.dtls.fairdatapoint", - "nl.dtls.rdf.migration", - "org.springframework.security.acls" - } -) -public class MongoConfig { - - @Autowired - private ResourceDefinitionCache resourceDefinitionCache; - - @Autowired - private ResourceDefinitionTargetClassesCache targetClassesCache; - - @Autowired - private SettingsCache settingsCache; - - @Bean("mongockRunner") - public MongockInitializingBeanRunner mongockApplicationRunner( - ApplicationContext springContext, - MongoTemplate mongoTemplate - ) { - return MongockSpringboot.builder() - .setDriver(SpringDataMongoV4Driver.withDefaultLock(mongoTemplate)) - .addMigrationScanPackage( - "nl.dtls.fairdatapoint.database.mongo.migration.production" - ) - .setSpringContext(springContext) - .setLegacyMigration(new LegacyMigration("dbchangelog")) - .addDependency(ResourceDefinitionCache.class, resourceDefinitionCache) - .addDependency(ResourceDefinitionTargetClassesCache.class, targetClassesCache) - .addDependency(SettingsCache.class, settingsCache) - .buildInitializingBeanRunner(); - } -} diff --git a/src/main/java/nl/dtls/fairdatapoint/config/RepositoryMigrationConfig.java b/src/main/java/nl/dtls/fairdatapoint/config/RepositoryMigrationConfig.java index 1710985e0..343280746 100644 --- a/src/main/java/nl/dtls/fairdatapoint/config/RepositoryMigrationConfig.java +++ b/src/main/java/nl/dtls/fairdatapoint/config/RepositoryMigrationConfig.java @@ -28,14 +28,12 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.Profile; @Configuration public class RepositoryMigrationConfig { @Bean - @DependsOn("mongockRunner") @Profile(Profiles.PRODUCTION) public RdfProductionMigrationRunner rdfProductionMigrationRunner( RdfMigrationRepository rdfMigrationRepository, diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/ApiKeyRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/ApiKeyRepository.java similarity index 79% rename from src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/ApiKeyRepository.java rename to src/main/java/nl/dtls/fairdatapoint/database/db/repository/ApiKeyRepository.java index eef8275d6..218c4beb9 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/ApiKeyRepository.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/ApiKeyRepository.java @@ -20,20 +20,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.database.mongo.repository; +package nl.dtls.fairdatapoint.database.db.repository; +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; import nl.dtls.fairdatapoint.entity.apikey.ApiKey; -import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; -import java.util.List; import java.util.Optional; -public interface ApiKeyRepository extends MongoRepository { - - List findByUserUuid(String userUuid); - - Optional findByUuid(String uuid); - +@Repository +public interface ApiKeyRepository extends BaseRepository { Optional findByToken(String token); - } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/IndexEntryRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/IndexEntryRepository.java similarity index 57% rename from src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/IndexEntryRepository.java rename to src/main/java/nl/dtls/fairdatapoint/database/db/repository/IndexEntryRepository.java index 905acc1be..b288c5384 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/IndexEntryRepository.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/IndexEntryRepository.java @@ -20,49 +20,48 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.database.mongo.repository; +package nl.dtls.fairdatapoint.database.db.repository; +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; import nl.dtls.fairdatapoint.entity.index.entry.IndexEntry; import nl.dtls.fairdatapoint.entity.index.entry.IndexEntryPermit; import nl.dtls.fairdatapoint.entity.index.entry.IndexEntryState; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; -import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; import java.time.Instant; import java.util.List; import java.util.Optional; -public interface IndexEntryRepository extends MongoRepository { - - Optional findByUuid(String uuid); +@Repository +public interface IndexEntryRepository extends BaseRepository { + Iterable findAllByPermitIn(List permit); - Optional findByClientUrl(String clientUrl); + Page findAllByPermitIn(Pageable pageable, List permit); - Page findAllByStateEqualsAndPermitIn( - Pageable pageable, IndexEntryState state, List permit - ); + Page findAllByStateEqualsAndLastRetrievalAtAfterAndPermitIn( + Pageable pageable, IndexEntryState indexEntryState, Instant validThreshold, + List permit); - Page findAllByStateEqualsAndLastRetrievalTimeBeforeAndPermitIn( - Pageable pageable, IndexEntryState state, Instant when, List permit - ); + Page findAllByStateEqualsAndLastRetrievalAtBeforeAndPermitIn( + Pageable pageable, IndexEntryState indexEntryState, Instant validThreshold, + List permit); - Page findAllByStateEqualsAndLastRetrievalTimeAfterAndPermitIn( - Pageable pageable, IndexEntryState state, Instant when, List permit - ); + Page findAllByStateEqualsAndPermitIn( + Pageable pageable, IndexEntryState indexEntryState, List permit); - Page findAllByPermitIn(Pageable pageable, List permit); + Long countAllByPermitIn(List permit); - Iterable findAllByPermitIn(List permit); + Long countAllByStateEqualsAndPermitIn( + IndexEntryState indexEntryState, List permit); - long countAllByPermitIn(List permit); + Long countAllByStateEqualsAndLastRetrievalAtAfterAndPermitIn( + IndexEntryState indexEntryState, Instant validThreshold, List permit); - long countAllByStateEqualsAndPermitIn(IndexEntryState state, List permit); + Long countAllByStateEqualsAndLastRetrievalAtBeforeAndPermitIn( + IndexEntryState indexEntryState, Instant validThreshold, List permit); - long countAllByStateEqualsAndLastRetrievalTimeAfterAndPermitIn( - IndexEntryState state, Instant when, List permit); + Optional findByClientUrl(String clientUrl); - long countAllByStateEqualsAndLastRetrievalTimeBeforeAndPermitIn( - IndexEntryState state, Instant when, List permit - ); } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/EventRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/IndexEventRepository.java similarity index 62% rename from src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/EventRepository.java rename to src/main/java/nl/dtls/fairdatapoint/database/db/repository/IndexEventRepository.java index 13f954d22..67f006f25 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/EventRepository.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/IndexEventRepository.java @@ -20,26 +20,25 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.database.mongo.repository; +package nl.dtls.fairdatapoint.database.db.repository; +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; import nl.dtls.fairdatapoint.entity.index.entry.IndexEntry; -import nl.dtls.fairdatapoint.entity.index.event.Event; -import nl.dtls.fairdatapoint.entity.index.event.EventType; -import org.springframework.data.domain.Page; -import org.springframework.data.domain.Pageable; -import org.springframework.data.mongodb.repository.MongoRepository; +import nl.dtls.fairdatapoint.entity.index.event.IndexEvent; +import nl.dtls.fairdatapoint.entity.index.event.IndexEventType; +import org.springframework.data.domain.PageRequest; +import org.springframework.stereotype.Repository; import java.time.Instant; import java.util.List; -public interface EventRepository extends MongoRepository { +@Repository +public interface IndexEventRepository extends BaseRepository { + Iterable getAllByRelatedTo(IndexEntry indexEntry, PageRequest pageRequest); - List getAllByType(EventType type); + List findAllByRemoteAddrAndCreatedAtAfter(String remoteAddr, Instant rateLimitSince); - List getAllByFinishedIsNull(); + List getAllByFinishedAtIsNull(); - Page getAllByRelatedTo(IndexEntry indexEntry, Pageable pageable); - - List findAllByIncomingPingExchangeRemoteAddrAndCreatedAfter( - String remoteAddr, Instant after); + List getAllByType(IndexEventType indexEventType); } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/IndexSettingsRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/IndexSettingsRepository.java similarity index 80% rename from src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/IndexSettingsRepository.java rename to src/main/java/nl/dtls/fairdatapoint/database/db/repository/IndexSettingsRepository.java index 2a7075bdc..e746771fe 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/IndexSettingsRepository.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/IndexSettingsRepository.java @@ -20,13 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.database.mongo.repository; +package nl.dtls.fairdatapoint.database.db.repository; +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; import nl.dtls.fairdatapoint.entity.index.settings.IndexSettings; -import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; -import java.util.Optional; - -public interface IndexSettingsRepository extends MongoRepository { - Optional findFirstBy(); +@Repository +public interface IndexSettingsRepository extends BaseRepository { } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/db/repository/IndexWebhookRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/IndexWebhookRepository.java new file mode 100644 index 000000000..bdca026f7 --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/IndexWebhookRepository.java @@ -0,0 +1,31 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.database.db.repository; + +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; +import nl.dtls.fairdatapoint.entity.index.webhook.IndexWebhook; +import org.springframework.stereotype.Repository; + +@Repository +public interface IndexWebhookRepository extends BaseRepository { +} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/db/repository/MembershipPermissionRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/MembershipPermissionRepository.java new file mode 100644 index 000000000..260e187d3 --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/MembershipPermissionRepository.java @@ -0,0 +1,31 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.database.db.repository; + +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; +import nl.dtls.fairdatapoint.entity.membership.MembershipPermission; +import org.springframework.stereotype.Repository; + +@Repository +public interface MembershipPermissionRepository extends BaseRepository { +} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/MembershipRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/MembershipRepository.java similarity index 80% rename from src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/MembershipRepository.java rename to src/main/java/nl/dtls/fairdatapoint/database/db/repository/MembershipRepository.java index 1923af66f..d702ab6e4 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/MembershipRepository.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/MembershipRepository.java @@ -20,15 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.database.mongo.repository; +package nl.dtls.fairdatapoint.database.db.repository; +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; import nl.dtls.fairdatapoint.entity.membership.Membership; -import org.springframework.data.mongodb.repository.MongoRepository; - -import java.util.Optional; - -public interface MembershipRepository extends MongoRepository { - - Optional findByUuid(String uuid); +import org.springframework.stereotype.Repository; +@Repository +public interface MembershipRepository extends BaseRepository { } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/db/repository/MetadataSchemaExtensionRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/MetadataSchemaExtensionRepository.java new file mode 100644 index 000000000..caceab19d --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/MetadataSchemaExtensionRepository.java @@ -0,0 +1,68 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.database.db.repository; + +import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaExtension; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.UUID; + +@Repository +public interface MetadataSchemaExtensionRepository extends JpaRepository { + + List findByExtendedMetadataSchema(MetadataSchema schema); + + @Query( + """ + SELECT e.extendedMetadataSchema.uuid + FROM MetadataSchemaExtension e + WHERE e.metadataSchemaVersion.uuid = :uuid + """ + ) + List getExtendedSchemaUuids(UUID uuid); + + @Query( + """ + SELECT e.uuid as uuid, v.schema.uuid as schemaUuid, + e.metadataSchemaVersion.uuid as versionUuid, + e.extendedMetadataSchema.uuid as extendedMetadataSchemaUuid + FROM MetadataSchemaExtension e JOIN MetadataSchemaVersion v ON e.metadataSchemaVersion.uuid = v.uuid + WHERE v.state = 'LATEST' + """ + ) + Iterable getBasicExtensionsForLatest(); + + interface MetadataSchemaExtensionBasic { + UUID getUuid(); + + UUID getSchemaUuid(); + + UUID getVersionUuid(); + + UUID getExtendedMetadataSchemaUuid(); + } +} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/MetadataSchemaRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/MetadataSchemaRepository.java similarity index 56% rename from src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/MetadataSchemaRepository.java rename to src/main/java/nl/dtls/fairdatapoint/database/db/repository/MetadataSchemaRepository.java index 4dcb5f646..8b77ed7e2 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/MetadataSchemaRepository.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/MetadataSchemaRepository.java @@ -20,31 +20,38 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.database.mongo.repository; +package nl.dtls.fairdatapoint.database.db.repository; +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; -import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.stereotype.Repository; import java.util.List; -import java.util.Optional; +import java.util.UUID; -public interface MetadataSchemaRepository extends MongoRepository { +@Repository +public interface MetadataSchemaRepository extends BaseRepository { - List findByUuid(String uuid); + @Query( + """ + SELECT ms.uuid as uuid, msv.uuid as versionUuid, msv.name as name, + msv.version as version, msv.targetClasses as targetClasses + FROM MetadataSchema ms JOIN MetadataSchemaVersion msv ON ms.uuid = msv.schema.uuid + WHERE msv.state = 'LATEST' + """ + ) + Iterable getBasicLatestMetadataSchemas(); - Optional findByVersionUuid(String uuid); + interface MetadataSchemaBasic { + UUID getUuid(); - Optional findByUuidAndVersionString(String uuid, String versionString); + UUID getVersionUuid(); - Optional findByUuidAndLatestIsTrue(String uuid); + String getName(); - List findAllByPublishedIsTrue(); + String getVersion(); - List findAllByLatestIsTrue(); - - List findAllByExtendSchemasContains(String uuid); - - Optional findByPreviousVersionUuid(String uuid); - - List findAllByImportedFromIsNotNull(); + List getTargetClasses(); + } } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/db/repository/MetadataSchemaUsageRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/MetadataSchemaUsageRepository.java new file mode 100644 index 000000000..4d2cc9a36 --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/MetadataSchemaUsageRepository.java @@ -0,0 +1,59 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.database.db.repository; + +import nl.dtls.fairdatapoint.entity.resource.MetadataSchemaUsage; +import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.UUID; + +@Repository +public interface MetadataSchemaUsageRepository extends JpaRepository { + + List findAllByResourceDefinition(ResourceDefinition resourceDefinition); + + @Query( + """ + SELECT e.uuid as uuid, rd.uuid as resourceDefinitionUuid, + e.usedMetadataSchema.uuid as schemaUuid, + rd.name as resourceDefinitionName + FROM MetadataSchemaUsage e JOIN ResourceDefinition rd ON e.resourceDefinition.uuid = rd.uuid + """ + ) + Iterable getBasicUsages(); + + interface MetadataSchemaUsageBasic { + UUID getUuid(); + + UUID getResourceDefinitionUuid(); + + UUID getSchemaUuid(); + + UUID getResourceDefinitionName(); + } + +} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/db/repository/MetadataSchemaVersionRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/MetadataSchemaVersionRepository.java new file mode 100644 index 000000000..53da389f5 --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/MetadataSchemaVersionRepository.java @@ -0,0 +1,106 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.database.db.repository; + +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaState; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaVersion; +import org.springframework.data.jpa.repository.Query; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.Optional; +import java.util.UUID; + +@Repository +public interface MetadataSchemaVersionRepository extends BaseRepository { + + @Query( + """ + SELECT msv + FROM MetadataSchemaVersion msv JOIN MetadataSchema ms ON msv.schema = ms + WHERE ms.uuid = :uuid AND msv.state = 'DRAFT' + """ + ) + Optional getDraftBySchemaUuid(UUID uuid); + + @Query( + """ + SELECT msv + FROM MetadataSchemaVersion msv + WHERE msv.uuid = :uuid AND msv.state = 'DRAFT' + """ + ) + Optional getDraftBySchemaVersionUuid(UUID uuid); + + @Query( + """ + SELECT msv + FROM MetadataSchemaVersion msv JOIN MetadataSchema ms ON msv.schema = ms + WHERE msv.state = 'LATEST' + """ + ) + List getAllLatest(); + + @Query( + """ + SELECT msv + FROM MetadataSchemaVersion msv JOIN MetadataSchema ms ON msv.schema = ms + WHERE ms.uuid = :uuid AND msv.state = 'LATEST' + """ + ) + Optional getLatestBySchemaUuid(UUID uuid); + + @Query( + """ + SELECT msv + FROM MetadataSchemaVersion msv + WHERE msv.uuid = :uuid AND msv.state = 'LATEST' + """ + ) + Optional getLatestBySchemaVersionUuid(UUID uuid); + + @Query( + """ + SELECT msv + FROM MetadataSchemaVersion msv JOIN MetadataSchema ms ON msv.schema = ms + WHERE ms.uuid = :uuid AND msv.version = :version + """ + ) + Optional getBySchemaUuidAndVersion(UUID uuid, String version); + + @Query( + """ + SELECT msv + FROM MetadataSchemaVersion msv JOIN MetadataSchema ms ON msv.schema = ms + WHERE ms.uuid = :uuid + """ + ) + List getBySchemaUuid(UUID uuid); + + List findAllByImportedFromIsNotNull(); + + List findAllByState(MetadataSchemaState state); + + List findAllByPublishedIsTrue(); +} diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsFormsAutocomplete.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/ResourceDefinitionChildMetadataRepository.java similarity index 77% rename from src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsFormsAutocomplete.java rename to src/main/java/nl/dtls/fairdatapoint/database/db/repository/ResourceDefinitionChildMetadataRepository.java index ffd9df06a..af470ed6f 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsFormsAutocomplete.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/ResourceDefinitionChildMetadataRepository.java @@ -20,21 +20,10 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.entity.settings; +package nl.dtls.fairdatapoint.database.db.repository; -import lombok.*; +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; +import nl.dtls.fairdatapoint.entity.resource.ResourceDefinitionChildMetadata; -import java.util.List; - -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -@EqualsAndHashCode -@Builder(toBuilder = true) -public class SettingsFormsAutocomplete { - - private Boolean searchNamespace; - - private List sources; +public interface ResourceDefinitionChildMetadataRepository extends BaseRepository { } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/db/repository/ResourceDefinitionChildRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/ResourceDefinitionChildRepository.java new file mode 100644 index 000000000..96bcd7fe9 --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/ResourceDefinitionChildRepository.java @@ -0,0 +1,49 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.database.db.repository; + +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; +import nl.dtls.fairdatapoint.entity.resource.ResourceDefinitionChild; +import org.springframework.data.jpa.repository.Query; +import org.springframework.stereotype.Repository; + +import java.util.List; +import java.util.UUID; + +@Repository +public interface ResourceDefinitionChildRepository extends BaseRepository { + + @Query( + """ + SELECT rdc.source.uuid as sourceUuid, rdc.target.uuid as targetUuid + FROM ResourceDefinitionChild rdc + """ + ) + List getAllMappings(); + + interface ResourceDefinitionChildMapping { + UUID getSourceUuid(); + + UUID getTargetUuid(); + } +} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/db/repository/ResourceDefinitionLinkRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/ResourceDefinitionLinkRepository.java new file mode 100644 index 000000000..009d31620 --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/ResourceDefinitionLinkRepository.java @@ -0,0 +1,31 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.database.db.repository; + +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; +import nl.dtls.fairdatapoint.entity.resource.ResourceDefinitionLink; +import org.springframework.stereotype.Repository; + +@Repository +public interface ResourceDefinitionLinkRepository extends BaseRepository { +} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/ResourceDefinitionRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/ResourceDefinitionRepository.java similarity index 76% rename from src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/ResourceDefinitionRepository.java rename to src/main/java/nl/dtls/fairdatapoint/database/db/repository/ResourceDefinitionRepository.java index 6655a9409..fbf385abb 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/ResourceDefinitionRepository.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/ResourceDefinitionRepository.java @@ -20,22 +20,17 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.database.mongo.repository; +package nl.dtls.fairdatapoint.database.db.repository; +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; -import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; -import java.util.List; import java.util.Optional; -public interface ResourceDefinitionRepository extends MongoRepository { - - Optional findByUuid(String uuid); - - Optional findByName(String name); - +@Repository +public interface ResourceDefinitionRepository extends BaseRepository { Optional findByUrlPrefix(String urlPrefix); - List findByMetadataSchemaUuidsIsContaining(String metadataSchemaUuid); - + Optional findByName(String name); } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/SearchSavedQueryRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/SearchSavedQueryRepository.java similarity index 79% rename from src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/SearchSavedQueryRepository.java rename to src/main/java/nl/dtls/fairdatapoint/database/db/repository/SearchSavedQueryRepository.java index cdd716e56..19ff9efc1 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/SearchSavedQueryRepository.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/SearchSavedQueryRepository.java @@ -20,15 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.database.mongo.repository; +package nl.dtls.fairdatapoint.database.db.repository; +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; import nl.dtls.fairdatapoint.entity.search.SearchSavedQuery; -import org.springframework.data.mongodb.repository.MongoRepository; - -import java.util.Optional; - -public interface SearchSavedQueryRepository extends MongoRepository { - - Optional findByUuid(String uuid); +import org.springframework.stereotype.Repository; +@Repository +public interface SearchSavedQueryRepository extends BaseRepository { } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/db/repository/SettingsAutocompleteSourceRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/SettingsAutocompleteSourceRepository.java new file mode 100644 index 000000000..a8ee08130 --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/SettingsAutocompleteSourceRepository.java @@ -0,0 +1,31 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.database.db.repository; + +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; +import nl.dtls.fairdatapoint.entity.settings.SettingsAutocompleteSource; +import org.springframework.stereotype.Repository; + +@Repository +public interface SettingsAutocompleteSourceRepository extends BaseRepository { +} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/db/repository/SettingsMetricRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/SettingsMetricRepository.java new file mode 100644 index 000000000..c3e022ff1 --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/SettingsMetricRepository.java @@ -0,0 +1,31 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.database.db.repository; + +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; +import nl.dtls.fairdatapoint.entity.settings.SettingsMetric; +import org.springframework.stereotype.Repository; + +@Repository +public interface SettingsMetricRepository extends BaseRepository { +} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/SettingsRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/SettingsRepository.java similarity index 81% rename from src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/SettingsRepository.java rename to src/main/java/nl/dtls/fairdatapoint/database/db/repository/SettingsRepository.java index b0bbb6576..8575dbf35 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/SettingsRepository.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/SettingsRepository.java @@ -20,13 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.database.mongo.repository; +package nl.dtls.fairdatapoint.database.db.repository; +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; import nl.dtls.fairdatapoint.entity.settings.Settings; -import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.stereotype.Repository; -import java.util.Optional; - -public interface SettingsRepository extends MongoRepository { - Optional findFirstBy(); +@Repository +public interface SettingsRepository extends BaseRepository { } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/db/repository/SettingsSearchFilterItemRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/SettingsSearchFilterItemRepository.java new file mode 100644 index 000000000..b22b6bb3b --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/SettingsSearchFilterItemRepository.java @@ -0,0 +1,31 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.database.db.repository; + +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; +import nl.dtls.fairdatapoint.entity.settings.SettingsSearchFilterItem; +import org.springframework.stereotype.Repository; + +@Repository +public interface SettingsSearchFilterItemRepository extends BaseRepository { +} diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsPing.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/SettingsSearchFilterRepository.java similarity index 76% rename from src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsPing.java rename to src/main/java/nl/dtls/fairdatapoint/database/db/repository/SettingsSearchFilterRepository.java index a3d4f68ad..f9dac2373 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsPing.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/SettingsSearchFilterRepository.java @@ -20,23 +20,12 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.entity.settings; +package nl.dtls.fairdatapoint.database.db.repository; -import jakarta.validation.constraints.NotNull; -import lombok.*; +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; +import nl.dtls.fairdatapoint.entity.settings.SettingsSearchFilter; +import org.springframework.stereotype.Repository; -import java.util.List; - -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -@EqualsAndHashCode -@Builder(toBuilder = true) -public class SettingsPing { - - private boolean enabled; - - @NotNull - private List endpoints; +@Repository +public interface SettingsSearchFilterRepository extends BaseRepository { } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/UserRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/UserAccountRepository.java similarity index 75% rename from src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/UserRepository.java rename to src/main/java/nl/dtls/fairdatapoint/database/db/repository/UserAccountRepository.java index b5deda1dd..98fc2e7d5 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/UserRepository.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/UserAccountRepository.java @@ -20,17 +20,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.database.mongo.repository; +package nl.dtls.fairdatapoint.database.db.repository; -import nl.dtls.fairdatapoint.entity.user.User; -import org.springframework.data.mongodb.repository.MongoRepository; +import nl.dtls.fairdatapoint.database.db.repository.base.BaseRepository; +import nl.dtls.fairdatapoint.entity.user.UserAccount; +import org.springframework.stereotype.Repository; import java.util.Optional; -public interface UserRepository extends MongoRepository { - - Optional findByUuid(String uuid); - - Optional findByEmail(String email); - +@Repository +public interface UserAccountRepository extends BaseRepository { + Optional findByEmail(String email); } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/WebhookRepository.java b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/base/BaseRepository.java similarity index 79% rename from src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/WebhookRepository.java rename to src/main/java/nl/dtls/fairdatapoint/database/db/repository/base/BaseRepository.java index c8331374a..f821b4470 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/WebhookRepository.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/db/repository/base/BaseRepository.java @@ -20,14 +20,15 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.database.mongo.repository; +package nl.dtls.fairdatapoint.database.db.repository.base; -import nl.dtls.fairdatapoint.entity.index.webhook.Webhook; -import org.springframework.data.mongodb.repository.MongoRepository; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.repository.NoRepositoryBean; import java.util.Optional; import java.util.UUID; -public interface WebhookRepository extends MongoRepository { - Optional findByUuid(UUID uuid); +@NoRepositoryBean +public interface BaseRepository extends JpaRepository { + Optional findByUuid(UUID uuid); } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/MigrationRunner.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/MigrationRunner.java deleted file mode 100644 index e86177378..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/MigrationRunner.java +++ /dev/null @@ -1,104 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.development; - -import jakarta.annotation.PostConstruct; -import nl.dtls.fairdatapoint.Profiles; -import nl.dtls.fairdatapoint.database.mongo.migration.development.acl.AclMigration; -import nl.dtls.fairdatapoint.database.mongo.migration.development.apikey.ApiKeyMigration; -import nl.dtls.fairdatapoint.database.mongo.migration.development.index.entry.IndexEntryMigration; -import nl.dtls.fairdatapoint.database.mongo.migration.development.index.event.EventMigration; -import nl.dtls.fairdatapoint.database.mongo.migration.development.membership.MembershipMigration; -import nl.dtls.fairdatapoint.database.mongo.migration.development.resource.ResourceDefinitionMigration; -import nl.dtls.fairdatapoint.database.mongo.migration.development.schema.MetadataSchemaMigration; -import nl.dtls.fairdatapoint.database.mongo.migration.development.settings.SettingsMigration; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.UserMigration; -import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionCache; -import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionTargetClassesCache; -import nl.dtls.fairdatapoint.service.search.SearchFilterCache; -import nl.dtls.fairdatapoint.service.settings.SettingsCache; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Profile; -import org.springframework.stereotype.Service; - -@Service -@Profile(Profiles.NON_PRODUCTION) -public class MigrationRunner { - - @Autowired - private UserMigration userMigration; - - @Autowired - private MembershipMigration membershipMigration; - - @Autowired - private AclMigration aclMigration; - - @Autowired - private ResourceDefinitionMigration resourceDefinitionMigration; - - @Autowired - private MetadataSchemaMigration metadataSchemaMigration; - - @Autowired - private ApiKeyMigration apiKeyMigration; - - @Autowired - private IndexEntryMigration indexEntryMigration; - - @Autowired - private EventMigration eventMigration; - - @Autowired - private SettingsMigration settingsMigration; - - @Autowired - private SettingsCache settingsCache; - - @Autowired - private ResourceDefinitionTargetClassesCache resourceDefinitionTargetClassesCache; - - @Autowired - private ResourceDefinitionCache resourceDefinitionCache; - - @Autowired - private SearchFilterCache searchFilterCache; - - @PostConstruct - public void run() { - settingsMigration.runMigration(); - settingsCache.updateCachedSettings(); - userMigration.runMigration(); - membershipMigration.runMigration(); - aclMigration.runMigration(); - resourceDefinitionMigration.runMigration(); - metadataSchemaMigration.runMigration(); - apiKeyMigration.runMigration(); - indexEntryMigration.runMigration(); - eventMigration.runMigration(); - resourceDefinitionTargetClassesCache.computeCache(); - resourceDefinitionCache.computeCache(); - searchFilterCache.clearCache(); - } - -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/apikey/ApiKeyMigration.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/apikey/ApiKeyMigration.java deleted file mode 100644 index 81ed7f163..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/apikey/ApiKeyMigration.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.development.apikey; - -import nl.dtls.fairdatapoint.database.common.migration.Migration; -import nl.dtls.fairdatapoint.database.mongo.migration.development.apikey.data.ApiKeyFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.ApiKeyRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class ApiKeyMigration implements Migration { - - @Autowired - private ApiKeyFixtures apiKeyFixtures; - - @Autowired - private ApiKeyRepository apiKeyRepository; - - public void runMigration() { - apiKeyRepository.deleteAll(); - apiKeyRepository.save(apiKeyFixtures.albertApiKey()); - apiKeyRepository.save(apiKeyFixtures.nikolaApiKey()); - } - -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/apikey/data/ApiKeyFixtures.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/apikey/data/ApiKeyFixtures.java deleted file mode 100644 index 88264cb76..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/apikey/data/ApiKeyFixtures.java +++ /dev/null @@ -1,60 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.development.apikey.data; - -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; -import nl.dtls.fairdatapoint.entity.apikey.ApiKey; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class ApiKeyFixtures { - - public static final String ALBERT_API_KEY = - "a274793046e34a219fd0ea6362fcca61a001500b71724f4c973a017031653c20"; - - public static final String NIKOLA_API_KEY = - "dd5dc3b53b6145cfa9f6c58b72ebad21cd2f860ace62451ba4e3c74a0e63540a"; - - @Autowired - private UserFixtures userFixtures; - - public ApiKey albertApiKey() { - return new ApiKey( - null, - "a1c00673-24c5-4e0a-bdbe-22e961ee7548", - userFixtures.albert().getUuid(), - ALBERT_API_KEY - ); - } - - public ApiKey nikolaApiKey() { - return new ApiKey( - null, - "62657760-21fe-488c-a0ea-f612a70493da", - userFixtures.nikola().getUuid(), - NIKOLA_API_KEY - ); - } - -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/index/entry/IndexEntryMigration.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/index/entry/IndexEntryMigration.java deleted file mode 100644 index 6a7427599..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/index/entry/IndexEntryMigration.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.development.index.entry; - -import nl.dtls.fairdatapoint.database.common.migration.Migration; -import nl.dtls.fairdatapoint.database.mongo.migration.development.index.entry.data.IndexEntryFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.IndexEntryRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class IndexEntryMigration implements Migration { - - @Autowired - private IndexEntryFixtures indexEntryFixtures; - - @Autowired - private IndexEntryRepository indexEntryRepository; - - public void runMigration() { - indexEntryRepository.deleteAll(); - - indexEntryRepository.save(indexEntryFixtures.entryActive()); - indexEntryRepository.save(indexEntryFixtures.entryActive2()); - indexEntryRepository.save(indexEntryFixtures.entryInactive()); - indexEntryRepository.save(indexEntryFixtures.entryUnreachable()); - indexEntryRepository.save(indexEntryFixtures.entryInvalid()); - indexEntryRepository.save(indexEntryFixtures.entryUnknown()); - } - -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/index/entry/data/IndexEntryFixtures.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/index/entry/data/IndexEntryFixtures.java deleted file mode 100644 index 7b231334e..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/index/entry/data/IndexEntryFixtures.java +++ /dev/null @@ -1,191 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.development.index.entry.data; - -import nl.dtls.fairdatapoint.entity.index.entry.IndexEntry; -import nl.dtls.fairdatapoint.entity.index.entry.IndexEntryPermit; -import nl.dtls.fairdatapoint.entity.index.entry.IndexEntryState; -import nl.dtls.fairdatapoint.entity.index.entry.RepositoryMetadata; -import org.springframework.stereotype.Service; - -import java.time.Instant; -import java.util.HashMap; - -@Service -public class IndexEntryFixtures { - - public IndexEntry entryActive() { - final String clientUri = "https://example.com/my-valid-fairdatapoint1"; - final RepositoryMetadata repositoryData = new RepositoryMetadata( - RepositoryMetadata.CURRENT_VERSION, - clientUri, - new HashMap<>() - ); - return IndexEntry.builder() - .uuid("8987abc1-15a4-4752-903c-8f8a5882cca6") - .clientUrl(clientUri) - .state(IndexEntryState.Valid) - .permit(IndexEntryPermit.ACCEPTED) - .registrationTime(Instant.now()) - .modificationTime(Instant.now()) - .lastRetrievalTime(Instant.now()) - .currentMetadata(repositoryData) - .build(); - } - - public IndexEntry entryActive2() { - final String clientUri = "https://app.fairdatapoint.org"; - final RepositoryMetadata repositoryData = new RepositoryMetadata( - RepositoryMetadata.CURRENT_VERSION, - clientUri, - new HashMap<>() - ); - final Instant date = Instant.parse("2020-05-30T23:38:31.085Z"); - return IndexEntry.builder() - .uuid("c912331f-4a77-4300-a469-dbaf5fc0b4e2") - .clientUrl(clientUri) - .state(IndexEntryState.Valid) - .permit(IndexEntryPermit.ACCEPTED) - .registrationTime(date) - .modificationTime(date) - .lastRetrievalTime(date) - .currentMetadata(repositoryData) - .build(); - } - - public IndexEntry entryInactive() { - final String clientUri = "https://example.com/my-valid-fairdatapoint2"; - final RepositoryMetadata repositoryData = new RepositoryMetadata( - RepositoryMetadata.CURRENT_VERSION, - clientUri, - new HashMap<>() - ); - final Instant date = Instant.parse("2020-05-30T23:38:23.085Z"); - return IndexEntry.builder() - .uuid("b5851ebe-aacf-4de9-bf0a-3686e9256e73") - .clientUrl(clientUri) - .state(IndexEntryState.Valid) - .permit(IndexEntryPermit.ACCEPTED) - .registrationTime(date) - .modificationTime(date) - .lastRetrievalTime(date) - .currentMetadata(repositoryData) - .build(); - } - - public IndexEntry entryUnreachable() { - final String clientUri = "https://example.com/my-unreachable-fairdatapoint"; - final RepositoryMetadata repositoryData = new RepositoryMetadata( - RepositoryMetadata.CURRENT_VERSION, - clientUri, - new HashMap<>() - ); - return IndexEntry.builder() - .uuid("dae46b47-87fb-4fdf-995c-8aa3739a27fc") - .clientUrl(clientUri) - .state(IndexEntryState.Unreachable) - .permit(IndexEntryPermit.ACCEPTED) - .registrationTime(Instant.now()) - .modificationTime(Instant.now()) - .lastRetrievalTime(Instant.now()) - .currentMetadata(repositoryData) - .build(); - } - - public IndexEntry entryInvalid() { - final String clientUri = "https://example.com/my-invalid-fairdatapoint"; - final RepositoryMetadata repositoryData = new RepositoryMetadata( - RepositoryMetadata.CURRENT_VERSION, - clientUri, - new HashMap<>() - ); - return IndexEntry.builder() - .uuid("b37e8c1f-ac0e-49f8-8e07-35571c4f8235") - .clientUrl(clientUri) - .state(IndexEntryState.Invalid) - .permit(IndexEntryPermit.ACCEPTED) - .registrationTime(Instant.now()) - .modificationTime(Instant.now()) - .lastRetrievalTime(Instant.now()) - .currentMetadata(repositoryData) - .build(); - } - - public IndexEntry entryUnknown() { - final String clientUri = "https://example.com/my-unknown-fairdatapoint"; - final RepositoryMetadata repositoryData = new RepositoryMetadata( - RepositoryMetadata.CURRENT_VERSION, - clientUri, - new HashMap<>() - ); - return IndexEntry.builder() - .uuid("4471d7c5-8c5b-4581-a9bc-d175456492c4") - .clientUrl(clientUri) - .state(IndexEntryState.Unknown) - .permit(IndexEntryPermit.ACCEPTED) - .registrationTime(Instant.now()) - .modificationTime(Instant.now()) - .lastRetrievalTime(Instant.now()) - .currentMetadata(repositoryData) - .build(); - } - - public IndexEntry entryRejected() { - final String clientUri = "https://example.com/valid-rejected-fairdatapoint"; - final RepositoryMetadata repositoryData = new RepositoryMetadata( - RepositoryMetadata.CURRENT_VERSION, - clientUri, - new HashMap<>() - ); - return IndexEntry.builder() - .uuid("4471d7c5-8c5b-4581-a9bc-d175456492c5") - .clientUrl(clientUri) - .state(IndexEntryState.Valid) - .permit(IndexEntryPermit.REJECTED) - .registrationTime(Instant.now()) - .modificationTime(Instant.now()) - .lastRetrievalTime(Instant.now()) - .currentMetadata(repositoryData) - .build(); - } - - public IndexEntry entryPending() { - final String clientUri = "https://example.com/valid-pending-fairdatapoint"; - final RepositoryMetadata repositoryData = new RepositoryMetadata( - RepositoryMetadata.CURRENT_VERSION, - clientUri, - new HashMap<>() - ); - return IndexEntry.builder() - .uuid("4471d7c5-8c5b-4581-a9bc-d175456492c6") - .clientUrl(clientUri) - .state(IndexEntryState.Valid) - .permit(IndexEntryPermit.PENDING) - .registrationTime(Instant.now()) - .modificationTime(Instant.now()) - .lastRetrievalTime(Instant.now()) - .currentMetadata(repositoryData) - .build(); - } - -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/index/event/EventMigration.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/index/event/EventMigration.java deleted file mode 100644 index 5e7768c0a..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/index/event/EventMigration.java +++ /dev/null @@ -1,39 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.development.index.event; - -import nl.dtls.fairdatapoint.database.mongo.repository.EventRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class EventMigration { - - @Autowired - private EventRepository eventRepository; - - public void runMigration() { - eventRepository.deleteAll(); - } - -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/membership/MembershipMigration.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/membership/MembershipMigration.java deleted file mode 100644 index d53c4ec48..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/membership/MembershipMigration.java +++ /dev/null @@ -1,46 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.development.membership; - -import nl.dtls.fairdatapoint.database.common.migration.Migration; -import nl.dtls.fairdatapoint.database.mongo.migration.development.membership.data.MembershipFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.MembershipRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class MembershipMigration implements Migration { - - @Autowired - private MembershipFixtures membershipFixtures; - - @Autowired - private MembershipRepository membershipRepository; - - public void runMigration() { - membershipRepository.deleteAll(); - membershipRepository.save(membershipFixtures.owner()); - membershipRepository.save(membershipFixtures.dataProvider()); - } - -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/membership/data/MembershipFixtures.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/membership/data/MembershipFixtures.java deleted file mode 100644 index a26042a9e..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/membership/data/MembershipFixtures.java +++ /dev/null @@ -1,68 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.development.membership.data; - -import nl.dtls.fairdatapoint.entity.membership.Membership; -import nl.dtls.fairdatapoint.entity.membership.MembershipPermission; -import nl.dtls.fairdatapoint.util.KnownUUIDs; -import org.springframework.stereotype.Service; - -import java.util.List; - -@Service -public class MembershipFixtures { - - public static final MembershipPermission READ = new MembershipPermission(1, 'R'); - public static final MembershipPermission WRITE = new MembershipPermission(2, 'W'); - public static final MembershipPermission CREATE = new MembershipPermission(4, 'C'); - public static final MembershipPermission DELETE = new MembershipPermission(8, 'D'); - public static final MembershipPermission ADMINISTRATION = new MembershipPermission(16, 'A'); - - public Membership owner() { - return new Membership( - KnownUUIDs.MEMBERSHIP_OWNER_UUID, - "Owner", - List.of( - WRITE, - DELETE, - CREATE, - ADMINISTRATION - ), - List.of( - KnownUUIDs.RD_CATALOG_UUID, - KnownUUIDs.RD_DATASET_UUID, - KnownUUIDs.RD_DISTRIBUTION_UUID - ) - ); - } - - public Membership dataProvider() { - return new Membership( - KnownUUIDs.MEMBERSHIP_DATAPROVIDER_UUID, - "Data Provider", - List.of(CREATE), - List.of(KnownUUIDs.RD_CATALOG_UUID) - ); - } - -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/resource/ResourceDefinitionMigration.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/resource/ResourceDefinitionMigration.java deleted file mode 100644 index 97b6b7f61..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/resource/ResourceDefinitionMigration.java +++ /dev/null @@ -1,64 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.development.resource; - -import nl.dtls.fairdatapoint.database.common.migration.Migration; -import nl.dtls.fairdatapoint.database.mongo.migration.development.resource.data.ResourceDefinitionFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.ResourceDefinitionRepository; -import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; -import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionCache; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class ResourceDefinitionMigration implements Migration { - - @Autowired - private ResourceDefinitionFixtures resourceDefinitionFixtures; - - @Autowired - private ResourceDefinitionRepository resourceDefinitionRepository; - - @Autowired - private ResourceDefinitionCache resourceDefinitionCache; - - public void runMigration() { - resourceDefinitionRepository.deleteAll(); - - final ResourceDefinition repositoryDef = resourceDefinitionFixtures.fdpDefinition(); - resourceDefinitionRepository.save(repositoryDef); - - final ResourceDefinition catalogDef = resourceDefinitionFixtures.catalogDefinition(); - resourceDefinitionRepository.save(catalogDef); - - final ResourceDefinition datasetDef = resourceDefinitionFixtures.datasetDefinition(); - resourceDefinitionRepository.save(datasetDef); - - final ResourceDefinition distributionDef = - resourceDefinitionFixtures.distributionDefinition(); - resourceDefinitionRepository.save(distributionDef); - - resourceDefinitionCache.computeCache(); - } - -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/resource/data/ResourceDefinitionFixtures.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/resource/data/ResourceDefinitionFixtures.java deleted file mode 100644 index f50ea8c9d..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/resource/data/ResourceDefinitionFixtures.java +++ /dev/null @@ -1,121 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.development.resource.data; - -import nl.dtls.fairdatapoint.entity.resource.*; -import nl.dtls.fairdatapoint.util.KnownUUIDs; -import nl.dtls.fairdatapoint.vocabulary.FDP; -import org.eclipse.rdf4j.model.vocabulary.DCAT; -import org.springframework.stereotype.Service; - -import java.util.List; - -@Service -public class ResourceDefinitionFixtures { - - public static final String ONTOLOGY_DEFINITION_UUID = "4bc19f45-845d-48d6-ade7-ac2664563f60"; - - public ResourceDefinition fdpDefinition() { - return new ResourceDefinition( - KnownUUIDs.RD_FDP_UUID, - "FAIR Data Point", - "", - List.of(KnownUUIDs.SCHEMA_FDP_UUID), - List.of(new ResourceDefinitionChild( - KnownUUIDs.RD_CATALOG_UUID, - FDP.METADATACATALOG.stringValue(), - new ResourceDefinitionChildListView( - "Catalogs", - DCAT.THEME_TAXONOMY.stringValue(), - List.of() - ) - )), - List.of() - ); - } - - public ResourceDefinition catalogDefinition() { - return new ResourceDefinition( - KnownUUIDs.RD_CATALOG_UUID, - "Catalog", - "catalog", - List.of(KnownUUIDs.SCHEMA_CATALOG_UUID), - List.of(new ResourceDefinitionChild( - KnownUUIDs.RD_DATASET_UUID, - DCAT.HAS_DATASET.stringValue(), - new ResourceDefinitionChildListView( - "Datasets", - DCAT.THEME.stringValue(), - List.of() - ) - )), - List.of() - ); - } - - public ResourceDefinition datasetDefinition() { - return new ResourceDefinition( - KnownUUIDs.RD_DATASET_UUID, - "Dataset", - "dataset", - List.of(KnownUUIDs.SCHEMA_DATASET_UUID), - List.of(new ResourceDefinitionChild( - KnownUUIDs.RD_DISTRIBUTION_UUID, - DCAT.HAS_DISTRIBUTION.stringValue(), - new ResourceDefinitionChildListView("Distributions", null, List.of( - new ResourceDefinitionChildListViewMetadata( - "Media Type", - DCAT.MEDIA_TYPE.stringValue() - ) - )) - )), - List.of() - ); - } - - public ResourceDefinition distributionDefinition() { - return new ResourceDefinition( - KnownUUIDs.RD_DISTRIBUTION_UUID, - "Distribution", - "distribution", - List.of(KnownUUIDs.SCHEMA_DISTRIBUTION_UUID), - List.of(), - List.of( - new ResourceDefinitionLink("Access online", DCAT.ACCESS_URL.stringValue()), - new ResourceDefinitionLink("Download", DCAT.DOWNLOAD_URL.stringValue()) - ) - ); - } - - public ResourceDefinition ontologyDefinition() { - return new ResourceDefinition( - ONTOLOGY_DEFINITION_UUID, - "Data Service", - "data-service", - List.of(KnownUUIDs.SCHEMA_DATASERVICE_UUID), - List.of(), - List.of() - ); - } - -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/MetadataSchemaMigration.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/MetadataSchemaMigration.java deleted file mode 100644 index fbfed77d7..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/MetadataSchemaMigration.java +++ /dev/null @@ -1,51 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.development.schema; - -import nl.dtls.fairdatapoint.database.common.migration.Migration; -import nl.dtls.fairdatapoint.database.mongo.migration.development.schema.data.MetadataSchemaFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class MetadataSchemaMigration implements Migration { - - @Autowired - private MetadataSchemaFixtures metadataSchemaFixtures; - - @Autowired - private MetadataSchemaRepository metadataSchemaRepository; - - public void runMigration() { - metadataSchemaRepository.deleteAll(); - metadataSchemaRepository.save(metadataSchemaFixtures.resourceSchema()); - metadataSchemaRepository.save(metadataSchemaFixtures.fdpSchema()); - metadataSchemaRepository.save(metadataSchemaFixtures.dataServiceSchema()); - metadataSchemaRepository.save(metadataSchemaFixtures.metadataServiceSchema()); - metadataSchemaRepository.save(metadataSchemaFixtures.catalogSchema()); - metadataSchemaRepository.save(metadataSchemaFixtures.datasetSchema()); - metadataSchemaRepository.save(metadataSchemaFixtures.distributionSchema()); - } - -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/MetadataSchemaFixtures.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/MetadataSchemaFixtures.java deleted file mode 100644 index c7af5276c..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/MetadataSchemaFixtures.java +++ /dev/null @@ -1,271 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.development.schema.data; - -import lombok.SneakyThrows; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaDraft; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaType; -import nl.dtls.fairdatapoint.entity.schema.SemVer; -import nl.dtls.fairdatapoint.util.KnownUUIDs; -import org.springframework.stereotype.Service; - -import java.time.Instant; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import static nl.dtls.fairdatapoint.util.ResourceReader.loadClassResource; - -@Service -public class MetadataSchemaFixtures { - - private static final String DEFAULT_VERSION = "1.0.0"; - - private static final SemVer VERSION = new SemVer(DEFAULT_VERSION); - - private MetadataSchema createSchemaFixture( - String uuid, - String versionUuid, - String name, - String definition, - Set targetClasses, - List extendsSchemas, - MetadataSchemaType type - ) { - return MetadataSchema.builder() - .uuid(uuid) - .versionUuid(versionUuid) - .version(VERSION) - .versionString(VERSION.toString()) - .name(name) - .definition(definition) - .targetClasses(targetClasses) - .extendSchemas(extendsSchemas) - .type(type) - .origin(null) - .latest(true) - .published(true) - .abstractSchema(false) - .suggestedResourceName(null) - .suggestedUrlPrefix(null) - .previousVersionUuid(null) - .createdAt(Instant.now()) - .build(); - } - - private MetadataSchemaDraft createSchemaDraftFixture( - String uuid, - String name, - String definition, - Set targetClasses - ) { - return MetadataSchemaDraft.builder() - .uuid(uuid) - .name(name) - .description("") - .abstractSchema(false) - .definition(definition) - .targetClasses(targetClasses) - .extendSchemas(Collections.emptyList()) - .createdAt(Instant.now()) - .updatedAt(Instant.now()) - .build(); - } - - @SneakyThrows - public MetadataSchema resourceSchema() { - final String definition = loadClassResource("shape-resource.ttl", getClass()); - final MetadataSchema schema = createSchemaFixture( - KnownUUIDs.SCHEMA_RESOURCE_UUID, - KnownUUIDs.SCHEMA_V1_RESOURCE_UUID, - "Resource", - definition, - Set.of("http://www.w3.org/ns/dcat#Resource"), - Collections.emptyList(), - MetadataSchemaType.INTERNAL - ); - schema.setAbstractSchema(true); - return schema; - } - - @SneakyThrows - public MetadataSchema fdpSchema() { - final String definition = loadClassResource("shape-fdp.ttl", getClass()); - return createSchemaFixture( - KnownUUIDs.SCHEMA_FDP_UUID, - KnownUUIDs.SCHEMA_V1_FDP_UUID, - "FAIR Data Point", - definition, - Set.of("https://w3id.org/fdp/fdp-o#FAIRDataPoint"), - Collections.singletonList(KnownUUIDs.SCHEMA_METADATASERVICE_UUID), - MetadataSchemaType.INTERNAL - ); - } - - @SneakyThrows - public MetadataSchema dataServiceSchema() { - final String definition = loadClassResource("shape-data-service.ttl", getClass()); - return createSchemaFixture( - KnownUUIDs.SCHEMA_DATASERVICE_UUID, - KnownUUIDs.SCHEMA_V1_DATASERVICE_UUID, - "Data Service", - definition, - Set.of("http://www.w3.org/ns/dcat#DataService"), - Collections.singletonList(KnownUUIDs.SCHEMA_RESOURCE_UUID), - MetadataSchemaType.INTERNAL - ); - } - - @SneakyThrows - public MetadataSchema metadataServiceSchema() { - final String definition = loadClassResource("shape-metadata-service.ttl", getClass()); - return createSchemaFixture( - KnownUUIDs.SCHEMA_METADATASERVICE_UUID, - KnownUUIDs.SCHEMA_V1_METADATASERVICE_UUID, - "Metadata Service", - definition, - Set.of("https://w3id.org/fdp/fdp-o#MetadataService"), - Collections.singletonList(KnownUUIDs.SCHEMA_DATASERVICE_UUID), - MetadataSchemaType.INTERNAL - ); - } - - @SneakyThrows - public MetadataSchema catalogSchema() { - final String definition = loadClassResource("shape-catalog.ttl", getClass()); - return createSchemaFixture( - KnownUUIDs.SCHEMA_CATALOG_UUID, - KnownUUIDs.SCHEMA_V1_CATALOG_UUID, - "Catalog", - definition, - Set.of("http://www.w3.org/ns/dcat#Catalog"), - Collections.singletonList(KnownUUIDs.SCHEMA_RESOURCE_UUID), - MetadataSchemaType.INTERNAL - ); - } - - @SneakyThrows - public MetadataSchema datasetSchema() { - final String definition = loadClassResource("shape-dataset.ttl", getClass()); - return createSchemaFixture( - KnownUUIDs.SCHEMA_DATASET_UUID, - KnownUUIDs.SCHEMA_V1_DATASET_UUID, - "Dataset", - definition, - Set.of("http://www.w3.org/ns/dcat#Dataset"), - Collections.singletonList(KnownUUIDs.SCHEMA_RESOURCE_UUID), - MetadataSchemaType.CUSTOM - ); - } - - @SneakyThrows - public MetadataSchema distributionSchema() { - final String definition = loadClassResource("shape-distribution.ttl", getClass()); - return createSchemaFixture( - KnownUUIDs.SCHEMA_DISTRIBUTION_UUID, - KnownUUIDs.SCHEMA_V1_DISTRIBUTION_UUID, - "Distribution", - definition, - Set.of("http://www.w3.org/ns/dcat#Distribution"), - Collections.singletonList(KnownUUIDs.SCHEMA_RESOURCE_UUID), - MetadataSchemaType.CUSTOM - ); - } - - @SneakyThrows - public MetadataSchema customSchema() { - final String definition = loadClassResource("shape-custom.ttl", getClass()); - return createSchemaFixture( - "ceba9984-9838-4be2-a2a7-12213016fd96", - "ceba9984-9838-4be2-a2a7-12213016fd97", - "Custom Shape", - definition, - Set.of("http://example.org/Dog"), - Collections.singletonList(KnownUUIDs.SCHEMA_RESOURCE_UUID), - MetadataSchemaType.CUSTOM - ); - } - - @SneakyThrows - public MetadataSchema customSchemaEdited() { - final String definition = loadClassResource("shape-custom-edited.ttl", getClass()); - final MetadataSchema schema = customSchema(); - schema.setVersionUuid("ceba9984-9838-4be2-a2a7-12213016fd98"); - schema.setDefinition(definition); - return schema; - } - - @SneakyThrows - public MetadataSchemaDraft customSchemaDraft1() { - final MetadataSchema schema = customSchema(); - return createSchemaDraftFixture( - schema.getUuid(), - schema.getName(), - schema.getDefinition(), - schema.getTargetClasses() - ); - } - - @SneakyThrows - public MetadataSchemaDraft customSchemaDraft2() { - final MetadataSchema schema = customSchema(); - return createSchemaDraftFixture( - schema.getUuid(), - "Custom Shape 2", - schema.getDefinition(), - schema.getTargetClasses() - ); - } - - @SneakyThrows - public MetadataSchema customSchemaV1(boolean latest) { - final MetadataSchema schema = customSchema(); - schema.setName("Schema v1.0.0"); - schema.setVersionString(DEFAULT_VERSION); - schema.setLatest(latest); - return schema; - } - - @SneakyThrows - public MetadataSchema customSchemaV2(MetadataSchema previousVersion, boolean latest) { - final MetadataSchema schema = customSchema(); - schema.setName("Schema v2.0.0"); - schema.setVersionString("2.0.0"); - schema.setLatest(latest); - schema.setVersionUuid("ceba9984-9838-4be2-a2a7-12213016fd99"); - schema.setPreviousVersionUuid(previousVersion.getVersionUuid()); - return schema; - } - - @SneakyThrows - public MetadataSchema customSchemaV3(MetadataSchema previousVersion, boolean latest) { - final MetadataSchema schema = customSchema(); - schema.setName("Schema v2.1.0"); - schema.setVersionString("2.1.0"); - schema.setLatest(latest); - schema.setVersionUuid("ceba9984-9838-4be2-a2a7-12213016fd00"); - schema.setPreviousVersionUuid(previousVersion.getVersionUuid()); - return schema; - } -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/search/SearchSavedQueryFixtures.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/search/SearchSavedQueryFixtures.java deleted file mode 100644 index 8565de6ce..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/search/SearchSavedQueryFixtures.java +++ /dev/null @@ -1,96 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.development.search; - -import nl.dtls.fairdatapoint.api.dto.search.SearchQueryVariablesDTO; -import nl.dtls.fairdatapoint.entity.search.SearchSavedQuery; -import nl.dtls.fairdatapoint.entity.search.SearchSavedQueryType; -import nl.dtls.fairdatapoint.util.KnownUUIDs; -import org.springframework.stereotype.Service; - -import java.time.Instant; -import java.util.UUID; - -@Service -public class SearchSavedQueryFixtures { - - private static final String PREFIX_DCAT = "PREFIX dcat: "; - private static final String ORDER_TITLE = "ASC(?title)"; - - public SearchSavedQuery savedQueryPublic01() { - return SearchSavedQuery.builder() - .uuid(UUID.randomUUID().toString()) - .name("All datasets") - .description("Quickly query all datasets (DCAT)") - .type(SearchSavedQueryType.PUBLIC) - .userUuid(KnownUUIDs.USER_ALBERT_UUID) - .variables(SearchQueryVariablesDTO.builder() - .prefixes(PREFIX_DCAT) - .graphPattern("?entity rdf:type dcat:Dataset .") - .ordering(ORDER_TITLE) - .build() - ) - .createdAt(Instant.now()) - .updatedAt(Instant.now()) - .build(); - } - - public SearchSavedQuery savedQueryInternal01() { - return SearchSavedQuery.builder() - .uuid(UUID.randomUUID().toString()) - .name("All distributions") - .description("Quickly query all distributions (DCAT)") - .type(SearchSavedQueryType.INTERNAL) - .userUuid(KnownUUIDs.USER_ADMIN_UUID) - .variables(SearchQueryVariablesDTO.builder() - .prefixes(PREFIX_DCAT) - .graphPattern("?entity rdf:type dcat:Distribution .") - .ordering(ORDER_TITLE) - .build() - ) - .createdAt(Instant.now()) - .updatedAt(Instant.now()) - .build(); - } - - public SearchSavedQuery savedQueryPrivate01() { - return SearchSavedQuery.builder() - .uuid(UUID.randomUUID().toString()) - .name("Things with data") - .description("This is private query of Nikola Tesla.") - .type(SearchSavedQueryType.PRIVATE) - .userUuid(KnownUUIDs.USER_NIKOLA_UUID) - .variables(SearchQueryVariablesDTO.builder() - .prefixes("") - .graphPattern(""" - ?entity ?relationPredicate ?relationObject . - FILTER isLiteral(?relationObject) - FILTER CONTAINS(LCASE(str(?relationObject)), LCASE("data"))""") - .ordering(ORDER_TITLE) - .build() - ) - .createdAt(Instant.now()) - .updatedAt(Instant.now()) - .build(); - } -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/settings/data/SettingsFixtures.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/settings/data/SettingsFixtures.java deleted file mode 100644 index 883105b3f..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/settings/data/SettingsFixtures.java +++ /dev/null @@ -1,113 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.development.settings.data; - -import nl.dtls.fairdatapoint.entity.search.SearchFilterType; -import nl.dtls.fairdatapoint.entity.settings.Settings; -import nl.dtls.fairdatapoint.entity.settings.SettingsAutocompleteSource; -import nl.dtls.fairdatapoint.entity.settings.SettingsSearchFilter; -import nl.dtls.fairdatapoint.entity.settings.SettingsSearchFilterItem; - -import java.util.Collections; -import java.util.List; - -public class SettingsFixtures { - - private static final SettingsSearchFilter SEARCH_FILTER_TYPE = SettingsSearchFilter - .builder() - .type(SearchFilterType.IRI) - .label("Type") - .predicate("http://www.w3.org/1999/02/22-rdf-syntax-ns#type") - .queryFromRecords(false) - .presetValues(List.of( - SettingsSearchFilterItem.builder() - .label("Catalog") - .value("http://www.w3.org/ns/dcat#Catalog") - .build(), - SettingsSearchFilterItem.builder() - .label("Dataset") - .value("http://www.w3.org/ns/dcat#Dataset") - .build(), - SettingsSearchFilterItem.builder() - .label("Distribution") - .value("http://www.w3.org/ns/dcat#Distribution") - .build(), - SettingsSearchFilterItem.builder() - .label("Data Service") - .value("http://www.w3.org/ns/dcat#DataService") - .build(), - SettingsSearchFilterItem.builder() - .label("Metadata Service") - .value("http://www.w3.org/ns/dcat#MetadataService") - .build(), - SettingsSearchFilterItem.builder() - .label("FAIR Data Point") - .value("https://w3id.org/fdp/fdp-o#FAIRDataPoint") - .build() - )) - .build(); - - private static final SettingsSearchFilter SEARCH_FILTER_LICENSE = SettingsSearchFilter - .builder() - .type(SearchFilterType.IRI) - .label("License") - .predicate("http://purl.org/dc/terms/license") - .queryFromRecords(true) - .presetValues(Collections.emptyList()) - .build(); - - private static final SettingsSearchFilter SEARCH_FILTER_VERSION = SettingsSearchFilter - .builder() - .type(SearchFilterType.LITERAL) - .label("Version") - .predicate("http://www.w3.org/ns/dcat#version") - .queryFromRecords(true) - .presetValues(Collections.emptyList()) - .build(); - - private static final SettingsAutocompleteSource AUTOCOMPLETE_SOURCE_COUNTRY = SettingsAutocompleteSource - .builder() - .rdfType("https://example.com/ontology#Country") - .sparqlEndpoint("https://query.wikidata.org/sparql") - .sparqlQuery(""" - SELECT DISTINCT ?entity ?entityLabel - WHERE { - ?entity wdt:P31 wd:Q6256 . - SERVICE wikibase:label { bd:serviceParam wikibase:language "en" } - } - """) - .build(); - - public static Settings settings() { - final Settings settings = Settings.getDefault(); - settings.setSearchFilters(List.of( - SEARCH_FILTER_TYPE, - SEARCH_FILTER_LICENSE, - SEARCH_FILTER_VERSION - )); - settings.getForms().getAutocomplete().setSources(List.of( - AUTOCOMPLETE_SOURCE_COUNTRY - )); - return settings; - } -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/user/UserMigration.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/user/UserMigration.java deleted file mode 100644 index 81a9f0f67..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/user/UserMigration.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.development.user; - -import nl.dtls.fairdatapoint.database.common.migration.Migration; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.UserRepository; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; - -@Service -public class UserMigration implements Migration { - - @Autowired - private UserFixtures userFixtures; - - @Autowired - private UserRepository userRepository; - - public void runMigration() { - userRepository.deleteAll(); - userRepository.save(userFixtures.admin()); - userRepository.save(userFixtures.albert()); - userRepository.save(userFixtures.nikola()); - } - -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/user/data/UserFixtures.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/user/data/UserFixtures.java deleted file mode 100644 index 30eb64fe5..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/user/data/UserFixtures.java +++ /dev/null @@ -1,92 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.development.user.data; - -import nl.dtls.fairdatapoint.entity.user.User; -import nl.dtls.fairdatapoint.entity.user.UserRole; -import nl.dtls.fairdatapoint.util.KnownUUIDs; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Service; - -@Service -public class UserFixtures { - - public static final String ADMIN_EMAIL = "admin@example.com"; - - public static final String ALBERT_EMAIL = "albert.einstein@example.com"; - - public static final String NIKOLA_EMAIL = "nikola.tesla@example.com"; - - public static final String ISAAC_EMAIL = "isaac.newton@example.com"; - - private static final String PASSWORD = "password"; - - @Autowired - private PasswordEncoder passwordEncoder; - - public User admin() { - return new User( - KnownUUIDs.USER_ADMIN_UUID, - "Admin", - "von Universe", - ADMIN_EMAIL, - passwordEncoder.encode(PASSWORD), - UserRole.ADMIN - ); - } - - public User albert() { - return new User( - KnownUUIDs.USER_ALBERT_UUID, - "Albert", - "Einstein", - ALBERT_EMAIL, - passwordEncoder.encode(PASSWORD), - UserRole.USER - ); - } - - public User nikola() { - return new User( - KnownUUIDs.USER_NIKOLA_UUID, - "Nikola", - "Tesla", - NIKOLA_EMAIL, - passwordEncoder.encode(PASSWORD), - UserRole.USER - ); - } - - public User isaac() { - return new User( - KnownUUIDs.USER_ISAAC_UUID, - "Isaac", - "Newton", - ISAAC_EMAIL, - passwordEncoder.encode(PASSWORD), - UserRole.USER - ); - } - -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0001_Init.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0001_Init.java deleted file mode 100644 index c04cb21eb..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0001_Init.java +++ /dev/null @@ -1,110 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.production; - -import com.github.cloudyrock.mongock.ChangeLog; -import com.github.cloudyrock.mongock.ChangeSet; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import nl.dtls.fairdatapoint.Profiles; -import nl.dtls.fairdatapoint.util.KnownUUIDs; -import org.bson.BasicBSONObject; -import org.bson.Document; -import org.bson.types.BasicBSONList; -import org.springframework.context.annotation.Profile; - -@ChangeLog(order = "0001") -@Profile(Profiles.PRODUCTION) -public class Migration_0001_Init { - - private static final String FIELD_UUID = "uuid"; - private static final String FIELD_PERMISSIONS = "permissions"; - private static final String FIELD_MASK = "mask"; - private static final String FIELD_CODE = "code"; - private static final String FIELD_CLASS = "_class"; - private static final int MASK_W = 2; - private static final int MASK_C = 4; - private static final int MASK_D = 8; - private static final int MASK_A = 16; - - @ChangeSet(order = "0001", id = "0001_init", author = "migrationBot") - public void run(MongoDatabase database) { - final MongoCollection userCol = database.getCollection("user"); - userCol.insertOne(userAlbert()); - userCol.insertOne(userNikola()); - - final MongoCollection membershipCol = database.getCollection("membership"); - membershipCol.insertOne(membershipOwner()); - membershipCol.insertOne(membershipDataProvider()); - } - - private Document userAlbert() { - return createUser(KnownUUIDs.USER_ALBERT_UUID, "Albert", "Einstein", "albert.einstein@example.com", "ADMIN"); - } - - private Document userNikola() { - return createUser(KnownUUIDs.USER_NIKOLA_UUID, "Nikola", "Tesla", "nikola.tesla@example.com", "USER"); - } - - private Document createUser(String uuid, String firstName, String lastName, String email, String role) { - final Document user = new Document(); - user.append(FIELD_UUID, uuid); - user.append("firstName", firstName); - user.append("lastName", lastName); - user.append("email", email); - user.append("passwordHash", "$2a$10$t2foZfp7cZFQo2u/33ZqTu2WNitBqYd2EY2tQO0/rBUdf8QfsAxyW"); - user.append("role", role); - user.append(FIELD_CLASS, "nl.dtls.fairdatapoint.entity.user.User"); - return user; - } - - private Document membershipOwner() { - return createMembership(KnownUUIDs.MEMBERSHIP_OWNER_UUID, "Owner", true); - } - - private Document membershipDataProvider() { - return createMembership(KnownUUIDs.MEMBERSHIP_DATAPROVIDER_UUID, "Data Provider", false); - } - - private Document createMembership(String uuid, String name, boolean owner) { - final Document membership = new Document(); - membership.append(FIELD_UUID, uuid); - membership.append("name", name); - final BasicBSONList permissions = new BasicBSONList(); - permissions.add(new BasicBSONObject().append(FIELD_MASK, MASK_C).append(FIELD_CODE, "C")); - final BasicBSONList allowedEntities = new BasicBSONList(); - allowedEntities.add("CATALOG"); - if (owner) { - permissions.add(new BasicBSONObject().append(FIELD_MASK, MASK_W).append(FIELD_CODE, "W")); - permissions.add(new BasicBSONObject().append(FIELD_MASK, MASK_D).append(FIELD_CODE, "D")); - permissions.add(new BasicBSONObject().append(FIELD_MASK, MASK_A).append(FIELD_CODE, "A")); - allowedEntities.add("DATASET"); - allowedEntities.add("DISTRIBUTION"); - } - membership.append(FIELD_PERMISSIONS, permissions); - membership.append("allowedEntities", allowedEntities); - membership.append(FIELD_CLASS, "nl.dtls.fairdatapoint.entity.membership.Membership"); - return membership; - } - -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0002_CustomMetamodel.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0002_CustomMetamodel.java deleted file mode 100644 index aac786a1b..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0002_CustomMetamodel.java +++ /dev/null @@ -1,137 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.production; - -import com.github.cloudyrock.mongock.ChangeLog; -import com.github.cloudyrock.mongock.ChangeSet; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import nl.dtls.fairdatapoint.Profiles; -import nl.dtls.fairdatapoint.util.KnownUUIDs; -import org.bson.Document; -import org.eclipse.rdf4j.model.vocabulary.DCAT; -import org.springframework.context.annotation.Profile; - -import java.util.List; - -import static com.mongodb.client.model.Updates.combine; -import static com.mongodb.client.model.Updates.set; - -@ChangeLog(order = "0002") -@Profile(Profiles.PRODUCTION) -public class Migration_0002_CustomMetamodel { - - private static final String R3D_REPOSITORY = "http://www.re3data.org/schema/3-0#Repository"; - private static final String R3D_HAS_CATALOG = "http://www.re3data.org/schema/3-0#dataCatalog"; - - @ChangeSet(order = "0002", id = "0002_Custom_metamodel", author = "migrationBot") - public void run(MongoDatabase database) { - updateAcl(database); - addResourceDefinitions(database); - } - - private void updateAcl(MongoDatabase database) { - final MongoCollection aclCol = database.getCollection("ACL"); - aclCol.updateMany(new Document(), combine(set("className", "nl.dtls.fairdatapoint.entity.metadata.Metadata"))); - } - - private void addResourceDefinitions(MongoDatabase database) { - final MongoCollection rdCol = database.getCollection("resourceDefinition"); - rdCol.insertOne(repositoryDefinition()); - rdCol.insertOne(catalogDefinition()); - rdCol.insertOne(datasetDefinition()); - rdCol.insertOne(distributionDefinition()); - } - - private Document repositoryDefinition() { - return createDefinition( - KnownUUIDs.RD_REPOSITORY_UUID, - "Repository", - "", - R3D_REPOSITORY, - "https://www.purl.org/fairtools/fdp/schema/0.1/fdpMetadata", - List.of(R3D_REPOSITORY, DCAT.RESOURCE.stringValue()), - R3D_HAS_CATALOG, - null, - KnownUUIDs.RD_CATALOG_UUID - ); - } - - private Document catalogDefinition() { - return createDefinition( - KnownUUIDs.RD_CATALOG_UUID, - "Catalog", - "catalog", - DCAT.CATALOG.stringValue(), - "https://www.purl.org/fairtools/fdp/schema/0.1/catalogMetadata", - List.of(DCAT.CATALOG.stringValue(), DCAT.RESOURCE.stringValue()), - DCAT.HAS_DATASET.stringValue(), - KnownUUIDs.RD_REPOSITORY_UUID, - KnownUUIDs.RD_DATASET_UUID - ); - } - - private Document datasetDefinition() { - return createDefinition( - KnownUUIDs.RD_DATASET_UUID, - "Dataset", - "dataset", - DCAT.DATASET.stringValue(), - "https://www.purl.org/fairtools/fdp/schema/0.1/datasetMetadata", - List.of(DCAT.DATASET.stringValue(), DCAT.RESOURCE.stringValue()), - DCAT.HAS_DISTRIBUTION.stringValue(), - KnownUUIDs.RD_CATALOG_UUID, - KnownUUIDs.RD_DISTRIBUTION_UUID - ); - } - - private Document distributionDefinition() { - return createDefinition( - KnownUUIDs.RD_DISTRIBUTION_UUID, - "Distribution", - "distribution", - DCAT.DISTRIBUTION.stringValue(), - "https://www.purl.org/fairtools/fdp/schema/0.1/distributionMetadata", - List.of(DCAT.DISTRIBUTION.stringValue(), DCAT.RESOURCE.stringValue()), - null, - KnownUUIDs.RD_DATASET_UUID, - null - ); - } - - private Document createDefinition(String uuid, String name, String prefix, String type, String specs, - List classes, String child, String parentUuid, String childUuid) { - final Document definition = new Document(); - definition.append("uuid", uuid); - definition.append("name", name); - definition.append("uriPrefix", prefix); - definition.append("rdfType", type); - definition.append("specs", specs); - definition.append("shaclTargetClasses", classes); - definition.append("child", child); - definition.append("parentResourceDefinitionUuid", parentUuid); - definition.append("childResourceDefinitionUuid", childUuid); - definition.append("_class", "nl.dtls.fairdatapoint.entity.resource.ResourceDefinition"); - return definition; - } -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0003_ShapeDefinition.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0003_ShapeDefinition.java deleted file mode 100644 index 0ab13444b..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0003_ShapeDefinition.java +++ /dev/null @@ -1,84 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.production; - -import com.github.cloudyrock.mongock.ChangeLog; -import com.github.cloudyrock.mongock.ChangeSet; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import nl.dtls.fairdatapoint.Profiles; -import nl.dtls.fairdatapoint.util.KnownUUIDs; -import org.bson.Document; -import org.springframework.context.annotation.Profile; - -import static nl.dtls.fairdatapoint.util.ResourceReader.loadClassResource; - -@ChangeLog(order = "0003") -@Profile(Profiles.PRODUCTION) -public class Migration_0003_ShapeDefinition { - - @ChangeSet(order = "0003", id = "Migration_0003_ShapeDefinition", author = "migrationBot") - public void run(MongoDatabase database) throws Exception { - addShapeDefinitions(database); - } - - private void addShapeDefinitions(MongoDatabase database) throws Exception { - final MongoCollection shapeCol = database.getCollection("shape"); - shapeCol.insertOne(resourceDefinition()); - shapeCol.insertOne(repositoryDefinition()); - shapeCol.insertOne(catalogDefinition()); - shapeCol.insertOne(datasetDefinition()); - shapeCol.insertOne(distributionDefinition()); - } - - private Document resourceDefinition() throws Exception { - return createShape("0003_shape-resource.ttl", KnownUUIDs.SCHEMA_RESOURCE_UUID, "Resource"); - } - - private Document repositoryDefinition() throws Exception { - return createShape("0003_shape-repository.ttl", KnownUUIDs.SCHEMA_REPOSITORY_UUID, "Repository"); - } - - private Document catalogDefinition() throws Exception { - return createShape("0003_shape-catalog.ttl", KnownUUIDs.SCHEMA_CATALOG_UUID, "Catalog"); - } - - private Document datasetDefinition() throws Exception { - return createShape("0003_shape-dataset.ttl", KnownUUIDs.SCHEMA_DATASET_UUID, "Dataset"); - } - - private Document distributionDefinition() throws Exception { - return createShape("0003_shape-distribution.ttl", KnownUUIDs.SCHEMA_DISTRIBUTION_UUID, "Distribution"); - } - - private Document createShape(String filename, String uuid, String name) throws Exception { - final String shaclDefinition = loadClassResource(filename, getClass()); - final Document shape = new Document(); - shape.append("uuid", uuid); - shape.append("name", name); - shape.append("type", "INTERNAL"); - shape.append("definition", shaclDefinition); - shape.append("_class", "nl.dtls.fairdatapoint.entity.shape.Shape"); - return shape; - } -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0004_ResourceDefinition.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0004_ResourceDefinition.java deleted file mode 100644 index 875c5dda2..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0004_ResourceDefinition.java +++ /dev/null @@ -1,212 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.production; - -import com.github.cloudyrock.mongock.ChangeLog; -import com.github.cloudyrock.mongock.ChangeSet; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import nl.dtls.fairdatapoint.Profiles; -import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionCache; -import nl.dtls.fairdatapoint.util.KnownUUIDs; -import org.bson.BasicBSONObject; -import org.bson.Document; -import org.bson.types.BasicBSONList; -import org.eclipse.rdf4j.model.vocabulary.DCAT; -import org.springframework.context.annotation.Profile; - -import java.util.List; - -@ChangeLog(order = "0004") -@Profile(Profiles.PRODUCTION) -public class Migration_0004_ResourceDefinition { - - private static final String R3D_REPOSITORY = "http://www.re3data.org/schema/3-0#Repository"; - private static final String R3D_HAS_CATALOG = "http://www.re3data.org/schema/3-0#dataCatalog"; - private static final String FIELD_TITLE = "title"; - private static final String FIELD_NAME = "name"; - private static final String FIELD_UUID = "uuid"; - private static final String FIELD_PERMISSIONS = "permissions"; - private static final String FIELD_MASK = "mask"; - private static final String FIELD_CODE = "code"; - private static final String FIELD_CLASS = "_class"; - - private static final int MASK_W = 2; - private static final int MASK_C = 4; - private static final int MASK_D = 8; - private static final int MASK_A = 16; - - @ChangeSet(order = "0004", id = "Migration_0004_ResourceDefinition", author = "migrationBot") - public void run(MongoDatabase database, ResourceDefinitionCache resourceDefinitionCache) { - migrateResourceDefinitions(database); - resourceDefinitionCache.computeCache(); - } - - private void migrateResourceDefinitions(MongoDatabase database) { - final MongoCollection rdCol = database.getCollection("resourceDefinition"); - rdCol.deleteMany(new Document()); - rdCol.insertOne(repositoryDefinition()); - rdCol.insertOne(catalogDefinition()); - rdCol.insertOne(datasetDefinition()); - rdCol.insertOne(distributionDefinition()); - - final MongoCollection membershipCol = database.getCollection("membership"); - membershipCol.deleteMany(new Document()); - membershipCol.insertOne(membershipOwner()); - membershipCol.insertOne(membershipDataProvider()); - } - - private Document repositoryDefinition() { - return createDefinition( - KnownUUIDs.RD_REPOSITORY_UUID, - "Repository", - "", - List.of(DCAT.RESOURCE.stringValue(), R3D_REPOSITORY), - List.of(createChild( - KnownUUIDs.RD_CATALOG_UUID, - R3D_HAS_CATALOG, - "Catalogs", - DCAT.THEME_TAXONOMY.stringValue(), - List.of() - )), - List.of() - ); - } - - private Document catalogDefinition() { - return createDefinition( - KnownUUIDs.RD_CATALOG_UUID, - "Catalog", - "catalog", - List.of(DCAT.RESOURCE.stringValue(), DCAT.CATALOG.stringValue()), - List.of(createChild( - KnownUUIDs.RD_DATASET_UUID, - DCAT.HAS_DATASET.stringValue(), - "Datasets", - DCAT.THEME.stringValue(), - List.of() - )), - List.of() - ); - } - - private Document datasetDefinition() { - return createDefinition( - KnownUUIDs.RD_DATASET_UUID, - "Dataset", - "dataset", - List.of(DCAT.RESOURCE.stringValue(), DCAT.DATASET.stringValue()), - List.of(createChild( - KnownUUIDs.RD_DISTRIBUTION_UUID, - DCAT.HAS_DISTRIBUTION.stringValue(), - "Distributions", - null, - List.of(createChildMetadata("Media Type", DCAT.MEDIA_TYPE.stringValue())) - )), - List.of() - ); - } - - private Document distributionDefinition() { - return createDefinition( - KnownUUIDs.RD_DISTRIBUTION_UUID, - "Distribution", - "distribution", - List.of(DCAT.RESOURCE.stringValue(), DCAT.DISTRIBUTION.stringValue()), - List.of(), - List.of( - createLink("Access online", DCAT.ACCESS_URL.stringValue()), - createLink("Download", DCAT.DOWNLOAD_URL.stringValue()) - ) - ); - } - - private Document createChildMetadata(String title, String property) { - return createLink(title, property); - } - - private Document createChild(String uuid, String relation, String title, String tagsUri, - List metadata) { - // Child - final Document child = new Document(); - child.append("resourceDefinitionUuid", uuid); - child.append("relationUri", relation); - // - list View - final Document listView = new Document(); - listView.append(FIELD_TITLE, title); - listView.append("tagsUri", tagsUri); - listView.append("metadata", metadata); - child.append("listView", listView); - return child; - } - - private Document createLink(String title, String property) { - final Document link = new Document(); - link.append(FIELD_TITLE, title); - link.append("propertyUri", property); - return link; - } - - private Document createDefinition(String uuid, String name, String prefix, List classes, - List children, List links) { - final Document definition = new Document(); - definition.append(FIELD_UUID, uuid); - definition.append(FIELD_NAME, name); - definition.append("urlPrefix", prefix); - definition.append("targetClassUris", classes); - definition.append("children", children); - definition.append("externalLinks", links); - definition.append(FIELD_CLASS, "nl.dtls.fairdatapoint.entity.resource.ResourceDefinition"); - return definition; - } - - private Document membershipOwner() { - return createMembership(KnownUUIDs.MEMBERSHIP_OWNER_UUID, "Owner", true); - } - - private Document membershipDataProvider() { - return createMembership(KnownUUIDs.MEMBERSHIP_DATAPROVIDER_UUID, "Data Provider", false); - } - - private Document createMembership(String uuid, String name, boolean owner) { - final Document membership = new Document(); - membership.append(FIELD_UUID, uuid); - membership.append(FIELD_NAME, name); - final BasicBSONList permissions = new BasicBSONList(); - permissions.add(new BasicBSONObject().append(FIELD_MASK, MASK_C).append(FIELD_CODE, "C")); - final BasicBSONList allowedEntities = new BasicBSONList(); - allowedEntities.add(KnownUUIDs.RD_CATALOG_UUID); - if (owner) { - permissions.add(new BasicBSONObject().append(FIELD_MASK, MASK_W).append(FIELD_CODE, "W")); - permissions.add(new BasicBSONObject().append(FIELD_MASK, MASK_D).append(FIELD_CODE, "D")); - permissions.add(new BasicBSONObject().append(FIELD_MASK, MASK_A).append(FIELD_CODE, "A")); - allowedEntities.add(KnownUUIDs.RD_DATASET_UUID); - allowedEntities.add(KnownUUIDs.RD_DISTRIBUTION_UUID); - } - membership.append(FIELD_PERMISSIONS, permissions); - membership.append("allowedEntities", allowedEntities); - membership.append(FIELD_CLASS, "nl.dtls.fairdatapoint.entity.membership.Membership"); - return membership; - } - -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0005_UpdateShapeDefinition.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0005_UpdateShapeDefinition.java deleted file mode 100644 index d99ff8edb..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0005_UpdateShapeDefinition.java +++ /dev/null @@ -1,94 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.production; - -import com.github.cloudyrock.mongock.ChangeLog; -import com.github.cloudyrock.mongock.ChangeSet; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import nl.dtls.fairdatapoint.Profiles; -import nl.dtls.fairdatapoint.util.KnownUUIDs; -import org.bson.Document; -import org.springframework.context.annotation.Profile; - -import static nl.dtls.fairdatapoint.util.ResourceReader.loadClassResource; - -@ChangeLog(order = "0005") -@Profile(Profiles.PRODUCTION) -public class Migration_0005_UpdateShapeDefinition { - - private static final String FIELD_UUID = "uuid"; - - @ChangeSet(order = "0005", id = "Migration_0005_UpdateShapeDefinition", author = "migrationBot") - public void run(MongoDatabase database) throws Exception { - addShapeDefinitions(database); - } - - private void addShapeDefinitions(MongoDatabase database) throws Exception { - final MongoCollection shapeCol = database.getCollection("shape"); - - shapeCol.deleteOne(new Document(FIELD_UUID, KnownUUIDs.SCHEMA_RESOURCE_UUID)); - shapeCol.deleteOne(new Document(FIELD_UUID, KnownUUIDs.SCHEMA_REPOSITORY_UUID)); - shapeCol.deleteOne(new Document(FIELD_UUID, KnownUUIDs.SCHEMA_CATALOG_UUID)); - shapeCol.deleteOne(new Document(FIELD_UUID, KnownUUIDs.SCHEMA_DATASET_UUID)); - shapeCol.deleteOne(new Document(FIELD_UUID, KnownUUIDs.SCHEMA_DISTRIBUTION_UUID)); - - shapeCol.insertOne(resourceDefinition()); - shapeCol.insertOne(repositoryDefinition()); - shapeCol.insertOne(catalogDefinition()); - shapeCol.insertOne(datasetDefinition()); - shapeCol.insertOne(distributionDefinition()); - } - - private Document resourceDefinition() throws Exception { - return createShape("0005_shape-resource.ttl", KnownUUIDs.SCHEMA_RESOURCE_UUID, "Resource"); - } - - private Document repositoryDefinition() throws Exception { - return createShape("0005_shape-repository.ttl", KnownUUIDs.SCHEMA_REPOSITORY_UUID, "Repository"); - } - - private Document catalogDefinition() throws Exception { - return createShape("0005_shape-catalog.ttl", KnownUUIDs.SCHEMA_CATALOG_UUID, "Catalog"); - } - - private Document datasetDefinition() throws Exception { - return createShape("0005_shape-dataset.ttl", KnownUUIDs.SCHEMA_DATASET_UUID, "Dataset"); - } - - private Document distributionDefinition() throws Exception { - return createShape("0005_shape-distribution.ttl", KnownUUIDs.SCHEMA_DISTRIBUTION_UUID, "Distribution"); - } - - private Document createShape(String filename, String uuid, String name) throws Exception { - final String shaclDefinition = loadClassResource(filename, getClass()); - final Document shape = new Document(); - shape.append(FIELD_UUID, uuid); - shape.append("name", name); - shape.append("type", "INTERNAL"); - shape.append("definition", shaclDefinition); - shape.append("_class", "nl.dtls.fairdatapoint.entity.shape.Shape"); - return shape; - } - -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0007_RemoveMongobee.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0007_RemoveMongobee.java deleted file mode 100644 index 072ab67e7..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0007_RemoveMongobee.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.production; - -import com.github.cloudyrock.mongock.ChangeLog; -import com.github.cloudyrock.mongock.ChangeSet; -import com.mongodb.client.MongoDatabase; -import nl.dtls.fairdatapoint.Profiles; -import org.springframework.context.annotation.Profile; - -@ChangeLog(order = "0007") -@Profile(Profiles.PRODUCTION) -public class Migration_0007_RemoveMongobee { - - @ChangeSet(order = "0007", id = "Migration_0007_RemoveMongobee", author = "migrationBot") - public void run(MongoDatabase database) { - database.getCollection("dbchangelog").drop(); - database.getCollection("mongobeelock").drop(); - } -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0008_ShapesInternalChange.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0008_ShapesInternalChange.java deleted file mode 100644 index 1d55a37f7..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0008_ShapesInternalChange.java +++ /dev/null @@ -1,62 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.production; - -import com.github.cloudyrock.mongock.ChangeLog; -import com.github.cloudyrock.mongock.ChangeSet; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.model.Filters; -import com.mongodb.client.model.Updates; -import nl.dtls.fairdatapoint.Profiles; -import nl.dtls.fairdatapoint.util.KnownUUIDs; -import org.bson.Document; -import org.springframework.context.annotation.Profile; - -@ChangeLog(order = "0008") -@Profile(Profiles.PRODUCTION) -public class Migration_0008_ShapesInternalChange { - - private static final String FIELD_UUID = "uuid"; - private static final String FIELD_TYPE = "type"; - private static final String VALUE_CUSTOM = "CUSTOM"; - - @ChangeSet(order = "0008", id = "Migration_0008_ShapesInternalChange", author = "migrationBot") - public void run(MongoDatabase database) { - updateInternalShapesType(database); - } - - private void updateInternalShapesType(MongoDatabase database) { - final MongoCollection shapeCol = database.getCollection("shape"); - // DATASET - shapeCol.updateOne( - Filters.eq(FIELD_UUID, KnownUUIDs.SCHEMA_DATASET_UUID), - Updates.set(FIELD_TYPE, VALUE_CUSTOM) - ); - // DISTRIBUTION - shapeCol.updateOne( - Filters.eq(FIELD_UUID, KnownUUIDs.SCHEMA_DISTRIBUTION_UUID), - Updates.set(FIELD_TYPE, VALUE_CUSTOM) - ); - } -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0009_ShapeTargetClasses.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0009_ShapeTargetClasses.java deleted file mode 100644 index 6f88f2b59..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0009_ShapeTargetClasses.java +++ /dev/null @@ -1,91 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.production; - -import com.github.cloudyrock.mongock.ChangeLog; -import com.github.cloudyrock.mongock.ChangeSet; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.model.Filters; -import com.mongodb.client.model.Updates; -import nl.dtls.fairdatapoint.Profiles; -import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionCache; -import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionTargetClassesCache; -import nl.dtls.fairdatapoint.service.schema.MetadataSchemaShaclUtils; -import org.bson.Document; -import org.springframework.context.annotation.Profile; - -import java.util.*; - -@ChangeLog(order = "0009") -@Profile(Profiles.PRODUCTION) -public class Migration_0009_ShapeTargetClasses { - - private static final String FIELD_UUID = "uuid"; - private static final String FILED_CLASSES = "targetClassUris"; - - @ChangeSet(order = "0009", id = "Migration_0009_ShapeTargetClasses", author = "migrationBot") - public void run(MongoDatabase database, ResourceDefinitionCache resourceDefinitionCache, - ResourceDefinitionTargetClassesCache targetClassesCache) { - updateShapesAndResources(database); - resourceDefinitionCache.computeCache(); - targetClassesCache.computeCache(); - } - - private void updateShapesAndResources(MongoDatabase database) { - final Map> targetClassesMap = new HashMap<>(); - // Update shapes - final MongoCollection shapeCol = database.getCollection("shape"); - for (Document document : shapeCol.find()) { - final String definition = (String) document.get("definition"); - final String uuid = (String) document.get(FIELD_UUID); - final Set targetClasses = MetadataSchemaShaclUtils.extractTargetClasses(definition); - targetClassesMap.put(uuid, targetClasses); - shapeCol.updateOne( - Filters.eq(FIELD_UUID, uuid), - Updates.set("targetClasses", targetClasses) - ); - } - // Update resource definitions - final MongoCollection rdCol = database.getCollection("resourceDefinition"); - for (Document document : rdCol.find()) { - final List targetClassUris = (List) document.get(FILED_CLASSES); - final Set shapeUuids = new HashSet<>(); - targetClassUris.forEach(uri -> { - targetClassesMap.forEach((shapeUuid, targetClasses) -> { - if (targetClasses.contains(uri)) { - shapeUuids.add(shapeUuid); - } - }); - }); - rdCol.updateOne( - Filters.eq(FIELD_UUID, document.get(FIELD_UUID)), - Updates.unset(FILED_CLASSES) - ); - rdCol.updateOne( - Filters.eq(FIELD_UUID, document.get(FIELD_UUID)), - Updates.set("shapeUuids", shapeUuids) - ); - } - } -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0010_FixShapeXsdPrefix.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0010_FixShapeXsdPrefix.java deleted file mode 100644 index eabcd76e3..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0010_FixShapeXsdPrefix.java +++ /dev/null @@ -1,81 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.production; - -import com.github.cloudyrock.mongock.ChangeLog; -import com.github.cloudyrock.mongock.ChangeSet; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import com.mongodb.client.model.Filters; -import com.mongodb.client.model.Updates; -import nl.dtls.fairdatapoint.Profiles; -import org.bson.Document; -import org.springframework.context.annotation.Profile; - -import java.util.List; -import java.util.stream.Collectors; - -@ChangeLog(order = "0010") -@Profile(Profiles.PRODUCTION) -public class Migration_0010_FixShapeXsdPrefix { - - private static final String XSD_PREFIX = "@prefix xsd: ."; - private static final String FIELD_UUID = "uuid"; - private static final String FIELD_DEFINITION = "definition"; - - @ChangeSet(order = "0010", id = "Migration_0010_FixShapeXsdPrefix", author = "migrationBot") - public void run(MongoDatabase database) { - fixShapePrefixes(database); - } - - private void fixShapePrefixes(MongoDatabase database) { - // catalog - fixShape("2aa7ba63-d27a-4c0e-bfa6-3a4e250f4660", database); - // dataset - fixShape("866d7fb8-5982-4215-9c7c-18d0ed1bd5f3", database); - // distribution - fixShape("ebacbf83-cd4f-4113-8738-d73c0735b0ab", database); - } - - private void fixShape(String shapeUuid, MongoDatabase database) { - final MongoCollection shapeCol = database.getCollection("shape"); - final Document shape = shapeCol.find(Filters.eq(FIELD_UUID, shapeUuid)).first(); - if (shape != null) { - final String definition = shape.getString(FIELD_DEFINITION); - final boolean isFaulty = definition.contains("xsd:") && !definition.contains("@prefix xsd:"); - if (isFaulty) { - final List lines = definition.lines().collect(Collectors.toList()); - int line = 0; - while (lines.get(line).startsWith("@prefix")) { - line++; - } - lines.add(line, XSD_PREFIX); - - shapeCol.updateOne( - Filters.eq(FIELD_UUID, shapeUuid), - Updates.set(FIELD_DEFINITION, String.join("\n", lines)) - ); - } - } - } -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0011_ComplyFDPO.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0011_ComplyFDPO.java deleted file mode 100644 index 271a10d00..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0011_ComplyFDPO.java +++ /dev/null @@ -1,138 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.production; - -import com.github.cloudyrock.mongock.ChangeLog; -import com.github.cloudyrock.mongock.ChangeSet; -import com.mongodb.client.MongoCollection; -import com.mongodb.client.MongoDatabase; -import nl.dtls.fairdatapoint.Profiles; -import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionCache; -import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionTargetClassesCache; -import nl.dtls.fairdatapoint.util.KnownUUIDs; -import nl.dtls.fairdatapoint.vocabulary.FDP; -import org.bson.Document; -import org.eclipse.rdf4j.model.vocabulary.DCAT; -import org.springframework.context.annotation.Profile; - -import java.util.*; - -import static nl.dtls.fairdatapoint.util.ResourceReader.loadClassResource; - -@ChangeLog(order = "0011") -@Profile(Profiles.PRODUCTION) -public class Migration_0011_ComplyFDPO { - - private static final String FIELD_UUID = "uuid"; - private static final String FIELD_NAME = "name"; - private static final String FIELD_CLASS = "_class"; - private static final String FDP_NAME = "FAIR Data Point"; - - @ChangeSet(order = "0011", id = "Migration_0011_ComplyFDPO", author = "migrationBot") - public void run(MongoDatabase database, ResourceDefinitionCache resourceDefinitionCache, - ResourceDefinitionTargetClassesCache targetClassesCache) throws Exception { - updateShapes(database); - updateResourceDefinitions(database); - resourceDefinitionCache.computeCache(); - targetClassesCache.computeCache(); - } - - private void updateShapes(MongoDatabase database) throws Exception { - final MongoCollection shapeCol = database.getCollection("shape"); - - // Delete Repository Shape - shapeCol.deleteOne(new Document(FIELD_UUID, KnownUUIDs.SCHEMA_REPOSITORY_UUID)); - - // Insert New Shapes - shapeCol.insertOne(dataServiceShape()); - shapeCol.insertOne(metadataServiceShape()); - shapeCol.insertOne(fdpShape()); - } - - private Document fdpShape() throws Exception { - return createShape("0011_shape-fdp.ttl", KnownUUIDs.SCHEMA_FDP_UUID, - FDP_NAME, List.of(FDP.FAIRDATAPOINT.stringValue())); - } - - private Document dataServiceShape() throws Exception { - return createShape("0011_shape-data-service.ttl", KnownUUIDs.SCHEMA_DATASERVICE_UUID, - "Data Service", List.of(DCAT.DATA_SERVICE.stringValue())); - } - - private Document metadataServiceShape() throws Exception { - return createShape("0011_shape-metadata-service.ttl", KnownUUIDs.SCHEMA_METADATASERVICE_UUID, - "Metadata Service", List.of(FDP.METADATASERVICE.stringValue())); - } - - private Document createShape(String filename, String uuid, String name, List classes) throws Exception { - final String shaclDefinition = loadClassResource(filename, getClass()); - final Document shape = new Document(); - shape.append(FIELD_UUID, uuid); - shape.append(FIELD_NAME, name); - shape.append("type", "INTERNAL"); - shape.append("definition", shaclDefinition); - shape.append("targetClasses", classes); - shape.append(FIELD_CLASS, "nl.dtls.fairdatapoint.entity.shape.Shape"); - return shape; - } - - private void updateResourceDefinitions(MongoDatabase database) { - final MongoCollection rdCol = database.getCollection("resourceDefinition"); - - // Delete Repository Shape - rdCol.deleteOne(new Document(FIELD_UUID, KnownUUIDs.RD_REPOSITORY_UUID)); - - // Insert New Shapes - rdCol.insertOne(fdpResourceDefinition()); - } - - private Document fdpResourceDefinition() { - final Document definition = new Document(); - definition.append(FIELD_UUID, KnownUUIDs.RD_FDP_UUID); - definition.append(FIELD_NAME, FDP_NAME); - definition.append("urlPrefix", ""); - definition.append("shapeUuids", List.of( - KnownUUIDs.SCHEMA_RESOURCE_UUID, - KnownUUIDs.SCHEMA_DATASERVICE_UUID, - KnownUUIDs.SCHEMA_METADATASERVICE_UUID, - KnownUUIDs.SCHEMA_FDP_UUID - )); - - // Child - final Document child = new Document(); - child.append("resourceDefinitionUuid", KnownUUIDs.RD_CATALOG_UUID); - child.append("relationUri", FDP.METADATACATALOG.stringValue()); - final Document listView = new Document(); - listView.append("title", "Catalogs"); - listView.append("tagsUri", DCAT.THEME_TAXONOMY.stringValue()); - listView.append("metadata", List.of()); - child.append("listView", listView); - definition.append("children", List.of(child)); - - // External Links - definition.append("externalLinks", List.of()); - - definition.append(FIELD_CLASS, "nl.dtls.fairdatapoint.entity.resource.ResourceDefinition"); - return definition; - } -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0012_MetadataSchemas.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0012_MetadataSchemas.java deleted file mode 100644 index 66988b6ad..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0012_MetadataSchemas.java +++ /dev/null @@ -1,259 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.production; - -import com.mongodb.client.MongoCollection; -import com.mongodb.client.model.Filters; -import com.mongodb.client.model.Updates; -import io.mongock.api.annotations.ChangeUnit; -import io.mongock.api.annotations.Execution; -import io.mongock.api.annotations.RollbackExecution; -import nl.dtls.fairdatapoint.Profiles; -import nl.dtls.fairdatapoint.entity.schema.SemVer; -import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionCache; -import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionTargetClassesCache; -import nl.dtls.fairdatapoint.service.schema.MetadataSchemaShaclUtils; -import nl.dtls.fairdatapoint.util.KnownUUIDs; -import org.bson.Document; -import org.springframework.context.annotation.Profile; -import org.springframework.data.mongodb.core.MongoTemplate; - -import java.time.Instant; -import java.util.*; - -@ChangeUnit(id = "Migration_0012_MetadataSchemas", order = "0012", author = "migrationBot") -@Profile(Profiles.PRODUCTION) -public class Migration_0012_MetadataSchemas { - - private static final String FDP_APP_URL = "https://purl.org/fairdatapoint/app"; - private static final String COL_SHAPES = "shape"; - private static final String COL_SCHEMAS = "metadataSchema"; - private static final String COL_DRAFTS = "metadataSchemaDraft"; - private static final String COL_RD = "resourceDefinition"; - private static final String FIELD_UUID = "uuid"; - private static final String FIELD_NAME = "name"; - private static final String FIELD_DEFINITION = "definition"; - private static final String FIELD_CLASSES = "targetClasses"; - private static final String FIELD_TYPE = "type"; - private static final String FIELD_LATEST = "latest"; - private static final String FIELD_PUBLISHED = "published"; - private static final String FIELD_SHAPES = "shapeUuids"; - private static final String FIELD_SCHEMAS = "metadataSchemaUuids"; - private static final String TYPE_INTERNAL = "INTERNAL"; - private static final String TYPE_CUSTOM = "CUSTOM"; - private static final String KEY_RESOURCE = "r"; - private static final String KEY_DATA_SERVICE = "d"; - private static final String KEY_METADATA_SERVICE = "m"; - - private final MongoTemplate database; - - public Migration_0012_MetadataSchemas(MongoTemplate template) { - this.database = template; - } - - @Execution - public void run(ResourceDefinitionCache resourceDefinitionCache, - ResourceDefinitionTargetClassesCache targetClassesCache) { - updateInternalShapesType(); - updateResourceDefinitionLinks(); - - resourceDefinitionCache.computeCache(); - targetClassesCache.computeCache(); - } - - private void updateInternalShapesType() { - final MongoCollection shapeCol = database.getCollection(COL_SHAPES); - final MongoCollection schemaCol = database.createCollection(COL_SCHEMAS); - database.createCollection(COL_DRAFTS); - - // Check default schemas presence - final Map existsMap = Map.of( - KEY_RESOURCE, docWithUuidExists(shapeCol, KnownUUIDs.SCHEMA_RESOURCE_UUID), - KEY_DATA_SERVICE, docWithUuidExists(shapeCol, KnownUUIDs.SCHEMA_DATASERVICE_UUID), - KEY_METADATA_SERVICE, docWithUuidExists(shapeCol, KnownUUIDs.SCHEMA_METADATASERVICE_UUID) - ); - - // Migrate shapes to schemas - shapeCol.find().forEach(shapeDoc -> schemaCol.insertOne(shapeToSchema(shapeDoc, existsMap))); - database.dropCollection(COL_SHAPES); - } - - private Document shapeToSchema(Document shape, Map existsMap) { - final SemVer version = new SemVer("1.0.0"); - final Instant now = Instant.now(); - final String schemaUuid = shape.getString(FIELD_UUID); - // Internal shapes - String origin = null; - String versionUuid = UUID.randomUUID().toString(); - String suggestedResourceName = null; - String suggestedUrlPrefix = null; - boolean isAbstract = false; - if (Objects.equals(schemaUuid, KnownUUIDs.SCHEMA_RESOURCE_UUID)) { - isAbstract = true; - versionUuid = KnownUUIDs.SCHEMA_V1_RESOURCE_UUID; - origin = FDP_APP_URL; - } - else if (Objects.equals(schemaUuid, KnownUUIDs.SCHEMA_FDP_UUID)) { - versionUuid = KnownUUIDs.SCHEMA_V1_FDP_UUID; - origin = FDP_APP_URL; - suggestedResourceName = "FAIR Data Point"; - suggestedUrlPrefix = ""; - } - else if (Objects.equals(schemaUuid, KnownUUIDs.SCHEMA_DATASERVICE_UUID)) { - versionUuid = KnownUUIDs.SCHEMA_V1_DATASERVICE_UUID; - origin = FDP_APP_URL; - suggestedResourceName = "Data Service"; - suggestedUrlPrefix = "data-service"; - } - else if (Objects.equals(schemaUuid, KnownUUIDs.SCHEMA_METADATASERVICE_UUID)) { - versionUuid = KnownUUIDs.SCHEMA_V1_METADATASERVICE_UUID; - origin = FDP_APP_URL; - suggestedResourceName = "Metadata Service"; - suggestedUrlPrefix = "metadata-service"; - } - else if (Objects.equals(schemaUuid, KnownUUIDs.SCHEMA_CATALOG_UUID)) { - versionUuid = KnownUUIDs.SCHEMA_V1_CATALOG_UUID; - origin = FDP_APP_URL; - suggestedResourceName = "Catalog"; - suggestedUrlPrefix = "catalog"; - } - else if (Objects.equals(schemaUuid, KnownUUIDs.SCHEMA_DATASET_UUID)) { - versionUuid = KnownUUIDs.SCHEMA_V1_DATASET_UUID; - origin = FDP_APP_URL; - suggestedResourceName = "Dataset"; - suggestedUrlPrefix = "dataset"; - } - else if (Objects.equals(schemaUuid, KnownUUIDs.SCHEMA_DISTRIBUTION_UUID)) { - versionUuid = KnownUUIDs.SCHEMA_V1_DISTRIBUTION_UUID; - origin = FDP_APP_URL; - suggestedResourceName = "Distribution"; - suggestedUrlPrefix = "distribution"; - } - // Prepare - final Document schemaDoc = new Document(); - schemaDoc.append(FIELD_UUID, schemaUuid); - schemaDoc.append("versionUuid", versionUuid); - schemaDoc.append("versionString", version.toString()); - schemaDoc.append(FIELD_NAME, shape.getString(FIELD_NAME)); - schemaDoc.append("description", ""); - schemaDoc.append(FIELD_DEFINITION, shape.getString(FIELD_DEFINITION)); - schemaDoc.append(FIELD_CLASSES, - MetadataSchemaShaclUtils.extractTargetClasses(shape.getString(FIELD_DEFINITION))); - schemaDoc.append("extendSchemas", prepareExtends(schemaUuid, existsMap)); - schemaDoc.append(FIELD_TYPE, shape.get(FIELD_TYPE)); - schemaDoc.append("origin", origin); - schemaDoc.append("importedFrom", origin); - schemaDoc.append(FIELD_LATEST, true); - schemaDoc.append("previousVersionUuid", null); - schemaDoc.append(FIELD_PUBLISHED, shape.getBoolean(FIELD_PUBLISHED, false)); - schemaDoc.append("abstractSchema", isAbstract); - schemaDoc.append("suggestedResourceName", suggestedResourceName); - schemaDoc.append("suggestedUrlPrefix", suggestedUrlPrefix); - schemaDoc.append("createdAt", now); - return schemaDoc; - } - - private List prepareExtends(String schemaUuid, Map existsMap) { - final List extendSchemas = new ArrayList<>(); - if (Objects.equals(schemaUuid, KnownUUIDs.SCHEMA_FDP_UUID) && existsMap.get(KEY_METADATA_SERVICE)) { - // FAIRDataPoint extends MetadataService - extendSchemas.add(KnownUUIDs.SCHEMA_METADATASERVICE_UUID); - } - else if (Objects.equals(schemaUuid, KnownUUIDs.SCHEMA_METADATASERVICE_UUID) - && existsMap.get(KEY_DATA_SERVICE)) { - // MetadataService extends DataService - extendSchemas.add(KnownUUIDs.SCHEMA_DATASERVICE_UUID); - } - else if (!Objects.equals(schemaUuid, KnownUUIDs.SCHEMA_RESOURCE_UUID) && existsMap.get(KEY_RESOURCE)) { - // Everything else (except Resource) extends Resource - extendSchemas.add(KnownUUIDs.SCHEMA_RESOURCE_UUID); - } - return extendSchemas; - } - - private void updateResourceDefinitionLinks() { - final MongoCollection rdCol = database.getCollection(COL_RD); - // Rename shape to metadata schema - rdCol.updateMany( - Filters.exists(FIELD_SHAPES), - Updates.rename(FIELD_SHAPES, FIELD_SCHEMAS) - ); - // Remove Resource link (it is abstract) - rdCol.find().forEach(rdDoc -> { - final ArrayList metadataSchemaUuids = (ArrayList) rdDoc.get(FIELD_SCHEMAS); - if (metadataSchemaUuids.contains(KnownUUIDs.SCHEMA_RESOURCE_UUID)) { - rdCol.updateOne( - Filters.eq(FIELD_UUID, rdDoc.get(FIELD_UUID)), - Updates.set( - FIELD_SCHEMAS, - metadataSchemaUuids - .stream() - .filter(uuid -> !Objects.equals(uuid, KnownUUIDs.SCHEMA_RESOURCE_UUID)) - .toList() - ) - ); - } - }); - } - - private boolean docWithUuidExists(MongoCollection collection, String uuid) { - return collection.find(Filters.eq(FIELD_UUID, uuid)).first() != null; - } - - @RollbackExecution - public void rollback() { - // updateInternalShapesType - final MongoCollection shapeCol = database.getCollection(COL_SHAPES); - final MongoCollection schemaCol = database.getCollection(COL_SCHEMAS); - schemaCol.find(Filters.eq(FIELD_LATEST, true)).forEach(schemaDoc -> { - final Document shapeDoc = new Document(); - shapeDoc.append(FIELD_UUID, schemaDoc.getString(FIELD_UUID)); - shapeDoc.append(FIELD_NAME, schemaDoc.getString(FIELD_NAME)); - shapeDoc.append(FIELD_DEFINITION, schemaDoc.getString(FIELD_DEFINITION)); - shapeDoc.append(FIELD_CLASSES, schemaDoc.get(FIELD_CLASSES)); - shapeDoc.append(FIELD_TYPE, schemaDoc.get(FIELD_TYPE).equals(TYPE_INTERNAL) ? TYPE_INTERNAL : TYPE_CUSTOM); - shapeDoc.append(FIELD_PUBLISHED, schemaDoc.getBoolean(FIELD_PUBLISHED, false)); - shapeCol.insertOne(shapeDoc); - }); - database.dropCollection(COL_SCHEMAS); - database.dropCollection(COL_DRAFTS); - // updateResourceDefinitionLinks - final MongoCollection rdCol = database.getCollection(COL_RD); - // Add Resource link (it is abstract) - rdCol.find().forEach(rdDoc -> { - final ArrayList metadataSchemaUuids = (ArrayList) rdDoc.get(FIELD_SCHEMAS); - if (!metadataSchemaUuids.contains(KnownUUIDs.SCHEMA_RESOURCE_UUID)) { - metadataSchemaUuids.add(KnownUUIDs.SCHEMA_RESOURCE_UUID); - rdCol.updateOne( - Filters.eq(FIELD_UUID, rdDoc.get(FIELD_UUID)), - Updates.set(FIELD_SCHEMAS, metadataSchemaUuids) - ); - } - }); - // Rename metadata schema to shape - rdCol.updateMany( - Filters.exists(FIELD_SCHEMAS), - Updates.rename(FIELD_SCHEMAS, FIELD_SHAPES) - ); - } -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0013_ComplexSearch.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0013_ComplexSearch.java deleted file mode 100644 index e60065e43..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0013_ComplexSearch.java +++ /dev/null @@ -1,78 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.production; - -import com.mongodb.client.MongoCollection; -import com.mongodb.client.model.Filters; -import com.mongodb.client.model.Updates; -import io.mongock.api.annotations.ChangeUnit; -import io.mongock.api.annotations.Execution; -import io.mongock.api.annotations.RollbackExecution; -import nl.dtls.fairdatapoint.Profiles; -import nl.dtls.fairdatapoint.service.settings.SettingsCache; -import org.bson.Document; -import org.springframework.context.annotation.Profile; -import org.springframework.data.mongodb.core.MongoTemplate; - -import java.util.Collections; - -@ChangeUnit( - id = "Migration_0013_ComplexSearch", - order = "0013", - author = "migrationBot" -) -@Profile(Profiles.PRODUCTION) -public class Migration_0013_ComplexSearch { - - private static final String COL_SETTINGS = "settings"; - private static final String FIELD_SEARCH_FILTERS = "searchFilters"; - - private final MongoTemplate database; - - public Migration_0013_ComplexSearch(MongoTemplate template) { - this.database = template; - } - - @Execution - public void run(SettingsCache settingsCache) { - addSearchRelatedSettings(); - settingsCache.updateCachedSettings(); - } - - private void addSearchRelatedSettings() { - final MongoCollection settingsCol = database.getCollection(COL_SETTINGS); - settingsCol.updateMany( - Filters.not(Filters.exists(FIELD_SEARCH_FILTERS)), - Updates.set(FIELD_SEARCH_FILTERS, Collections.emptyList()) - ); - } - - @RollbackExecution - public void rollback() { - final MongoCollection settingsCol = database.getCollection(COL_SETTINGS); - settingsCol.updateMany( - Filters.exists(FIELD_SEARCH_FILTERS), - Updates.unset(FIELD_SEARCH_FILTERS) - ); - } -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0014_FormsAutocomplete.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0014_FormsAutocomplete.java deleted file mode 100644 index c2c881080..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0014_FormsAutocomplete.java +++ /dev/null @@ -1,86 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.production; - -import com.mongodb.client.MongoCollection; -import com.mongodb.client.model.Filters; -import com.mongodb.client.model.Updates; -import io.mongock.api.annotations.ChangeUnit; -import io.mongock.api.annotations.Execution; -import io.mongock.api.annotations.RollbackExecution; -import nl.dtls.fairdatapoint.Profiles; -import nl.dtls.fairdatapoint.service.settings.SettingsCache; -import org.bson.Document; -import org.springframework.context.annotation.Profile; -import org.springframework.data.mongodb.core.MongoTemplate; - -import java.util.Collections; - -@ChangeUnit( - id = "Migration_0014_FormsAutocomplete", - order = "0014", - author = "migrationBot" -) -@Profile(Profiles.PRODUCTION) -public class Migration_0014_FormsAutocomplete { - - private static final String COL_SETTINGS = "settings"; - private static final String FIELD_FORMS = "forms"; - private static final String FIELD_AUTOCOMPLETE = "autocomplete"; - private static final String FIELD_SEARCH_NAMESPACE = "searchNamespace"; - private static final String FIELD_SOURCES = "sources"; - - private final MongoTemplate database; - - public Migration_0014_FormsAutocomplete(MongoTemplate template) { - this.database = template; - } - - @Execution - public void run(SettingsCache settingsCache) { - addSearchRelatedSettings(); - settingsCache.updateCachedSettings(); - } - - private void addSearchRelatedSettings() { - final MongoCollection settingsCol = database.getCollection(COL_SETTINGS); - final Document forms = new Document(); - final Document autocomplete = new Document(); - autocomplete.put(FIELD_SEARCH_NAMESPACE, true); - autocomplete.put(FIELD_SOURCES, Collections.emptyList()); - forms.put(FIELD_AUTOCOMPLETE, autocomplete); - settingsCol.updateMany( - Filters.not(Filters.exists(FIELD_FORMS)), - Updates.set(FIELD_FORMS, forms) - ); - } - - @RollbackExecution - public void rollback() { - final MongoCollection settingsCol = database.getCollection(COL_SETTINGS); - settingsCol.updateMany( - Filters.exists(FIELD_FORMS), - Updates.unset(FIELD_FORMS) - ); - } -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0015_FixMetadataVersion.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0015_FixMetadataVersion.java deleted file mode 100644 index b09519216..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0015_FixMetadataVersion.java +++ /dev/null @@ -1,123 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.production; - -import com.mongodb.client.MongoCollection; -import com.mongodb.client.model.Filters; -import com.mongodb.client.model.Updates; -import io.mongock.api.annotations.ChangeUnit; -import io.mongock.api.annotations.Execution; -import io.mongock.api.annotations.RollbackExecution; -import nl.dtls.fairdatapoint.Profiles; -import nl.dtls.fairdatapoint.entity.schema.SemVer; -import nl.dtls.fairdatapoint.util.KnownUUIDs; -import org.bson.Document; -import org.springframework.context.annotation.Profile; -import org.springframework.data.mongodb.core.MongoTemplate; - -@ChangeUnit( - id = "Migration_0015_FixMetadataVersion", - order = "0015", - author = "migrationBot" -) -@Profile(Profiles.PRODUCTION) -public class Migration_0015_FixMetadataVersion { - - private static final String FIELD_UUID = "uuid"; - private static final String FIELD_VER_UUID = "versionUuid"; - private static final String FIELD_LATEST = "latest"; - private static final String FIELD_VERSION = "versionString"; - private static final String FIELD_DEF = "definition"; - private static final String COL_SCHEMAS = "metadataSchema"; - - private final MongoTemplate database; - - private String previousVersionUuid; - - public Migration_0015_FixMetadataVersion(MongoTemplate template) { - this.database = template; - } - - @Execution - public void run() { - final MongoCollection schemasCol = database.getCollection(COL_SCHEMAS); - final Document latestResourcesSchema = schemasCol.find( - Filters.and( - Filters.eq(FIELD_UUID, KnownUUIDs.SCHEMA_RESOURCE_UUID), - Filters.eq(FIELD_LATEST, true) - ) - ).first(); - if (latestResourcesSchema == null) { - return; - } - previousVersionUuid = latestResourcesSchema.getString(FIELD_VER_UUID); - latestResourcesSchema.put( - FIELD_DEF, - latestResourcesSchema - .getString(FIELD_DEF) - .replace( - """ - sh:path dct:hasVersion ; - sh:name "version" ; - sh:nodeKind sh:Literal ; - """, - """ - sh:path dcat:version ; - sh:nodeKind sh:Literal ; - """ - ) - ); - latestResourcesSchema.remove("_id"); - latestResourcesSchema.put(FIELD_VER_UUID, KnownUUIDs.SCHEMA_V2_RESOURCE_UUID); - latestResourcesSchema.put(FIELD_LATEST, true); - final SemVer semVer = new SemVer(latestResourcesSchema.getString(FIELD_VERSION)); - semVer.setPatch(semVer.getPatch() + 1); - latestResourcesSchema.put(FIELD_VERSION, semVer.toString()); - schemasCol.updateMany( - Filters.and( - Filters.eq(FIELD_UUID, KnownUUIDs.SCHEMA_RESOURCE_UUID), - Filters.eq(FIELD_VER_UUID, previousVersionUuid) - ), - Updates.set(FIELD_LATEST, false) - ); - schemasCol.insertOne(latestResourcesSchema); - } - - @RollbackExecution - public void rollback() { - final MongoCollection schemasCol = database.getCollection(COL_SCHEMAS); - schemasCol.deleteOne( - Filters.and( - Filters.eq(FIELD_UUID, KnownUUIDs.SCHEMA_RESOURCE_UUID), - Filters.eq(FIELD_VER_UUID, KnownUUIDs.SCHEMA_V2_RESOURCE_UUID) - ) - ); - schemasCol.updateOne( - Filters.and( - Filters.eq(FIELD_UUID, KnownUUIDs.SCHEMA_RESOURCE_UUID), - Filters.eq(FIELD_VER_UUID, previousVersionUuid) - ), - Updates.set(FIELD_LATEST, true) - ); - } -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0016_IndexSettingsAutoPermit.java b/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0016_IndexSettingsAutoPermit.java deleted file mode 100644 index 363ab3eb8..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/production/Migration_0016_IndexSettingsAutoPermit.java +++ /dev/null @@ -1,70 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.database.mongo.migration.production; - -import com.mongodb.client.MongoCollection; -import com.mongodb.client.model.Filters; -import com.mongodb.client.model.Updates; -import io.mongock.api.annotations.ChangeUnit; -import io.mongock.api.annotations.Execution; -import io.mongock.api.annotations.RollbackExecution; -import nl.dtls.fairdatapoint.Profiles; -import org.bson.Document; -import org.springframework.context.annotation.Profile; -import org.springframework.data.mongodb.core.MongoTemplate; - -@ChangeUnit( - id = "Migration_0016_IndexSettingsAutoPermit", - order = "0016", - author = "migrationBot" -) -@Profile(Profiles.PRODUCTION) -public class Migration_0016_IndexSettingsAutoPermit { - - private static final String FIELD_AUTO_PERMIT = "autoPermit"; - private static final String COL_INDEX_SETTINGS = "indexSettings"; - - private final MongoTemplate database; - - public Migration_0016_IndexSettingsAutoPermit(MongoTemplate template) { - this.database = template; - } - - @Execution - public void run() { - final MongoCollection settingsCol = database.getCollection(COL_INDEX_SETTINGS); - settingsCol.updateMany( - Filters.not(Filters.exists(FIELD_AUTO_PERMIT)), - Updates.set(FIELD_AUTO_PERMIT, true) - ); - } - - @RollbackExecution - public void rollback() { - final MongoCollection settingsCol = database.getCollection(COL_INDEX_SETTINGS); - settingsCol.updateMany( - Filters.exists(FIELD_AUTO_PERMIT), - Updates.unset(FIELD_AUTO_PERMIT) - ); - } -} diff --git a/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/development/RdfDevelopmentMigrationRunner.java b/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/RdfDevelopmentMigrationRunner.java similarity index 59% rename from src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/development/RdfDevelopmentMigrationRunner.java rename to src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/RdfDevelopmentMigrationRunner.java index cb2a5b358..c6dcd7250 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/development/RdfDevelopmentMigrationRunner.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/RdfDevelopmentMigrationRunner.java @@ -20,27 +20,53 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.database.rdf.migration.development; +package nl.dtls.fairdatapoint.database.rdf.migration; import jakarta.annotation.PostConstruct; import nl.dtls.fairdatapoint.Profiles; +import nl.dtls.fairdatapoint.database.rdf.migration.development.metadata.AclMigration; import nl.dtls.fairdatapoint.database.rdf.migration.development.metadata.RdfMetadataMigration; +import nl.dtls.fairdatapoint.database.rdf.repository.RepositoryMode; +import nl.dtls.fairdatapoint.database.rdf.repository.exception.MetadataRepositoryException; +import nl.dtls.fairdatapoint.database.rdf.repository.generic.GenericMetadataRepository; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.DependsOn; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Profile; import org.springframework.stereotype.Service; @Service -@DependsOn("mongockRunner") @Profile(Profiles.NON_PRODUCTION) public class RdfDevelopmentMigrationRunner { + @Value("${spring.profiles.active}") + private String activeProfile; + @Autowired private RdfMetadataMigration rdfMetadataMigration; + @Autowired + private AclMigration aclMigration; + + @Autowired + @Qualifier("genericMetadataRepository") + private GenericMetadataRepository metadataRepository; + @PostConstruct public void run() { rdfMetadataMigration.runMigration(); + if (activeProfile.equals(Profiles.DEVELOPMENT)) { + aclMigration.runMigration(); + } } + public void clean() { + try { + metadataRepository.removeAll(RepositoryMode.MAIN); + metadataRepository.removeAll(RepositoryMode.DRAFTS); + } + catch (MetadataRepositoryException exc) { + throw new RuntimeException(exc); + } + } } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/acl/AclMigration.java b/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/development/metadata/AclMigration.java similarity index 62% rename from src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/acl/AclMigration.java rename to src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/development/metadata/AclMigration.java index b439ca4cb..789bdb1a8 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/acl/AclMigration.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/development/metadata/AclMigration.java @@ -20,85 +20,69 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.database.mongo.migration.development.acl; +package nl.dtls.fairdatapoint.database.rdf.migration.development.metadata; -import nl.dtls.fairdatapoint.database.common.migration.Migration; -import nl.dtls.fairdatapoint.database.mongo.migration.development.membership.data.MembershipFixtures; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; import nl.dtls.fairdatapoint.entity.metadata.Metadata; import nl.dtls.fairdatapoint.service.member.MemberService; -import nl.dtls.fairdatapoint.service.security.MongoAuthenticationService; +import nl.dtls.fairdatapoint.service.security.AuthenticationService; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.security.acls.dao.AclRepository; import org.springframework.security.acls.model.AclCache; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.stereotype.Service; +import org.springframework.stereotype.Component; import static java.lang.String.format; -@Service -public class AclMigration implements Migration { +@Component +public class AclMigration { @Autowired @Qualifier("persistentUrl") private String persistentUrl; - @Autowired - private UserFixtures userFixtures; - - @Autowired - private MembershipFixtures membershipFixtures; - - @Autowired - private AclRepository aclRepository; - @Autowired private MemberService memberService; @Autowired - private MongoAuthenticationService mongoAuthenticationService; + private AuthenticationService authenticationService; @Autowired private AclCache aclCache; public void runMigration() { - aclRepository.deleteAll(); aclCache.clearCache(); - final String albertUuid = userFixtures.albert().getUuid(); - final String nicolaUuid = userFixtures.nikola().getUuid(); - final String ownerUuid = membershipFixtures.owner().getUuid(); - final String dataProviderUuid = membershipFixtures.dataProvider().getUuid(); - final Authentication auth = mongoAuthenticationService.getAuthentication(albertUuid); + final Authentication auth = authenticationService.getAuthentication(KnownUUIDs.USER_ALBERT_UUID.toString()); SecurityContextHolder.getContext().setAuthentication(auth); // -- Catalog final String catalog1Id = format("%s/catalog/catalog-1", persistentUrl); - memberService.createOwner(catalog1Id, Metadata.class, albertUuid); + memberService.createOwner(catalog1Id, Metadata.class, KnownUUIDs.USER_ALBERT_UUID); memberService.createOrUpdateMember( - catalog1Id, Metadata.class, nicolaUuid, dataProviderUuid + catalog1Id, Metadata.class, KnownUUIDs.USER_NIKOLA_UUID, KnownUUIDs.MEMBERSHIP_DATAPROVIDER_UUID ); final String catalog2Id = format("%s/catalog/catalog-2", persistentUrl); - memberService.createOwner(catalog2Id, Metadata.class, albertUuid); + memberService.createOwner(catalog2Id, Metadata.class, KnownUUIDs.USER_ALBERT_UUID); // -- Dataset final String dataset1Id = format("%s/dataset/dataset-1", persistentUrl); - memberService.createOwner(dataset1Id, Metadata.class, albertUuid); - memberService.createOrUpdateMember(dataset1Id, Metadata.class, nicolaUuid, ownerUuid); + memberService.createOwner(dataset1Id, Metadata.class, KnownUUIDs.USER_ALBERT_UUID); + memberService.createOrUpdateMember(dataset1Id, Metadata.class, + KnownUUIDs.USER_NIKOLA_UUID, KnownUUIDs.MEMBERSHIP_OWNER_UUID); final String dataset2Id = format("%s/dataset/dataset-2", persistentUrl); - memberService.createOwner(dataset2Id, Metadata.class, albertUuid); + memberService.createOwner(dataset2Id, Metadata.class, KnownUUIDs.USER_ALBERT_UUID); // -- Distribution final String distribution1Id = format("%s/distribution/distribution-1", persistentUrl); - memberService.createOwner(distribution1Id, Metadata.class, albertUuid); - memberService.createOrUpdateMember(distribution1Id, Metadata.class, nicolaUuid, ownerUuid); + memberService.createOwner(distribution1Id, Metadata.class, KnownUUIDs.USER_ALBERT_UUID); + memberService.createOrUpdateMember(distribution1Id, Metadata.class, + KnownUUIDs.USER_NIKOLA_UUID, KnownUUIDs.MEMBERSHIP_OWNER_UUID); final String distribution2Id = format("%s/distribution/distribution-2", persistentUrl); - memberService.createOwner(distribution2Id, Metadata.class, albertUuid); + memberService.createOwner(distribution2Id, Metadata.class, KnownUUIDs.USER_ALBERT_UUID); } - } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/development/metadata/RdfMetadataMigration.java b/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/development/metadata/RdfMetadataMigration.java index 20479da3a..941c216e7 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/development/metadata/RdfMetadataMigration.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/development/metadata/RdfMetadataMigration.java @@ -24,18 +24,20 @@ import nl.dtls.fairdatapoint.api.dto.metadata.MetaStateChangeDTO; import nl.dtls.fairdatapoint.database.common.migration.Migration; -import nl.dtls.fairdatapoint.database.mongo.migration.development.resource.data.ResourceDefinitionFixtures; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; +import nl.dtls.fairdatapoint.database.db.repository.ResourceDefinitionRepository; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; import nl.dtls.fairdatapoint.database.rdf.migration.development.metadata.data.RdfMetadataFixtures; import nl.dtls.fairdatapoint.database.rdf.repository.RepositoryMode; import nl.dtls.fairdatapoint.database.rdf.repository.exception.MetadataRepositoryException; import nl.dtls.fairdatapoint.database.rdf.repository.generic.GenericMetadataRepository; import nl.dtls.fairdatapoint.entity.metadata.MetadataState; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import nl.dtls.fairdatapoint.service.metadata.common.MetadataService; import nl.dtls.fairdatapoint.service.metadata.exception.MetadataServiceException; import nl.dtls.fairdatapoint.service.metadata.state.MetadataStateService; -import nl.dtls.fairdatapoint.service.security.MongoAuthenticationService; +import nl.dtls.fairdatapoint.service.security.AuthenticationService; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; import org.springframework.beans.factory.annotation.Autowired; @@ -50,9 +52,6 @@ @Service public class RdfMetadataMigration implements Migration { - @Autowired - private GenericMetadataRepository metadataRepository; - @Autowired private RdfMetadataFixtures rdfMetadataFixtures; @@ -65,44 +64,60 @@ public class RdfMetadataMigration implements Migration { private MetadataService genericMetadataService; @Autowired - private UserFixtures userFixtures; + private MetadataStateService metadataStateService; @Autowired - private ResourceDefinitionFixtures resourceDefinitionFixtures; + @Qualifier("persistentUrl") + private String persistentUrl; @Autowired - private MongoAuthenticationService mongoAuthenticationService; + private AuthenticationService authenticationService; @Autowired - private MetadataStateService metadataStateService; + private ResourceDefinitionRepository resourceDefinitionRepository; @Autowired - @Qualifier("persistentUrl") - private String persistentUrl; + private UserAccountRepository userAccountRepository; - public void runMigration() { + @Autowired + @Qualifier("genericMetadataRepository") + private GenericMetadataRepository metadataRepository; + + public void clean() { try { - // 1. Remove all previous metadata - metadataRepository.removeAll(RepositoryMode.COMBINED); + metadataRepository.removeAll(RepositoryMode.MAIN); + metadataRepository.removeAll(RepositoryMode.DRAFTS); + // TODO: delete acl? + } + catch (MetadataRepositoryException exc) { + throw new RuntimeException(exc); + } + } - // 2. Auth user - final String adminUuid = userFixtures.admin().getUuid(); - final Authentication auth = mongoAuthenticationService.getAuthentication(adminUuid); + public void runMigration() { + try { + // Auth user + final UserAccount user = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); + final Authentication auth = authenticationService.getAuthentication(user.getUuid().toString()); SecurityContextHolder.getContext().setAuthentication(auth); - // 3. Load metadata fixtures + // Load metadata fixtures importDefaultFixtures(persistentUrl); } - catch (MetadataServiceException | MetadataRepositoryException exception) { + catch (MetadataServiceException exception) { exception.printStackTrace(); } } public void importDefaultFixtures(String fdpUrl) throws MetadataServiceException { - final ResourceDefinition fdpRd = resourceDefinitionFixtures.fdpDefinition(); - final ResourceDefinition catalogRd = resourceDefinitionFixtures.catalogDefinition(); - final ResourceDefinition datasetRd = resourceDefinitionFixtures.datasetDefinition(); - final ResourceDefinition distributionRd = resourceDefinitionFixtures.distributionDefinition(); + final ResourceDefinition fdpRd = + resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_FDP_UUID).get(); + final ResourceDefinition catalogRd = + resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_CATALOG_UUID).get(); + final ResourceDefinition datasetRd = + resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DATASET_UUID).get(); + final ResourceDefinition distributionRd = + resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); final Model fdpM = rdfMetadataFixtures.fdpMetadata(fdpUrl); final IRI fdpUri = getUri(fdpM); @@ -136,5 +151,4 @@ public void importDefaultFixtures(String fdpUrl) throws MetadataServiceException final IRI distribution2Uri = getUri(distribution2); genericMetadataService.store(distribution2, distribution2Uri, distributionRd); } - } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0001_Init.java b/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0001_Init.java index fbd985c74..7233c2c25 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0001_Init.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0001_Init.java @@ -22,7 +22,6 @@ */ package nl.dtls.fairdatapoint.database.rdf.migration.production; -import com.mongodb.client.MongoCollection; import lombok.extern.slf4j.Slf4j; import nl.dtls.fairdatapoint.service.reset.FactoryDefaults; import nl.dtls.rdf.migration.entity.RdfMigrationAnnotation; @@ -36,7 +35,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; -import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.stereotype.Service; import java.util.List; @@ -48,7 +46,7 @@ @Slf4j @Service public class Rdf_Migration_0001_Init implements RdfProductionMigration { - // TODO: squash RDF migrations + // TODO: use data specs for initial data @Autowired private Repository mainRepository; @@ -66,9 +64,6 @@ public class Rdf_Migration_0001_Init implements RdfProductionMigration { @Autowired private IRI language; - @Autowired - private MongoTemplate mongoTemplate; - public void runMigration() { createRepositoryInTripleStore(); storePermissionForRepository(); @@ -90,12 +85,13 @@ private void createRepositoryInTripleStore() { } private void storePermissionForRepository() { - final MongoCollection aclCol = mongoTemplate.getCollection("ACL"); - aclCol.insertOne(repositoryPermission()); + // TODO + return; } private Document repositoryPermission() { - return FactoryDefaults.aclRepository(persistentUrl); + // TODO + return null; } } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0002_Metadata_Draft.java b/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0002_Metadata_Draft.java index 36bd2b9a4..289a823a0 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0002_Metadata_Draft.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0002_Metadata_Draft.java @@ -25,11 +25,6 @@ import lombok.extern.slf4j.Slf4j; import nl.dtls.rdf.migration.entity.RdfMigrationAnnotation; import nl.dtls.rdf.migration.runner.RdfProductionMigration; -import org.eclipse.rdf4j.model.Resource; -import org.eclipse.rdf4j.repository.Repository; -import org.eclipse.rdf4j.repository.RepositoryConnection; -import org.eclipse.rdf4j.repository.RepositoryException; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @RdfMigrationAnnotation( @@ -39,31 +34,9 @@ @Slf4j @Service public class Rdf_Migration_0002_Metadata_Draft implements RdfProductionMigration { - // TODO: squash RDF migrations - - @Autowired - private Repository mainRepository; - - // @Autowired - // private MetadataRepository metadataRepository; + // TODO: remove (use seed) public void runMigration() { - createRepositoryInTripleStore(); - } - private void createRepositoryInTripleStore() { - try (RepositoryConnection conn = mainRepository.getConnection()) { - conn.getContextIDs() - .stream() - .forEach(this::saveMetadataForResource); - } - catch (RepositoryException exception) { - log.error(exception.getMessage(), exception); - } } - - private void saveMetadataForResource(Resource resource) { - // metadataRepository.save(new Metadata(null, resource.stringValue(), MetadataState.PUBLISHED)); - } - } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0003_FDPO.java b/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0003_FDPO.java index 95f5aeacf..c75d2b63d 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0003_FDPO.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0003_FDPO.java @@ -23,27 +23,10 @@ package nl.dtls.fairdatapoint.database.rdf.migration.production; import lombok.extern.slf4j.Slf4j; -import nl.dtls.fairdatapoint.vocabulary.FDP; -import nl.dtls.fairdatapoint.vocabulary.R3D; import nl.dtls.rdf.migration.entity.RdfMigrationAnnotation; import nl.dtls.rdf.migration.runner.RdfProductionMigration; -import org.eclipse.rdf4j.model.IRI; -import org.eclipse.rdf4j.model.Statement; -import org.eclipse.rdf4j.model.vocabulary.DCAT; -import org.eclipse.rdf4j.model.vocabulary.DCTERMS; -import org.eclipse.rdf4j.model.vocabulary.RDF; -import org.eclipse.rdf4j.repository.Repository; -import org.eclipse.rdf4j.repository.RepositoryConnection; -import org.eclipse.rdf4j.repository.RepositoryException; -import org.eclipse.rdf4j.repository.RepositoryResult; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import java.util.List; - -import static nl.dtls.fairdatapoint.util.ValueFactoryHelper.i; -import static nl.dtls.fairdatapoint.util.ValueFactoryHelper.s; - @RdfMigrationAnnotation( number = 3, name = "FDPO Compliance", @@ -51,113 +34,8 @@ @Slf4j @Service public class Rdf_Migration_0003_FDPO implements RdfProductionMigration { - // TODO: squash RDF migrations - - private static final String LEGACY_CONFORMS_TO = "https://www.purl.org/fairtools/fdp/schema/0.1/fdpMetadata"; - - private static final IRI OLD_METADATA_IDENTIFIER = - i("http://rdf.biosemantics.org/ontologies/fdp-o#metadataIdentifier"); - private static final IRI OLD_METADATA_ISSUED = - i("http://rdf.biosemantics.org/ontologies/fdp-o#metadataIssued"); - private static final IRI OLD_METADATA_MODIFIED = - i("http://rdf.biosemantics.org/ontologies/fdp-o#metadataModified"); - - private static final String MSG_ADD = "Adding: {} {} {}"; - private static final String MSG_REMOVE = "Removing: {} {} {}"; - - @Autowired - private Repository mainRepository; + // TODO: remove (use seed) public void runMigration() { - removeOldConformsTo(); - updateRepositoryStatements(); - updateRepositoryCatalogLinks(); - updateOldFdpoStatements(); - } - - private void removeOldConformsTo() { - // remove conformsTo for repository if present (https://www.purl.org/fairtools/fdp/schema/0.1/fdpMetadata) - try (RepositoryConnection conn = mainRepository.getConnection()) { - final RepositoryResult queryResult = - conn.getStatements(null, DCTERMS.CONFORMS_TO, i(LEGACY_CONFORMS_TO)); - while (queryResult.hasNext()) { - final Statement st = queryResult.next(); - log.warn(MSG_REMOVE, st.getSubject(), st.getPredicate(), st.getObject()); - conn.remove(st); - } - } - catch (RepositoryException exception) { - log.error(exception.getMessage(), exception); - } - } - - private void updateRepositoryStatements() { - // change r3d:Repository -> fdp-o:FAIRDataPoint (and dcat:DataService + fdp-o:MetadataService?) - final List newTypes = List.of(DCAT.DATA_SERVICE, FDP.METADATASERVICE, FDP.FAIRDATAPOINT); - try (RepositoryConnection conn = mainRepository.getConnection()) { - final RepositoryResult queryResult = conn.getStatements(null, RDF.TYPE, R3D.REPOSITORY); - while (queryResult.hasNext()) { - final Statement st = queryResult.next(); - for (IRI type : newTypes) { - log.debug(MSG_ADD, st.getSubject(), RDF.TYPE, type); - conn.add(s(st.getSubject(), RDF.TYPE, type, st.getSubject())); - } - log.debug(MSG_REMOVE, st.getSubject(), st.getPredicate(), st.getObject()); - conn.remove(st); - } - } - catch (RepositoryException exception) { - log.error(exception.getMessage(), exception); - } - } - - private void updateOldFdpoStatements() { - // update old FDP-O generated metadata - try (RepositoryConnection conn = mainRepository.getConnection()) { - RepositoryResult queryResult = conn.getStatements(null, OLD_METADATA_IDENTIFIER, null); - while (queryResult.hasNext()) { - final Statement st = queryResult.next(); - log.debug(MSG_ADD, st.getSubject(), FDP.METADATAIDENTIFIER, st.getObject()); - conn.add(s(st.getSubject(), FDP.METADATAIDENTIFIER, st.getObject(), st.getSubject())); - log.debug(MSG_REMOVE, st.getSubject(), st.getPredicate(), st.getObject()); - conn.remove(st); - } - queryResult = conn.getStatements(null, OLD_METADATA_ISSUED, null); - while (queryResult.hasNext()) { - final Statement st = queryResult.next(); - log.debug(MSG_ADD, st.getSubject(), FDP.METADATAISSUED, st.getObject()); - conn.add(s(st.getSubject(), FDP.METADATAISSUED, st.getObject(), st.getSubject())); - log.debug(MSG_REMOVE, st.getSubject(), st.getPredicate(), st.getObject()); - conn.remove(st); - } - queryResult = conn.getStatements(null, OLD_METADATA_MODIFIED, null); - while (queryResult.hasNext()) { - final Statement st = queryResult.next(); - log.debug(MSG_ADD, st.getSubject(), FDP.METADATAMODIFIED, st.getObject()); - conn.add(s(st.getSubject(), FDP.METADATAMODIFIED, st.getObject(), st.getSubject())); - log.debug(MSG_REMOVE, st.getSubject(), st.getPredicate(), st.getObject()); - conn.remove(st); - } - } - catch (RepositoryException exception) { - log.error(exception.getMessage(), exception); - } - } - - private void updateRepositoryCatalogLinks() { - // change r3d:dataCatalog to fdp-o:metadataCatalog property (between Repository/FDP and Catalogs) - try (RepositoryConnection conn = mainRepository.getConnection()) { - final RepositoryResult queryResult = conn.getStatements(null, R3D.DATACATALOG, null); - while (queryResult.hasNext()) { - final Statement st = queryResult.next(); - log.debug(MSG_ADD, st.getSubject(), FDP.METADATACATALOG, st.getObject()); - conn.add(s(st.getSubject(), FDP.METADATACATALOG, st.getObject(), st.getSubject())); - log.debug(MSG_REMOVE, st.getSubject(), st.getPredicate(), st.getObject()); - conn.remove(st); - } - } - catch (RepositoryException exception) { - log.error(exception.getMessage(), exception); - } } } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0004_Cleanup_Index.java b/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0004_Cleanup_Index.java index 63314a6fd..71ef6d3eb 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0004_Cleanup_Index.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0004_Cleanup_Index.java @@ -23,23 +23,10 @@ package nl.dtls.fairdatapoint.database.rdf.migration.production; import lombok.extern.slf4j.Slf4j; -import nl.dtls.fairdatapoint.config.properties.InstanceProperties; -import nl.dtls.fairdatapoint.database.mongo.repository.IndexEntryRepository; -import nl.dtls.fairdatapoint.database.rdf.repository.RepositoryMode; -import nl.dtls.fairdatapoint.database.rdf.repository.exception.MetadataRepositoryException; -import nl.dtls.fairdatapoint.database.rdf.repository.generic.GenericMetadataRepository; -import nl.dtls.fairdatapoint.entity.index.entry.IndexEntry; import nl.dtls.rdf.migration.entity.RdfMigrationAnnotation; import nl.dtls.rdf.migration.runner.RdfProductionMigration; -import org.eclipse.rdf4j.model.Value; -import org.eclipse.rdf4j.repository.Repository; -import org.eclipse.rdf4j.repository.RepositoryConnection; -import org.eclipse.rdf4j.repository.RepositoryException; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import static nl.dtls.fairdatapoint.util.ValueFactoryHelper.i; - @RdfMigrationAnnotation( number = 4, name = "Cleanup Index", @@ -47,76 +34,8 @@ @Slf4j @Service public class Rdf_Migration_0004_Cleanup_Index implements RdfProductionMigration { - // TODO: squash RDF migrations - - @Autowired - private Repository mainRepository; - - @Autowired - private GenericMetadataRepository genericMetadataRepository; - - @Autowired - private String persistentUrl; - - @Autowired - private IndexEntryRepository indexEntryRepository; + // TODO: remove (use seed) - @Autowired - private InstanceProperties instanceProperties; - - @Override public void runMigration() { - if (instanceProperties.isIndex()) { - cleanupHarvestedRecords(); - } - } - - public void cleanupHarvestedRecords() { - indexEntryRepository.findAll().forEach(this::cleanupHarvestedRecordsFrom); - } - - public void cleanupHarvestedRecordsFrom(IndexEntry entry) { - log.debug("Deleting harvested records for '{}'", entry.getClientUrl()); - - if (entry.getCurrentMetadata() == null) { - log.debug("Deleting harvested records for '{}': no metadata retrieved", entry.getClientUrl()); - return; - } - - final String repositoryUri = entry.getCurrentMetadata().getRepositoryUri(); - log.debug("Deleting harvested records for '{}': has repository URI '{}'", entry.getClientUrl(), repositoryUri); - - if (repositoryUri.equals(persistentUrl) || repositoryUri.equals(instanceProperties.getClientUrl())) { - log.debug("Deleting harvested records for '{}': self-referenced repository", entry.getClientUrl()); - return; - } - - try (RepositoryConnection conn = mainRepository.getConnection()) { - conn.getContextIDs() - .stream() - .filter(Value::isIRI) - .map(Object::toString) - .filter(uri -> isRemoteRepository(uri, repositoryUri, entry) && !isThisInstance(uri)) - .forEach(contextId -> { - log.info("Deleting harvested records for '{}': {}", entry.getClientUrl(), contextId); - try { - genericMetadataRepository.remove(i(contextId), RepositoryMode.COMBINED); - } - catch (MetadataRepositoryException exception) { - throw new RuntimeException(exception); - } - }); - } - catch (RepositoryException exception) { - log.error(exception.getMessage(), exception); - } - } - - private boolean isRemoteRepository(String uri, String repositoryUri, IndexEntry entry) { - return uri.startsWith(repositoryUri) || uri.startsWith(entry.getClientUrl()); - } - - private boolean isThisInstance(String uri) { - return uri.startsWith(persistentUrl) || uri.startsWith(instanceProperties.getClientUrl()); } } diff --git a/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0005_FixMetadataVersion.java b/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0005_FixMetadataVersion.java index ac920322e..9e1dd7700 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0005_FixMetadataVersion.java +++ b/src/main/java/nl/dtls/fairdatapoint/database/rdf/migration/production/Rdf_Migration_0005_FixMetadataVersion.java @@ -23,20 +23,10 @@ package nl.dtls.fairdatapoint.database.rdf.migration.production; import lombok.extern.slf4j.Slf4j; -import nl.dtls.fairdatapoint.vocabulary.DCAT3; import nl.dtls.rdf.migration.entity.RdfMigrationAnnotation; import nl.dtls.rdf.migration.runner.RdfProductionMigration; -import org.eclipse.rdf4j.model.Statement; -import org.eclipse.rdf4j.model.vocabulary.DCTERMS; -import org.eclipse.rdf4j.repository.Repository; -import org.eclipse.rdf4j.repository.RepositoryConnection; -import org.eclipse.rdf4j.repository.RepositoryException; -import org.eclipse.rdf4j.repository.RepositoryResult; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import static nl.dtls.fairdatapoint.util.ValueFactoryHelper.s; - @RdfMigrationAnnotation( number = 5, name = "Fix Metadata Version", @@ -44,33 +34,8 @@ @Slf4j @Service public class Rdf_Migration_0005_FixMetadataVersion implements RdfProductionMigration { - - private static final String MSG_ADD = "Adding: {} {} {}"; - private static final String MSG_REMOVE = "Removing: {} {} {}"; - - @Autowired - private Repository mainRepository; + // TODO: remove (use seed) public void runMigration() { - updateVersionStatements(); - } - - private void updateVersionStatements() { - // change dcterms:hasVersion to dcat:version property (if object is literal) - try (RepositoryConnection conn = mainRepository.getConnection()) { - final RepositoryResult queryResult = conn.getStatements(null, DCTERMS.HAS_VERSION, null); - while (queryResult.hasNext()) { - final Statement st = queryResult.next(); - if (st.getObject().isLiteral()) { - log.debug(MSG_ADD, st.getSubject(), DCAT3.VERSION, st.getObject()); - conn.add(s(st.getSubject(), DCAT3.VERSION, st.getObject(), st.getSubject())); - log.debug(MSG_REMOVE, st.getSubject(), st.getPredicate(), st.getObject()); - conn.remove(st); - } - } - } - catch (RepositoryException exception) { - log.error(exception.getMessage(), exception); - } } } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/apikey/ApiKey.java b/src/main/java/nl/dtls/fairdatapoint/entity/apikey/ApiKey.java index a65733340..d94864a0d 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/apikey/ApiKey.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/apikey/ApiKey.java @@ -22,26 +22,28 @@ */ package nl.dtls.fairdatapoint.entity.apikey; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import lombok.*; -import org.bson.types.ObjectId; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import lombok.experimental.SuperBuilder; +import nl.dtls.fairdatapoint.entity.base.BaseEntity; +import nl.dtls.fairdatapoint.entity.user.UserAccount; -@Document +@Entity(name = "ApiKey") +@Table(name = "api_key") @Getter @Setter @NoArgsConstructor @AllArgsConstructor -@Builder(toBuilder = true) -public class ApiKey { - - @Id - private ObjectId id; - - private String uuid; - - private String userUuid; +@SuperBuilder +public class ApiKey extends BaseEntity { + @NotNull + @Column(name = "token", nullable = false) private String token; + @NotNull + @ManyToOne + @JoinColumn(name = "user_account_id", nullable = false) + private UserAccount userAccount; } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/base/BaseEntity.java b/src/main/java/nl/dtls/fairdatapoint/entity/base/BaseEntity.java new file mode 100644 index 000000000..e3900dfd9 --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/entity/base/BaseEntity.java @@ -0,0 +1,78 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.entity.base; + +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import lombok.*; +import lombok.experimental.SuperBuilder; +import org.hibernate.annotations.CreationTimestamp; +import org.hibernate.annotations.UpdateTimestamp; + +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; + +@MappedSuperclass +@SuperBuilder(toBuilder = true) +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +public class BaseEntity { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @NotNull + @Column(name = "uuid", nullable = false, updatable = false, unique = true) + private UUID uuid; + + @Builder.Default + @CreationTimestamp + @NotNull + @Column(name = "created_at", nullable = false, updatable = false) + private Instant createdAt = Instant.now(); + + @Builder.Default + @UpdateTimestamp + @NotNull + @Column(name = "updated_at", nullable = false) + private Instant updatedAt = Instant.now(); + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + final BaseEntity that = (BaseEntity) o; + return uuid.equals(that.uuid); + } + + @Override + public int hashCode() { + return Objects.hash(uuid); + } +} diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/base/BaseEntityCustomUUID.java b/src/main/java/nl/dtls/fairdatapoint/entity/base/BaseEntityCustomUUID.java new file mode 100644 index 000000000..bf4a9a5aa --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/entity/base/BaseEntityCustomUUID.java @@ -0,0 +1,79 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.entity.base; + +import jakarta.persistence.Column; +import jakarta.persistence.Id; +import jakarta.persistence.MappedSuperclass; +import jakarta.validation.constraints.NotNull; +import lombok.*; +import lombok.experimental.SuperBuilder; +import org.hibernate.annotations.CreationTimestamp; +import org.hibernate.annotations.UpdateTimestamp; + +import java.time.Instant; +import java.util.Objects; +import java.util.UUID; + +@MappedSuperclass +@SuperBuilder(toBuilder = true) +@Getter +@Setter +@AllArgsConstructor +@NoArgsConstructor +public class BaseEntityCustomUUID { + + @Id + @NotNull + @Column(name = "uuid", nullable = false, updatable = false, unique = true) + private UUID uuid; + + @Builder.Default + @CreationTimestamp + @NotNull + @Column(name = "created_at", nullable = false, updatable = false) + private Instant createdAt = Instant.now(); + + @Builder.Default + @UpdateTimestamp + @NotNull + @Column(name = "updated_at", nullable = false) + private Instant updatedAt = Instant.now(); + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + final BaseEntityCustomUUID that = (BaseEntityCustomUUID) o; + return uuid.equals(that.uuid); + } + + @Override + public int hashCode() { + return Objects.hash(uuid); + } +} diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/index/entry/IndexEntry.java b/src/main/java/nl/dtls/fairdatapoint/entity/index/entry/IndexEntry.java index 18afbadcb..650046b0a 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/index/entry/IndexEntry.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/index/entry/IndexEntry.java @@ -22,50 +22,73 @@ */ package nl.dtls.fairdatapoint.entity.index.entry; +import io.hypersistence.utils.hibernate.type.json.JsonBinaryType; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import lombok.*; -import org.bson.types.ObjectId; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; -import org.springframework.format.annotation.DateTimeFormat; +import lombok.experimental.SuperBuilder; +import nl.dtls.fairdatapoint.entity.base.BaseEntity; +import org.hibernate.annotations.JdbcType; +import org.hibernate.annotations.Type; +import org.hibernate.dialect.PostgreSQLEnumJdbcType; import java.time.Duration; import java.time.Instant; +import java.util.HashMap; +import java.util.Map; -@Document +@Entity(name = "IndexEntry") +@Table(name = "index_entry") @NoArgsConstructor @AllArgsConstructor @Getter @Setter -@EqualsAndHashCode -@Builder -public class IndexEntry { +@SuperBuilder +public class IndexEntry extends BaseEntity { - @Id - private ObjectId id; - - private String uuid; + public static final Integer CURRENT_VERSION = 1; + @NotNull + @Column(name = "client_url", nullable = false) private String clientUrl; - private IndexEntryState state = IndexEntryState.Unknown; + @Column(name = "repository_uri") + private String repositoryUri; - private IndexEntryPermit permit = IndexEntryPermit.PENDING; + @NotNull + @Enumerated(EnumType.STRING) + @JdbcType(PostgreSQLEnumJdbcType.class) + @Column(name = "state", columnDefinition = "INDEX_ENTRY_STATE", nullable = false) + private IndexEntryState state = IndexEntryState.UNKNOWN; - @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) - private Instant registrationTime; + @NotNull + @Enumerated(EnumType.STRING) + @JdbcType(PostgreSQLEnumJdbcType.class) + @Column(name = "permit", columnDefinition = "INDEX_ENTRY_PERMIT", nullable = false) + private IndexEntryPermit permit = IndexEntryPermit.PENDING; - @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) - private Instant modificationTime; + @NotNull + @Column(name = "metadata_version", nullable = false) + private Integer metadataVersion = CURRENT_VERSION; - @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) - private Instant lastRetrievalTime; + @Column(name = "last_retrieval_at") + private Instant lastRetrievalAt; - private RepositoryMetadata currentMetadata; + @NotNull + @Type(JsonBinaryType.class) + @Column(name = "metadata", columnDefinition = "jsonb", nullable = false) + private Map metadata = new HashMap<>(); public Duration getLastRetrievalAgo() { - if (lastRetrievalTime == null) { + if (getLastRetrievalAt() == null) { return null; } - return Duration.between(lastRetrievalTime, Instant.now()); + return Duration.between(getLastRetrievalAt(), Instant.now()); + } + + public void setCurrentMetadata(RepositoryMetadata repositoryMetadata) { + setRepositoryUri(repositoryMetadata.getRepositoryUri()); + setMetadataVersion(repositoryMetadata.getMetadataVersion()); + setMetadata(repositoryMetadata.getMetadata()); } } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/index/entry/IndexEntryState.java b/src/main/java/nl/dtls/fairdatapoint/entity/index/entry/IndexEntryState.java index d8bf0139c..69f1c9fc5 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/index/entry/IndexEntryState.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/index/entry/IndexEntryState.java @@ -23,8 +23,8 @@ package nl.dtls.fairdatapoint.entity.index.entry; public enum IndexEntryState { - Unknown, - Valid, - Unreachable, - Invalid + UNKNOWN, + VALID, + UNREACHABLE, + INVALID } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/index/entry/RepositoryMetadata.java b/src/main/java/nl/dtls/fairdatapoint/entity/index/entry/RepositoryMetadata.java index fa64fbe75..9ea6f92ca 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/index/entry/RepositoryMetadata.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/index/entry/RepositoryMetadata.java @@ -23,7 +23,10 @@ package nl.dtls.fairdatapoint.entity.index.entry; import jakarta.validation.constraints.NotNull; -import lombok.*; +import lombok.AllArgsConstructor; +import lombok.Builder; +import lombok.Data; +import lombok.NoArgsConstructor; import java.util.HashMap; import java.util.Map; @@ -31,9 +34,7 @@ @Data @NoArgsConstructor @AllArgsConstructor -@Getter -@Setter -@EqualsAndHashCode +@Builder public class RepositoryMetadata { public static final Integer CURRENT_VERSION = 1; @@ -46,3 +47,4 @@ public class RepositoryMetadata { private Map metadata = new HashMap<>(); } + diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/index/event/Event.java b/src/main/java/nl/dtls/fairdatapoint/entity/index/event/Event.java deleted file mode 100644 index 06450d17a..000000000 --- a/src/main/java/nl/dtls/fairdatapoint/entity/index/event/Event.java +++ /dev/null @@ -1,125 +0,0 @@ -/** - * The MIT License - * Copyright © 2017 DTL - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - */ -package nl.dtls.fairdatapoint.entity.index.event; - -import jakarta.validation.constraints.NotNull; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import nl.dtls.fairdatapoint.entity.index.entry.IndexEntry; -import org.bson.types.ObjectId; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.DBRef; -import org.springframework.data.mongodb.core.mapping.Document; -import org.springframework.format.annotation.DateTimeFormat; - -import java.time.Instant; -import java.util.UUID; - -@Data -@NoArgsConstructor -@AllArgsConstructor -@Document(collection = "event") -public class Event { - @Id - private ObjectId id; - @NotNull - private UUID uuid = UUID.randomUUID(); - @NotNull - private EventType type; - @NotNull - private Integer version; - - @DBRef - private Event triggeredBy; - @DBRef - private IndexEntry relatedTo; - - // Content (one of those) - private IncomingPing incomingPing; - private MetadataRetrieval metadataRetrieval; - private AdminTrigger adminTrigger; - private WebhookPing webhookPing; - private WebhookTrigger webhookTrigger; - - @NotNull - @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) - private Instant created = Instant.now(); - - @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) - private Instant executed; - - @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) - private Instant finished; - - public Event(Integer version, IncomingPing incomingPing) { - this.type = EventType.IncomingPing; - this.version = version; - this.incomingPing = incomingPing; - } - - public Event(Integer version, Event triggerEvent, IndexEntry relatedTo, - MetadataRetrieval metadataRetrieval) { - this.type = EventType.MetadataRetrieval; - this.version = version; - this.triggeredBy = triggerEvent; - this.relatedTo = relatedTo; - this.metadataRetrieval = metadataRetrieval; - } - - public Event(Integer version, AdminTrigger adminTrigger) { - this.type = EventType.AdminTrigger; - this.version = version; - this.adminTrigger = adminTrigger; - } - - public Event(Integer version, WebhookTrigger webhookTrigger, Event triggerEvent) { - this.type = EventType.WebhookTrigger; - this.version = version; - this.webhookTrigger = webhookTrigger; - this.triggeredBy = triggerEvent; - this.relatedTo = triggerEvent.getRelatedTo(); - } - - public Event(Integer version, WebhookPing webhookPing) { - this.type = EventType.WebhookPing; - this.version = version; - this.webhookPing = webhookPing; - } - - public boolean isExecuted() { - return executed != null; - } - - public void execute() { - executed = Instant.now(); - } - - public boolean isFinished() { - return finished != null; - } - - public void finish() { - finished = Instant.now(); - } -} diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/index/event/IndexEvent.java b/src/main/java/nl/dtls/fairdatapoint/entity/index/event/IndexEvent.java new file mode 100644 index 000000000..d369a6dd4 --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/entity/index/event/IndexEvent.java @@ -0,0 +1,134 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.entity.index.event; + +import io.hypersistence.utils.hibernate.type.json.JsonType; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.experimental.SuperBuilder; +import nl.dtls.fairdatapoint.entity.base.BaseEntity; +import nl.dtls.fairdatapoint.entity.index.entry.IndexEntry; +import nl.dtls.fairdatapoint.entity.index.event.payload.*; +import org.hibernate.annotations.JdbcType; +import org.hibernate.annotations.Type; +import org.hibernate.dialect.PostgreSQLEnumJdbcType; + +import java.time.Instant; + +@Entity(name = "IndexEvent") +@Table(name = "index_event") +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +@SuperBuilder +public class IndexEvent extends BaseEntity { + + @NotNull + @Enumerated(EnumType.STRING) + @JdbcType(PostgreSQLEnumJdbcType.class) + @Column(name = "type", columnDefinition = "INDEX_EVENT_TYPE", nullable = false) + private IndexEventType type; + + @NotNull + @Column(name = "version", nullable = false) + private Integer version; + + @Column(name = "remote_addr") + private String remoteAddr; + + @NotNull + @Type(JsonType.class) + @Column(name = "payload", columnDefinition = "jsonb", nullable = false) + private IndexEventPayload payload; + + @ManyToOne + @JoinColumn(name = "triggered_by") + private IndexEvent triggeredBy; + + @ManyToOne + @JoinColumn(name = "related_to") + private IndexEntry relatedTo; + + @Column(name = "executed_at") + private Instant executedAt; + + @Column(name = "finished_at") + private Instant finishedAt; + + public IndexEvent(Integer version, IncomingPing incomingPing) { + this.type = IndexEventType.INCOMING_PING; + this.version = version; + this.remoteAddr = incomingPing.getExchange().getRemoteAddr(); + this.payload = IndexEventPayload.builder().incomingPing(incomingPing).build(); + } + + public IndexEvent(Integer version, IndexEvent triggerEvent, IndexEntry relatedTo, + MetadataRetrieval metadataRetrieval) { + this.type = IndexEventType.METADATA_RETRIEVAL; + this.version = version; + this.triggeredBy = triggerEvent; + this.relatedTo = relatedTo; + this.payload = IndexEventPayload.builder().metadataRetrieval(metadataRetrieval).build(); + } + + public IndexEvent(Integer version, AdminTrigger adminTrigger) { + this.type = IndexEventType.ADMIN_TRIGGER; + this.version = version; + this.payload = IndexEventPayload.builder().adminTrigger(adminTrigger).build(); + } + + public IndexEvent(Integer version, WebhookTrigger webhookTrigger, IndexEvent triggerEvent) { + this.type = IndexEventType.WEBHOOK_TRIGGER; + this.version = version; + this.payload = IndexEventPayload.builder().webhookTrigger(webhookTrigger).build(); + this.triggeredBy = triggerEvent; + this.relatedTo = triggerEvent.getRelatedTo(); + } + + public IndexEvent(Integer version, WebhookPing webhookPing) { + this.type = IndexEventType.WEBHOOK_PING; + this.version = version; + this.payload = IndexEventPayload.builder().webhookPing(webhookPing).build(); + } + + public boolean isExecuted() { + return getExecutedAt() != null; + } + + public void execute() { + setExecutedAt(Instant.now()); + } + + public boolean isFinished() { + return getFinishedAt() != null; + } + + public void finish() { + setFinishedAt(Instant.now()); + } +} diff --git a/src/main/java/nl/dtls/fairdatapoint/service/metadata/validator/MetadataStateValidator.java b/src/main/java/nl/dtls/fairdatapoint/entity/index/event/IndexEventPayload.java similarity index 52% rename from src/main/java/nl/dtls/fairdatapoint/service/metadata/validator/MetadataStateValidator.java rename to src/main/java/nl/dtls/fairdatapoint/entity/index/event/IndexEventPayload.java index ff0c005e8..52d9be871 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/metadata/validator/MetadataStateValidator.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/index/event/IndexEventPayload.java @@ -20,25 +20,46 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.service.metadata.validator; +package nl.dtls.fairdatapoint.entity.index.event; -import nl.dtls.fairdatapoint.api.dto.metadata.MetaStateChangeDTO; -import nl.dtls.fairdatapoint.entity.exception.ValidationException; -import nl.dtls.fairdatapoint.entity.metadata.Metadata; -import nl.dtls.fairdatapoint.entity.metadata.MetadataState; -import org.springframework.stereotype.Service; +import lombok.Builder; +import lombok.Data; +import nl.dtls.fairdatapoint.entity.index.event.payload.*; -@Service -public class MetadataStateValidator { +@Data +@Builder +public class IndexEventPayload { - public void validate(MetaStateChangeDTO reqDto, Metadata metadata) { - if (reqDto.getCurrent().equals(MetadataState.DRAFT)) { - throw new ValidationException("You can not change state to DRAFT"); - } + private IncomingPing incomingPing; + + private MetadataRetrieval metadataRetrieval; + + private AdminTrigger adminTrigger; + + private WebhookPing webhookPing; + + private WebhookTrigger webhookTrigger; - if (metadata.getState().equals(MetadataState.PUBLISHED)) { - throw new ValidationException("Metadata is already published"); + public IndexEventType extractType() { + if (incomingPing != null) { + return IndexEventType.INCOMING_PING; } + else if (metadataRetrieval != null) { + return IndexEventType.METADATA_RETRIEVAL; + } + else if (adminTrigger != null) { + return IndexEventType.ADMIN_TRIGGER; + } + else if (webhookPing != null) { + return IndexEventType.WEBHOOK_PING; + } + else if (webhookTrigger != null) { + return IndexEventType.WEBHOOK_TRIGGER; + } + return null; } + public boolean hasType(IndexEventType type) { + return extractType() == type; + } } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/index/event/EventType.java b/src/main/java/nl/dtls/fairdatapoint/entity/index/event/IndexEventType.java similarity index 90% rename from src/main/java/nl/dtls/fairdatapoint/entity/index/event/EventType.java rename to src/main/java/nl/dtls/fairdatapoint/entity/index/event/IndexEventType.java index 54406f972..361d6a720 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/index/event/EventType.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/index/event/IndexEventType.java @@ -22,10 +22,10 @@ */ package nl.dtls.fairdatapoint.entity.index.event; -public enum EventType { - AdminTrigger, - MetadataRetrieval, - WebhookTrigger, - IncomingPing, - WebhookPing, +public enum IndexEventType { + ADMIN_TRIGGER, + METADATA_RETRIEVAL, + WEBHOOK_TRIGGER, + INCOMING_PING, + WEBHOOK_PING, } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/index/event/AdminTrigger.java b/src/main/java/nl/dtls/fairdatapoint/entity/index/event/payload/AdminTrigger.java similarity index 95% rename from src/main/java/nl/dtls/fairdatapoint/entity/index/event/AdminTrigger.java rename to src/main/java/nl/dtls/fairdatapoint/entity/index/event/payload/AdminTrigger.java index 839d3e309..0c35353c5 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/index/event/AdminTrigger.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/index/event/payload/AdminTrigger.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.entity.index.event; +package nl.dtls.fairdatapoint.entity.index.event.payload; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/index/event/IncomingPing.java b/src/main/java/nl/dtls/fairdatapoint/entity/index/event/payload/IncomingPing.java similarity index 96% rename from src/main/java/nl/dtls/fairdatapoint/entity/index/event/IncomingPing.java rename to src/main/java/nl/dtls/fairdatapoint/entity/index/event/payload/IncomingPing.java index 118c3c8e2..8c2b39bc5 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/index/event/IncomingPing.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/index/event/payload/IncomingPing.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.entity.index.event; +package nl.dtls.fairdatapoint.entity.index.event.payload; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/index/event/MetadataRetrieval.java b/src/main/java/nl/dtls/fairdatapoint/entity/index/event/payload/MetadataRetrieval.java similarity index 96% rename from src/main/java/nl/dtls/fairdatapoint/entity/index/event/MetadataRetrieval.java rename to src/main/java/nl/dtls/fairdatapoint/entity/index/event/payload/MetadataRetrieval.java index 6c65cbac2..4130b1be2 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/index/event/MetadataRetrieval.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/index/event/payload/MetadataRetrieval.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.entity.index.event; +package nl.dtls.fairdatapoint.entity.index.event.payload; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/index/event/WebhookPing.java b/src/main/java/nl/dtls/fairdatapoint/entity/index/event/payload/WebhookPing.java similarity index 96% rename from src/main/java/nl/dtls/fairdatapoint/entity/index/event/WebhookPing.java rename to src/main/java/nl/dtls/fairdatapoint/entity/index/event/payload/WebhookPing.java index c0776fe73..a7eab1163 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/index/event/WebhookPing.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/index/event/payload/WebhookPing.java @@ -20,7 +20,7 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.entity.index.event; +package nl.dtls.fairdatapoint.entity.index.event.payload; import lombok.AllArgsConstructor; import lombok.Data; diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/index/event/WebhookTrigger.java b/src/main/java/nl/dtls/fairdatapoint/entity/index/event/payload/WebhookTrigger.java similarity index 81% rename from src/main/java/nl/dtls/fairdatapoint/entity/index/event/WebhookTrigger.java rename to src/main/java/nl/dtls/fairdatapoint/entity/index/event/payload/WebhookTrigger.java index 4c4d51673..8bf93f9f3 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/index/event/WebhookTrigger.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/index/event/payload/WebhookTrigger.java @@ -20,24 +20,23 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.entity.index.event; +package nl.dtls.fairdatapoint.entity.index.event.payload; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import nl.dtls.fairdatapoint.entity.index.http.Exchange; -import nl.dtls.fairdatapoint.entity.index.webhook.Webhook; -import nl.dtls.fairdatapoint.entity.index.webhook.WebhookEvent; -import org.springframework.data.mongodb.core.mapping.DBRef; +import nl.dtls.fairdatapoint.entity.index.webhook.IndexWebhook; +import nl.dtls.fairdatapoint.entity.index.webhook.IndexWebhookEvent; @Data @NoArgsConstructor @AllArgsConstructor public class WebhookTrigger { - @DBRef - private Webhook webhook; - private WebhookEvent matchedEvent; + private IndexWebhook webhook; + + private IndexWebhookEvent matchedEvent; private Exchange exchange; } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/index/settings/IndexSettings.java b/src/main/java/nl/dtls/fairdatapoint/entity/index/settings/IndexSettings.java index ade210709..a7481bddd 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/index/settings/IndexSettings.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/index/settings/IndexSettings.java @@ -22,47 +22,86 @@ */ package nl.dtls.fairdatapoint.entity.index.settings; +import io.hypersistence.utils.hibernate.type.array.ListArrayType; +import jakarta.persistence.*; import jakarta.validation.constraints.NotNull; import lombok.*; -import org.bson.types.ObjectId; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import lombok.experimental.SuperBuilder; +import nl.dtls.fairdatapoint.entity.base.BaseEntityCustomUUID; +import org.hibernate.annotations.Type; -import java.util.Objects; +import java.time.Duration; +import java.util.List; -@Document +@Entity(name = "IndexSettings") +@Table(name = "index_settings") @NoArgsConstructor @AllArgsConstructor @Getter @Setter -@Builder(toBuilder = true) -public class IndexSettings { - @Id - private ObjectId id; +@SuperBuilder(toBuilder = true) +public class IndexSettings extends BaseEntityCustomUUID { @NotNull - private IndexSettingsRetrieval retrieval; + @Column(name = "auto_permit", nullable = false) + private Boolean autoPermit; @NotNull - private IndexSettingsPing ping; + @Column(name = "retrieval_rate_limit_wait", nullable = false) + private String retrievalRateLimitWait; @NotNull - private Boolean autoPermit; + @Column(name = "retrieval_timeout", nullable = false) + private String retrievalTimeout; + + @NotNull + @Column(name = "ping_valid_duration", nullable = false) + private String pingValidDuration; + + @NotNull + @Column(name = "ping_rate_limit_duration", nullable = false) + private String pingRateLimitDuration; + + @NotNull + @Column(name = "ping_rate_limit_hits", nullable = false) + private Integer pingRateLimitHits; + + @NotNull + @Type(ListArrayType.class) + @Column(name = "ping_deny_list", columnDefinition = "text[]", nullable = false) + private List pingDenyList; + + public SettingsIndexPing getPing() { + return SettingsIndexPing.builder() + .validDuration(Duration.parse(this.getPingValidDuration())) + .rateLimitDuration(Duration.parse(this.getPingRateLimitDuration())) + .rateLimitHits(this.getPingRateLimitHits()) + .denyList(this.getPingDenyList()) + .build(); + } + + public void setPing(SettingsIndexPing ping) { + this.setPingValidDuration(ping.getValidDuration().toString()); + this.setPingRateLimitDuration(ping.getRateLimitDuration().toString()); + this.setPingRateLimitHits(ping.getRateLimitHits()); + this.setPingDenyList(ping.getDenyList()); + } + + public SettingsIndexRetrieval getRetrieval() { + return SettingsIndexRetrieval.builder() + .rateLimitWait(Duration.parse(this.getRetrievalRateLimitWait())) + .timeout(Duration.parse(this.getRetrievalTimeout())) + .build(); + } - @Override - public boolean equals(Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - final IndexSettings that = (IndexSettings) o; - return retrieval.equals(that.retrieval) && ping.equals(that.ping); + public void setRetrieval(SettingsIndexRetrieval retrieval) { + this.setRetrievalRateLimitWait(retrieval.getRateLimitWait().toString()); + this.setRetrievalTimeout(retrieval.getTimeout().toString()); } - @Override - public int hashCode() { - return Objects.hash(retrieval, ping); + public Boolean isSameAs(IndexSettings defaults) { + return getAutoPermit().equals(defaults.getAutoPermit()) + && getPing().isSameAs(defaults.getPing()) + && getRetrieval().isSameAs(defaults.getRetrieval()); } } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/index/settings/IndexSettingsPing.java b/src/main/java/nl/dtls/fairdatapoint/entity/index/settings/SettingsIndexPing.java similarity index 82% rename from src/main/java/nl/dtls/fairdatapoint/entity/index/settings/IndexSettingsPing.java rename to src/main/java/nl/dtls/fairdatapoint/entity/index/settings/SettingsIndexPing.java index 0a9982715..af9171171 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/index/settings/IndexSettingsPing.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/index/settings/SettingsIndexPing.java @@ -35,7 +35,7 @@ @Setter @Builder(toBuilder = true) @EqualsAndHashCode -public class IndexSettingsPing { +public class SettingsIndexPing { private static final int DEFAULT_VALID_DAYS = 7; private static final int DEFAULT_LIMIT_DURATION_HOURS = 6; @@ -53,12 +53,19 @@ public class IndexSettingsPing { @NotNull private List denyList; - public static IndexSettingsPing getDefault() { - final IndexSettingsPing ping = new IndexSettingsPing(); + public static SettingsIndexPing getDefault() { + final SettingsIndexPing ping = new SettingsIndexPing(); ping.setValidDuration(Duration.ofDays(DEFAULT_VALID_DAYS)); ping.setRateLimitDuration(Duration.ofHours(DEFAULT_LIMIT_DURATION_HOURS)); ping.setRateLimitHits(DEFAULT_LIMIT_HITS); ping.setDenyList(Collections.singletonList("^(http|https)://localhost(:[0-9]+){0,1}.*$")); return ping; } + + public boolean isSameAs(SettingsIndexPing ping) { + return validDuration.equals(ping.getValidDuration()) + && rateLimitDuration.equals(ping.getRateLimitDuration()) + && rateLimitHits.equals(ping.getRateLimitHits()) + && denyList.equals(ping.getDenyList()); + } } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/index/settings/IndexSettingsRetrieval.java b/src/main/java/nl/dtls/fairdatapoint/entity/index/settings/SettingsIndexRetrieval.java similarity index 82% rename from src/main/java/nl/dtls/fairdatapoint/entity/index/settings/IndexSettingsRetrieval.java rename to src/main/java/nl/dtls/fairdatapoint/entity/index/settings/SettingsIndexRetrieval.java index a5d8ee919..f3c9a37ea 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/index/settings/IndexSettingsRetrieval.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/index/settings/SettingsIndexRetrieval.java @@ -33,21 +33,26 @@ @Setter @Builder(toBuilder = true) @EqualsAndHashCode -public class IndexSettingsRetrieval { - +public class SettingsIndexRetrieval { private static final int DEFAULT_WAIT_MIN = 10; private static final int DEFAULT_TIMEOUT_MIN = 1; + private String uri; + @NotNull private Duration rateLimitWait; @NotNull private Duration timeout; - public static IndexSettingsRetrieval getDefault() { - final IndexSettingsRetrieval retrieval = new IndexSettingsRetrieval(); + public static SettingsIndexRetrieval getDefault() { + final SettingsIndexRetrieval retrieval = new SettingsIndexRetrieval(); retrieval.setRateLimitWait(Duration.ofMinutes(DEFAULT_WAIT_MIN)); retrieval.setTimeout(Duration.ofMinutes(DEFAULT_TIMEOUT_MIN)); return retrieval; } + + public boolean isSameAs(SettingsIndexRetrieval retrieval) { + return rateLimitWait.equals(retrieval.getRateLimitWait()) && timeout.equals(retrieval.getTimeout()); + } } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/index/webhook/IndexWebhook.java b/src/main/java/nl/dtls/fairdatapoint/entity/index/webhook/IndexWebhook.java new file mode 100644 index 000000000..ad1d7c904 --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/entity/index/webhook/IndexWebhook.java @@ -0,0 +1,80 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.entity.index.webhook; + +import io.hypersistence.utils.hibernate.type.array.EnumArrayType; +import io.hypersistence.utils.hibernate.type.array.ListArrayType; +import jakarta.persistence.Column; +import jakarta.persistence.Entity; +import jakarta.persistence.Table; +import jakarta.validation.constraints.NotNull; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.experimental.SuperBuilder; +import nl.dtls.fairdatapoint.entity.base.BaseEntity; +import org.hibernate.annotations.Type; + +import java.util.ArrayList; +import java.util.List; + +@Entity(name = "IndexWebhook") +@Table(name = "index_webhook") +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +@SuperBuilder +public class IndexWebhook extends BaseEntity { + + @NotNull + @Column(name = "payload_url", nullable = false) + private String payloadUrl; + + @NotNull + @Column(name = "secret", nullable = false) + private String secret; + + @NotNull + @Column(name = "all_events", nullable = false) + private Boolean allEvents; + + @NotNull + @Column(name = "all_entries", nullable = false) + private Boolean allEntries; + + @NotNull + @Column(name = "enabled", nullable = false) + private Boolean enabled; + + @NotNull + @Type(ListArrayType.class) + @Column(name = "entries", columnDefinition = "text[]", nullable = false) + private List entries = new ArrayList<>(); + + @NotNull + @Type(EnumArrayType.class) + @Column(name = "events", columnDefinition = "INDEX_WEBHOOK_EVENT_TYPE[]", nullable = false) + private List events = new ArrayList<>(); +} diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/index/webhook/WebhookEvent.java b/src/main/java/nl/dtls/fairdatapoint/entity/index/webhook/IndexWebhookEvent.java similarity index 88% rename from src/main/java/nl/dtls/fairdatapoint/entity/index/webhook/WebhookEvent.java rename to src/main/java/nl/dtls/fairdatapoint/entity/index/webhook/IndexWebhookEvent.java index e4d22fca8..208146fbf 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/index/webhook/WebhookEvent.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/index/webhook/IndexWebhookEvent.java @@ -22,12 +22,12 @@ */ package nl.dtls.fairdatapoint.entity.index.webhook; -public enum WebhookEvent { - NewEntry, - IncomingPing, - EntryValid, - EntryInvalid, - EntryUnreachable, - AdminTrigger, - WebhookPing +public enum IndexWebhookEvent { + NEW_ENTRY, + INCOMING_PING, + ENTRY_VALID, + ENTRY_INVALID, + ENTRY_UNREACHABLE, + ADMIN_TRIGGER, + WEBHOOK_PING } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/membership/Membership.java b/src/main/java/nl/dtls/fairdatapoint/entity/membership/Membership.java index 183b23ef9..32b897944 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/membership/Membership.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/membership/Membership.java @@ -22,36 +22,42 @@ */ package nl.dtls.fairdatapoint.entity.membership; +import io.hypersistence.utils.hibernate.type.array.ListArrayType; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import lombok.*; -import org.bson.types.ObjectId; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import lombok.experimental.SuperBuilder; +import nl.dtls.fairdatapoint.entity.base.BaseEntity; +import org.hibernate.annotations.Type; import java.util.List; +import java.util.UUID; -@Document -@NoArgsConstructor -@AllArgsConstructor +@Entity(name = "Membership") +@Table(name = "membership") @Getter @Setter -@Builder(toBuilder = true) -public class Membership { - - @Id - private ObjectId id; - - private String uuid; +@NoArgsConstructor +@AllArgsConstructor +@SuperBuilder +public class Membership extends BaseEntity { + @NotNull + @Column(name = "name", nullable = false) private String name; - private List permissions; - + @NotNull + @Type(ListArrayType.class) + @Column(name = "allowed_entities", columnDefinition = "text[]", nullable = false) private List allowedEntities; - public Membership(String uuid, String name, + @OneToMany(fetch = FetchType.LAZY, mappedBy = "membership") + private List permissions; + + public Membership(UUID uuid, String name, List permissions, List allowedEntities) { - this.uuid = uuid; + this.setUuid(uuid); this.name = name; this.permissions = permissions; this.allowedEntities = allowedEntities; diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/membership/MembershipPermission.java b/src/main/java/nl/dtls/fairdatapoint/entity/membership/MembershipPermission.java index b98e4f42e..0a5e0d1de 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/membership/MembershipPermission.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/membership/MembershipPermission.java @@ -22,27 +22,38 @@ */ package nl.dtls.fairdatapoint.entity.membership; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import lombok.*; -import org.bson.types.ObjectId; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import lombok.experimental.SuperBuilder; +import nl.dtls.fairdatapoint.entity.base.BaseEntity; -@Document -@NoArgsConstructor -@AllArgsConstructor +import java.util.UUID; + +@Entity(name = "MembershipPermission") +@Table(name = "membership_permission") @Getter @Setter -@Builder(toBuilder = true) -public class MembershipPermission { +@NoArgsConstructor +@AllArgsConstructor +@SuperBuilder +public class MembershipPermission extends BaseEntity { - @Id - private ObjectId id; + @NotNull + @Column(name = "mask", nullable = false) + private Integer mask; - private int mask; + @NotNull + @Column(name = "code", nullable = false) + private Character code; - private char code; + @NotNull + @ManyToOne + @JoinColumn(name = "membership_id", nullable = false) + private Membership membership; public MembershipPermission(int mask, char code) { + this.setUuid(UUID.randomUUID()); this.mask = mask; this.code = code; } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/metadata/Metadata.java b/src/main/java/nl/dtls/fairdatapoint/entity/metadata/Metadata.java index 1169d4b0e..38b5af070 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/metadata/Metadata.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/metadata/Metadata.java @@ -22,16 +22,5 @@ */ package nl.dtls.fairdatapoint.entity.metadata; -import lombok.*; - -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -@Builder(toBuilder = true) public class Metadata { - - private String uri; - - private MetadataState state; } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/resource/MetadataSchemaUsage.java b/src/main/java/nl/dtls/fairdatapoint/entity/resource/MetadataSchemaUsage.java new file mode 100644 index 000000000..c2f804ab0 --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/entity/resource/MetadataSchemaUsage.java @@ -0,0 +1,62 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.entity.resource; + +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.experimental.SuperBuilder; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; + +import java.util.UUID; + +@Entity(name = "MetadataSchemaUsage") +@Table(name = "metadata_schema_usage") +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@SuperBuilder +public class MetadataSchemaUsage { + + @Id + @GeneratedValue(strategy = GenerationType.AUTO) + @NotNull + @Column(name = "uuid", nullable = false, updatable = false) + private UUID uuid; + + @ManyToOne + @JoinColumn(name = "resource_definition_id", nullable = false) + private ResourceDefinition resourceDefinition; + + @ManyToOne + @JoinColumn(name = "metadata_schema_id", nullable = false) + private MetadataSchema usedMetadataSchema; + + @NotNull + @Column(name = "order_priority", nullable = false) + private Integer orderPriority; +} diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinition.java b/src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinition.java index 75b74e696..c52af1da0 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinition.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinition.java @@ -22,53 +22,48 @@ */ package nl.dtls.fairdatapoint.entity.resource; -import com.fasterxml.jackson.annotation.JsonIgnore; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import lombok.*; -import org.bson.types.ObjectId; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import lombok.experimental.SuperBuilder; +import nl.dtls.fairdatapoint.entity.base.BaseEntity; -import java.util.ArrayList; import java.util.List; -@Document +@Entity(name = "ResourceDefinition") +@Table(name = "resource_definition") @NoArgsConstructor @AllArgsConstructor @Getter @Setter -@EqualsAndHashCode -@Builder(toBuilder = true) -public class ResourceDefinition { +@SuperBuilder(toBuilder = true) +public class ResourceDefinition extends BaseEntity { private static final String CATALOG_PREFIX = "catalog"; - @Id - @JsonIgnore - private ObjectId id; - - private String uuid; - + @NotNull + @Column(name = "name", nullable = false) private String name; + @NotNull + @Column(name = "url_prefix", nullable = false) private String urlPrefix; - private List metadataSchemaUuids = new ArrayList<>(); + @OrderBy("orderPriority") + @OneToMany(fetch = FetchType.LAZY, mappedBy = "source", cascade = CascadeType.ALL, orphanRemoval = true) + private List children; - private List children = new ArrayList<>(); + @OrderBy("orderPriority") + @OneToMany(fetch = FetchType.LAZY, mappedBy = "target") + private List parents; - private List externalLinks = new ArrayList<>(); + @OrderBy("orderPriority") + @OneToMany(fetch = FetchType.LAZY, mappedBy = "resourceDefinition", cascade = CascadeType.ALL, orphanRemoval = true) + private List externalLinks; - public ResourceDefinition( - String uuid, String name, String urlPrefix, List metadataSchemaUuids, - List children, List externalLinks - ) { - this.uuid = uuid; - this.name = name; - this.urlPrefix = urlPrefix; - this.metadataSchemaUuids = metadataSchemaUuids; - this.children = children; - this.externalLinks = externalLinks; - } + @OrderBy("orderPriority") + @OneToMany(mappedBy = "resourceDefinition", fetch = FetchType.LAZY) + private List metadataSchemaUsages; public boolean isRoot() { return urlPrefix.isEmpty(); diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinitionChild.java b/src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinitionChild.java index a871883f3..2af7afc3a 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinitionChild.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinitionChild.java @@ -22,27 +22,52 @@ */ package nl.dtls.fairdatapoint.entity.resource; -import jakarta.validation.Valid; +import jakarta.persistence.*; import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; import lombok.*; +import lombok.experimental.SuperBuilder; import nl.dtls.fairdatapoint.api.validator.ValidIri; +import nl.dtls.fairdatapoint.entity.base.BaseEntity; +import java.util.List; + +@Entity(name = "ResourceDefinitionChild") +@Table(name = "resource_definition_child") @NoArgsConstructor @AllArgsConstructor @Getter @Setter -@EqualsAndHashCode -@Builder(toBuilder = true) -public class ResourceDefinitionChild { - - @NotBlank - private String resourceDefinitionUuid; +@SuperBuilder +public class ResourceDefinitionChild extends BaseEntity { @NotBlank @ValidIri + @Column(name = "relation_uri", nullable = false) private String relationUri; - @Valid - private ResourceDefinitionChildListView listView; + @NotNull + @Column(name = "title", nullable = false) + private String title; + + @Column(name = "tags_uri") + private String tagsUri; + + @NotNull + @Column(name = "order_priority", nullable = false) + private Integer orderPriority; + + @NotNull + @ManyToOne + @JoinColumn(name = "source_resource_definition_id", nullable = false) + private ResourceDefinition source; + + @NotNull + @ManyToOne + @JoinColumn(name = "target_resource_definition_id", nullable = false) + private ResourceDefinition target; + @OrderBy("orderPriority") + @OneToMany(fetch = FetchType.LAZY, mappedBy = "child") + private List metadata; } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/schema/MetadataSchemaDraft.java b/src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinitionChildMetadata.java similarity index 61% rename from src/main/java/nl/dtls/fairdatapoint/entity/schema/MetadataSchemaDraft.java rename to src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinitionChildMetadata.java index ebf091143..8d4bfe7f1 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/schema/MetadataSchemaDraft.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinitionChildMetadata.java @@ -20,58 +20,40 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.entity.schema; +package nl.dtls.fairdatapoint.entity.resource; +import jakarta.persistence.*; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotNull; import lombok.*; -import org.bson.types.ObjectId; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.index.Indexed; -import org.springframework.data.mongodb.core.mapping.Document; +import lombok.experimental.SuperBuilder; +import nl.dtls.fairdatapoint.api.validator.ValidIri; +import nl.dtls.fairdatapoint.entity.base.BaseEntity; -import java.time.Instant; -import java.util.List; -import java.util.Set; - -@Document -@Getter -@Setter +@Entity(name = "ResourceDefinitionChildMetadata") +@Table(name = "resource_definition_child_metadata") @NoArgsConstructor @AllArgsConstructor -@Builder(toBuilder = true) -public class MetadataSchemaDraft { - - @Id - private ObjectId id; - - @Indexed - private String uuid; +@Getter +@Setter +@SuperBuilder +public class ResourceDefinitionChildMetadata extends BaseEntity { - @NotNull @NotBlank - private String name; - - @NotNull - private String description; - - private boolean abstractSchema; + @Column(name = "title", nullable = false) + private String title; - @NotNull - private String definition; + @NotBlank + @ValidIri + @Column(name = "property_uri", nullable = false) + private String propertyUri; @NotNull - private Set targetClasses; + @Column(name = "order_priority", nullable = false) + private Integer orderPriority; @NotNull - private List extendSchemas; - - private String suggestedResourceName; - - private String suggestedUrlPrefix; - - private Instant createdAt; - - private Instant updatedAt; - + @ManyToOne + @JoinColumn(name = "resource_definition_child_id", nullable = false) + private ResourceDefinitionChild child; } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinitionLink.java b/src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinitionLink.java index 88ab30767..3862666fa 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinitionLink.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/resource/ResourceDefinitionLink.java @@ -22,22 +22,39 @@ */ package nl.dtls.fairdatapoint.entity.resource; +import jakarta.persistence.*; import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; import lombok.*; +import lombok.experimental.SuperBuilder; import nl.dtls.fairdatapoint.api.validator.ValidIri; +import nl.dtls.fairdatapoint.entity.base.BaseEntity; +@Entity(name = "ResourceDefinitionLink") +@Table(name = "resource_definition_link") @NoArgsConstructor @AllArgsConstructor @Getter @Setter -@EqualsAndHashCode -public class ResourceDefinitionLink { +@SuperBuilder +public class ResourceDefinitionLink extends BaseEntity { @NotBlank + @Column(name = "title", nullable = false) private String title; @NotBlank @ValidIri + @Column(name = "property_uri", nullable = false) private String propertyUri; + @NotNull + @Column(name = "order_priority", nullable = false) + private Integer orderPriority; + + @NotNull + @ManyToOne + @JoinColumn(name = "resource_definition_id", nullable = false) + private ResourceDefinition resourceDefinition; + } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/schema/MetadataSchema.java b/src/main/java/nl/dtls/fairdatapoint/entity/schema/MetadataSchema.java index f1c403546..3ce6cae55 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/schema/MetadataSchema.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/schema/MetadataSchema.java @@ -22,126 +22,34 @@ */ package nl.dtls.fairdatapoint.entity.schema; -import jakarta.validation.constraints.NotBlank; -import jakarta.validation.constraints.NotNull; -import lombok.*; -import org.bson.types.ObjectId; -import org.springframework.data.annotation.Id; -import org.springframework.data.annotation.PersistenceConstructor; -import org.springframework.data.annotation.Transient; -import org.springframework.data.mongodb.core.index.Indexed; -import org.springframework.data.mongodb.core.mapping.Document; +import jakarta.persistence.*; +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; +import lombok.experimental.SuperBuilder; +import nl.dtls.fairdatapoint.entity.base.BaseEntityCustomUUID; +import nl.dtls.fairdatapoint.entity.resource.MetadataSchemaUsage; -import java.time.Instant; -import java.util.ArrayList; -import java.util.HashSet; import java.util.List; -import java.util.Set; -@Document +@Entity(name = "MetadataSchema") +@Table(name = "metadata_schema") @Getter @Setter +@NoArgsConstructor @AllArgsConstructor -@Builder(toBuilder = true) -public class MetadataSchema { +@SuperBuilder +public class MetadataSchema extends BaseEntityCustomUUID { - @Id - private ObjectId id; + @OneToMany(fetch = FetchType.LAZY, mappedBy = "schema") + private List versions; - @Indexed - private String uuid; + @OrderBy("orderPriority") + @OneToMany(mappedBy = "extendedMetadataSchema", fetch = FetchType.LAZY) + private List extensions; - @Indexed - private String versionUuid; - - @Indexed - private String versionString; - - @NotNull - @Transient - private SemVer version; - - @NotNull - @NotBlank - private String name; - - @NotNull - private String description; - - @NotNull - private String definition; - - @NotNull - private Set targetClasses = new HashSet<>(); - - @NotNull - private List extendSchemas = new ArrayList<>(); - - @NotNull - private MetadataSchemaType type; - - private String origin; - - private String importedFrom; - - private boolean latest; - - private boolean published; - - private boolean abstractSchema; - - private String suggestedResourceName; - - private String suggestedUrlPrefix; - - private Instant createdAt; - - private String previousVersionUuid; - - @PersistenceConstructor - public MetadataSchema( - ObjectId id, String uuid, String versionUuid, String versionString, - String name, String description, String definition, Set targetClasses, - List extendSchemas, MetadataSchemaType type, String origin, - String importedFrom, boolean latest, boolean published, boolean abstractSchema, - String suggestedResourceName, String suggestedUrlPrefix, Instant createdAt, - String previousVersionUuid - ) { - this.id = id; - this.uuid = uuid; - this.versionUuid = versionUuid; - this.versionString = versionString; - this.name = name; - this.description = description; - this.definition = definition; - this.targetClasses = targetClasses; - this.extendSchemas = extendSchemas; - this.type = type; - this.origin = origin; - this.importedFrom = importedFrom; - this.latest = latest; - this.published = published; - this.abstractSchema = abstractSchema; - this.suggestedResourceName = suggestedResourceName; - this.suggestedUrlPrefix = suggestedUrlPrefix; - this.createdAt = createdAt; - this.previousVersionUuid = previousVersionUuid; - } - - public void setVersionString(String versionString) { - this.versionString = versionString; - this.version = new SemVer(versionString); - } - - public void setVersion(SemVer version) { - this.version = version; - this.versionString = version.toString(); - } - - public SemVer getVersion() { - if (this.version == null) { - this.version = new SemVer(this.versionString); - } - return version; - } + @OrderBy("orderPriority") + @OneToMany(mappedBy = "usedMetadataSchema", fetch = FetchType.LAZY) + private List usages; } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/index/webhook/Webhook.java b/src/main/java/nl/dtls/fairdatapoint/entity/schema/MetadataSchemaExtension.java similarity index 62% rename from src/main/java/nl/dtls/fairdatapoint/entity/index/webhook/Webhook.java rename to src/main/java/nl/dtls/fairdatapoint/entity/schema/MetadataSchemaExtension.java index 5f24c7607..512971050 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/index/webhook/Webhook.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/schema/MetadataSchemaExtension.java @@ -20,42 +20,38 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.entity.index.webhook; +package nl.dtls.fairdatapoint.entity.schema; +import jakarta.persistence.*; import jakarta.validation.constraints.NotNull; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import org.bson.types.ObjectId; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import lombok.*; -import java.util.ArrayList; -import java.util.List; import java.util.UUID; -@Data +@Entity(name = "MetadataSchemaExtension") +@Table(name = "metadata_schema_extension") +@Getter +@Setter @NoArgsConstructor @AllArgsConstructor -@Document(collection = "webhook") -public class Webhook { - @Id - private ObjectId id; +@Builder +public class MetadataSchemaExtension { + @Id + @GeneratedValue(strategy = GenerationType.AUTO) @NotNull - private UUID uuid = UUID.randomUUID(); - - private String payloadUrl; - - private String secret; + @Column(name = "uuid", nullable = false, updatable = false) + private UUID uuid; - private boolean allEvents; + @ManyToOne + @JoinColumn(name = "metadata_schema_version_id", nullable = false) + private MetadataSchemaVersion metadataSchemaVersion; - private List events = new ArrayList<>(); + @ManyToOne + @JoinColumn(name = "extended_metadata_schema_id", nullable = false) + private MetadataSchema extendedMetadataSchema; - private boolean allEntries; - - private List entries = new ArrayList<>(); - - private boolean enabled; + @NotNull + @Column(name = "order_priority", nullable = false) + private Integer orderPriority; } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/schema/MetadataSchemaState.java b/src/main/java/nl/dtls/fairdatapoint/entity/schema/MetadataSchemaState.java new file mode 100644 index 000000000..ab6565ef5 --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/entity/schema/MetadataSchemaState.java @@ -0,0 +1,29 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.entity.schema; + +public enum MetadataSchemaState { + DRAFT, + LATEST, + LEGACY +} diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/schema/MetadataSchemaVersion.java b/src/main/java/nl/dtls/fairdatapoint/entity/schema/MetadataSchemaVersion.java new file mode 100644 index 000000000..b26dec86b --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/entity/schema/MetadataSchemaVersion.java @@ -0,0 +1,143 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.entity.schema; + +import io.hypersistence.utils.hibernate.type.array.ListArrayType; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; +import lombok.*; +import lombok.experimental.SuperBuilder; +import nl.dtls.fairdatapoint.entity.base.BaseEntityCustomUUID; +import org.hibernate.annotations.JdbcType; +import org.hibernate.annotations.Type; +import org.hibernate.dialect.PostgreSQLEnumJdbcType; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.UUID; + +@Entity(name = "MetadataSchemaVersion") +@Table(name = "metadata_schema_version") +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +@SuperBuilder(toBuilder = true) +public class MetadataSchemaVersion extends BaseEntityCustomUUID { + + @NotNull + @ManyToOne + @JoinColumn(name = "metadata_schema_id", nullable = false) + private MetadataSchema schema; + + @OneToOne(fetch = FetchType.LAZY) + @JoinColumn(name = "previous_version_id", nullable = false) + private MetadataSchemaVersion previousVersion; + + @OneToOne(fetch = FetchType.LAZY, mappedBy = "previousVersion") + private MetadataSchemaVersion nextVersion; + + @NotNull + @Column(name = "version", nullable = false) + private String version; + + @NotNull + @NotBlank + @Column(name = "name", nullable = false) + private String name; + + @NotNull + @Column(name = "description", nullable = false) + private String description; + + @NotNull + @Column(name = "definition", nullable = false) + private String definition; + + @NotNull + @Type(ListArrayType.class) + @Column(name = "target_classes", columnDefinition = "text[]", nullable = false) + private List targetClasses; + + @NotNull + @Enumerated(EnumType.STRING) + @JdbcType(PostgreSQLEnumJdbcType.class) + @Column(name = "type", columnDefinition = "METADATA_SCHEMA_TYPE", nullable = false) + private MetadataSchemaType type; + + @Column(name = "origin") + private String origin; + + @Column(name = "imported_from") + private String importedFrom; + + @NotNull + @Enumerated(EnumType.STRING) + @JdbcType(PostgreSQLEnumJdbcType.class) + @Column(name = "state", columnDefinition = "METADATA_SCHEMA_STATE", nullable = false) + private MetadataSchemaState state; + + @NotNull + @Column(name = "published", nullable = false) + private boolean published; + + @NotNull + @Column(name = "abstract", nullable = false) + private boolean abstractSchema; + + @Column(name = "suggested_resource_name") + private String suggestedResourceName; + + @Column(name = "suggested_url_prefix") + private String suggestedUrlPrefix; + + @OneToMany(mappedBy = "metadataSchemaVersion", fetch = FetchType.EAGER, + cascade = CascadeType.ALL, orphanRemoval = true) + private List extensions; + + public boolean isDraft() { + return getState().equals(MetadataSchemaState.DRAFT); + } + + public boolean isLatest() { + return getState().equals(MetadataSchemaState.LATEST); + } + + public Set getTargetClassesSet() { + return new HashSet<>(getTargetClasses()); + } + + public void setTargetClassesSet(Set targetClassesSet) { + setTargetClasses(targetClassesSet.stream().toList()); + } + + public UUID extractSchemaUuid() { + return getSchema().getUuid(); + } + + public SemVer getSemVer() { + return new SemVer(getVersion()); + } +} diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/search/SearchSavedQuery.java b/src/main/java/nl/dtls/fairdatapoint/entity/search/SearchSavedQuery.java index 48b9eb3e4..6522ebd86 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/search/SearchSavedQuery.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/search/SearchSavedQuery.java @@ -22,38 +22,53 @@ */ package nl.dtls.fairdatapoint.entity.search; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import lombok.*; -import nl.dtls.fairdatapoint.api.dto.search.SearchQueryVariablesDTO; -import org.bson.types.ObjectId; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import lombok.experimental.SuperBuilder; +import nl.dtls.fairdatapoint.entity.base.BaseEntity; +import nl.dtls.fairdatapoint.entity.user.UserAccount; +import org.hibernate.annotations.JdbcType; +import org.hibernate.dialect.PostgreSQLEnumJdbcType; -import java.time.Instant; - -@Document -@NoArgsConstructor -@AllArgsConstructor +@Entity(name = "SearchSavedQuery") +@Table(name = "search_saved_query") @Getter @Setter -@Builder(toBuilder = true) -public class SearchSavedQuery { - - @Id - private ObjectId id; - - private String uuid; +@NoArgsConstructor +@AllArgsConstructor +@SuperBuilder(toBuilder = true) +public class SearchSavedQuery extends BaseEntity { + @NotNull + @Column(name = "name", nullable = false) private String name; + @NotNull + @Column(name = "description", nullable = false) private String description; - private String userUuid; + @NotNull + @ManyToOne + @JoinColumn(name = "user_account_id", nullable = false) + private UserAccount userAccount; + @NotNull + @Enumerated(EnumType.STRING) + @JdbcType(PostgreSQLEnumJdbcType.class) + @Column(name = "type", columnDefinition = "SAVED_QUERY_TYPE", nullable = false) private SearchSavedQueryType type; - private Instant createdAt; + @NotNull + @Column(name = "var_prefixes", nullable = false) + private String varPrefixes; + + @NotNull + @Column(name = "var_graph_pattern", nullable = false) + private String varGraphPattern; - private Instant updatedAt; + @NotNull + @Column(name = "var_ordering", nullable = false) + private String varOrdering; - private SearchQueryVariablesDTO variables; } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/settings/Settings.java b/src/main/java/nl/dtls/fairdatapoint/entity/settings/Settings.java index e06469fed..3326c3808 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/settings/Settings.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/settings/Settings.java @@ -22,88 +22,53 @@ */ package nl.dtls.fairdatapoint.entity.settings; -import com.fasterxml.jackson.annotation.JsonIgnore; +import io.hypersistence.utils.hibernate.type.array.ListArrayType; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import lombok.*; -import org.bson.types.ObjectId; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import lombok.experimental.SuperBuilder; +import nl.dtls.fairdatapoint.entity.base.BaseEntityCustomUUID; +import org.hibernate.annotations.Type; -import java.util.Collections; import java.util.List; -@Document +@Entity(name = "Settings") +@Table(name = "settings") @NoArgsConstructor @AllArgsConstructor @Getter @Setter -@EqualsAndHashCode -@Builder(toBuilder = true) -public class Settings { - - private static final List DEFAULT_METRICS = List.of( - new SettingsMetricsEntry( - "https://purl.org/fair-metrics/FM_F1A", - "https://www.ietf.org/rfc/rfc3986.txt" - ), - new SettingsMetricsEntry( - "https://purl.org/fair-metrics/FM_A1.1", - "https://www.wikidata.org/wiki/Q8777" - ) - ); - - @Id - @JsonIgnore - private ObjectId id; +@SuperBuilder(toBuilder = true) +public class Settings extends BaseEntityCustomUUID { + @Column(name = "app_title") private String appTitle; + @Column(name = "app_subtitle") private String appSubtitle; - private List metadataMetrics; + @NotNull + @Column(name = "ping_enabled", nullable = false) + private Boolean pingEnabled; - private SettingsPing ping; + @NotNull + @Type(ListArrayType.class) + @Column(name = "ping_endpoints", columnDefinition = "text[]", nullable = false) + private List pingEndpoints; - private List searchFilters; + @NotNull + @Column(name = "autocomplete_search_ns", nullable = false) + private Boolean autocompleteSearchNamespace; - private SettingsForms forms; + @OrderBy("orderPriority") + @OneToMany(fetch = FetchType.LAZY, mappedBy = "settings", cascade = CascadeType.ALL, orphanRemoval = true) + private List autocompleteSources; - public static Settings getDefault() { - return Settings - .builder() - .appTitle(null) - .appSubtitle(null) - .metadataMetrics(DEFAULT_METRICS) - .ping(SettingsPing - .builder() - .enabled(true) - .endpoints(Collections.emptyList()) - .build() - ) - .searchFilters(Collections.emptyList()) - .forms(SettingsForms - .builder() - .autocomplete(SettingsFormsAutocomplete - .builder() - .searchNamespace(true) - .sources(Collections.emptyList()) - .build() - ) - .build() - ) - .build(); - } + @OrderBy("orderPriority") + @OneToMany(fetch = FetchType.LAZY, mappedBy = "settings", cascade = CascadeType.ALL, orphanRemoval = true) + private List metrics; - public List getSearchFilters() { - if (searchFilters == null) { - return Collections.emptyList(); - } - return searchFilters; - } - - public SettingsForms getForms() { - if (forms == null) { - return getDefault().getForms(); - } - return forms; - } + @OrderBy("orderPriority") + @OneToMany(fetch = FetchType.LAZY, mappedBy = "settings", cascade = CascadeType.ALL, orphanRemoval = true) + private List searchFilters; } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsAutocompleteSource.java b/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsAutocompleteSource.java index 49537dc9e..c6766cf31 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsAutocompleteSource.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsAutocompleteSource.java @@ -22,19 +22,39 @@ */ package nl.dtls.fairdatapoint.entity.settings; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import lombok.*; +import lombok.experimental.SuperBuilder; +import nl.dtls.fairdatapoint.entity.base.BaseEntity; +@Entity(name = "SettingsAutocompleteSource") +@Table(name = "settings_autocomplete_source") @NoArgsConstructor @AllArgsConstructor @Getter @Setter -@EqualsAndHashCode -@Builder(toBuilder = true) -public class SettingsAutocompleteSource { +@SuperBuilder +public class SettingsAutocompleteSource extends BaseEntity { + @NotNull + @Column(name = "rdf_type", nullable = false) private String rdfType; + @NotNull + @Column(name = "sparql_endpoint", nullable = false) private String sparqlEndpoint; + @NotNull + @Column(name = "sparql_query", nullable = false) private String sparqlQuery; + + @NotNull + @Column(name = "order_priority", nullable = false) + private Integer orderPriority; + + @NotNull + @ManyToOne + @JoinColumn(name = "settings_id", nullable = false) + private Settings settings; } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsMetric.java b/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsMetric.java new file mode 100644 index 000000000..e86f3a709 --- /dev/null +++ b/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsMetric.java @@ -0,0 +1,56 @@ +/** + * The MIT License + * Copyright © 2017 DTL + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + */ +package nl.dtls.fairdatapoint.entity.settings; + +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; +import lombok.*; +import lombok.experimental.SuperBuilder; +import nl.dtls.fairdatapoint.entity.base.BaseEntity; + +@Entity(name = "SettingsMetric") +@Table(name = "settings_metric") +@NoArgsConstructor +@AllArgsConstructor +@Getter +@Setter +@SuperBuilder +public class SettingsMetric extends BaseEntity { + + @NotNull + @Column(name = "metric_uri", nullable = false) + private String metricUri; + + @NotNull + @Column(name = "resource_uri", nullable = false) + private String resourceUri; + + @NotNull + @Column(name = "order_priority", nullable = false) + private Integer orderPriority; + + @NotNull + @ManyToOne + @JoinColumn(name = "settings_id", nullable = false) + private Settings settings; +} diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsSearchFilter.java b/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsSearchFilter.java index 7ded4781c..a45d21cd3 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsSearchFilter.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsSearchFilter.java @@ -22,26 +22,53 @@ */ package nl.dtls.fairdatapoint.entity.settings; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import lombok.*; +import lombok.experimental.SuperBuilder; +import nl.dtls.fairdatapoint.entity.base.BaseEntity; import nl.dtls.fairdatapoint.entity.search.SearchFilterType; +import org.hibernate.annotations.JdbcType; +import org.hibernate.dialect.PostgreSQLEnumJdbcType; import java.util.List; +@Entity(name = "SettingsSearchFilter") +@Table(name = "settings_search_filter") @NoArgsConstructor @AllArgsConstructor @Getter @Setter -@EqualsAndHashCode -@Builder(toBuilder = true) -public class SettingsSearchFilter { +@SuperBuilder +public class SettingsSearchFilter extends BaseEntity { + @NotNull + @Enumerated(EnumType.STRING) + @JdbcType(PostgreSQLEnumJdbcType.class) + @Column(name = "type", columnDefinition = "SEARCH_FILTER_TYPE", nullable = false) private SearchFilterType type; + @NotNull + @Column(name = "label", nullable = false) private String label; + @NotNull + @Column(name = "predicate", nullable = false) private String predicate; - private List presetValues; + @NotNull + @Column(name = "query_records", nullable = false) + private Boolean queryRecords; - private boolean queryFromRecords; + @NotNull + @Column(name = "order_priority", nullable = false) + private Integer orderPriority; + + @NotNull + @ManyToOne + @JoinColumn(name = "settings_id", nullable = false) + private Settings settings; + + @OneToMany(fetch = FetchType.LAZY, mappedBy = "filter", cascade = CascadeType.ALL, orphanRemoval = true) + private List items; } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsSearchFilterItem.java b/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsSearchFilterItem.java index b16d1d4ae..18f5475c4 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsSearchFilterItem.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsSearchFilterItem.java @@ -22,17 +22,35 @@ */ package nl.dtls.fairdatapoint.entity.settings; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import lombok.*; +import lombok.experimental.SuperBuilder; +import nl.dtls.fairdatapoint.entity.base.BaseEntity; +@Entity(name = "SettingsSearchFilterItem") +@Table(name = "settings_search_filter_item") @NoArgsConstructor @AllArgsConstructor @Getter @Setter -@EqualsAndHashCode -@Builder(toBuilder = true) -public class SettingsSearchFilterItem { +@SuperBuilder +public class SettingsSearchFilterItem extends BaseEntity { + @NotNull + @Column(name = "value", nullable = false) private String value; + @NotNull + @Column(name = "label", nullable = false) private String label; + + @NotNull + @Column(name = "order_priority", nullable = false) + private Integer orderPriority; + + @NotNull + @ManyToOne + @JoinColumn(name = "filter_id", nullable = false) + private SettingsSearchFilter filter; } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/user/User.java b/src/main/java/nl/dtls/fairdatapoint/entity/user/UserAccount.java similarity index 54% rename from src/main/java/nl/dtls/fairdatapoint/entity/user/User.java rename to src/main/java/nl/dtls/fairdatapoint/entity/user/UserAccount.java index 7a4f4b958..40fac2069 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/user/User.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/user/UserAccount.java @@ -22,39 +22,61 @@ */ package nl.dtls.fairdatapoint.entity.user; +import jakarta.persistence.*; +import jakarta.validation.constraints.NotNull; import lombok.*; -import org.bson.types.ObjectId; -import org.springframework.data.annotation.Id; -import org.springframework.data.mongodb.core.mapping.Document; +import lombok.experimental.SuperBuilder; +import nl.dtls.fairdatapoint.entity.apikey.ApiKey; +import nl.dtls.fairdatapoint.entity.base.BaseEntity; +import nl.dtls.fairdatapoint.entity.search.SearchSavedQuery; +import org.hibernate.annotations.JdbcType; +import org.hibernate.dialect.PostgreSQLEnumJdbcType; -@Document -@NoArgsConstructor -@AllArgsConstructor +import java.util.List; +import java.util.UUID; + +@Entity(name = "UserAccount") +@Table(name = "user_account") @Getter @Setter -@Builder(toBuilder = true) -public class User { - - @Id - private ObjectId id; - - private String uuid; +@NoArgsConstructor +@AllArgsConstructor +@SuperBuilder(toBuilder = true) +public class UserAccount extends BaseEntity { + @NotNull + @Column(name = "first_name", nullable = false) private String firstName; + @NotNull + @Column(name = "last_name", nullable = false) private String lastName; + @NotNull + @Column(name = "email", nullable = false) private String email; + @NotNull + @Column(name = "password_hash", nullable = false) private String passwordHash; + @NotNull + @Enumerated(EnumType.STRING) + @JdbcType(PostgreSQLEnumJdbcType.class) + @Column(name = "user_role", columnDefinition = "USER_ROLE", nullable = false) private UserRole role; - public User( - String uuid, String firstName, String lastName, + @OneToMany(fetch = FetchType.LAZY, mappedBy = "userAccount", cascade = CascadeType.ALL, orphanRemoval = true) + private List apiKeys; + + @OneToMany(fetch = FetchType.LAZY, mappedBy = "userAccount", cascade = CascadeType.ALL, orphanRemoval = true) + private List searchSavedQueries; + + public UserAccount( + UUID uuid, String firstName, String lastName, String email, String passwordHash, UserRole role ) { - this.uuid = uuid; + this.setUuid(uuid); this.firstName = firstName; this.lastName = lastName; this.email = email; diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/user/UserRole.java b/src/main/java/nl/dtls/fairdatapoint/entity/user/UserRole.java index a681e6f01..168bf918e 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/user/UserRole.java +++ b/src/main/java/nl/dtls/fairdatapoint/entity/user/UserRole.java @@ -23,7 +23,6 @@ package nl.dtls.fairdatapoint.entity.user; public enum UserRole { - - ADMIN, USER - + ADMIN, + USER } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/UtilityService.java b/src/main/java/nl/dtls/fairdatapoint/service/UtilityService.java index a280c7a3d..def3dfa4f 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/UtilityService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/UtilityService.java @@ -23,16 +23,16 @@ package nl.dtls.fairdatapoint.service; import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.config.properties.InstanceProperties; import nl.dtls.fairdatapoint.util.HttpUtil; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service +@RequiredArgsConstructor public class UtilityService { - @Autowired - private InstanceProperties instanceProperties; + private final InstanceProperties instanceProperties; public String getRemoteAddr(HttpServletRequest request) { return HttpUtil.getClientIpAddress(request, instanceProperties.isBehindProxy()); diff --git a/src/main/java/nl/dtls/fairdatapoint/service/apikey/ApiKeyMapper.java b/src/main/java/nl/dtls/fairdatapoint/service/apikey/ApiKeyMapper.java index 4d64b4e8f..3451ffc3c 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/apikey/ApiKeyMapper.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/apikey/ApiKeyMapper.java @@ -24,13 +24,23 @@ import nl.dtls.fairdatapoint.api.dto.apikey.ApiKeyDTO; import nl.dtls.fairdatapoint.entity.apikey.ApiKey; -import org.springframework.stereotype.Service; +import nl.dtls.fairdatapoint.entity.user.UserAccount; +import org.springframework.stereotype.Component; -@Service +import java.util.UUID; + +@Component public class ApiKeyMapper { public ApiKeyDTO toDTO(ApiKey apiKey) { return new ApiKeyDTO(apiKey.getUuid(), apiKey.getToken()); } + public ApiKey createApiKey(UserAccount userAccount, String token) { + return ApiKey.builder() + .uuid(UUID.randomUUID()) + .token(token) + .userAccount(userAccount) + .build(); + } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/apikey/ApiKeyService.java b/src/main/java/nl/dtls/fairdatapoint/service/apikey/ApiKeyService.java index 45b2a2473..791150d86 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/apikey/ApiKeyService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/apikey/ApiKeyService.java @@ -22,17 +22,17 @@ */ package nl.dtls.fairdatapoint.service.apikey; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.apikey.ApiKeyDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.ApiKeyRepository; +import nl.dtls.fairdatapoint.database.db.repository.ApiKeyRepository; import nl.dtls.fairdatapoint.entity.apikey.ApiKey; import nl.dtls.fairdatapoint.entity.exception.ForbiddenException; import nl.dtls.fairdatapoint.entity.exception.UnauthorizedException; -import nl.dtls.fairdatapoint.entity.user.User; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import nl.dtls.fairdatapoint.entity.user.UserRole; -import nl.dtls.fairdatapoint.service.security.MongoAuthenticationService; +import nl.dtls.fairdatapoint.service.security.AuthenticationService; import nl.dtls.fairdatapoint.service.user.CurrentUserService; import org.apache.commons.lang3.RandomStringUtils; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Service; @@ -42,58 +42,55 @@ import java.util.stream.Collectors; @Service +@RequiredArgsConstructor public class ApiKeyService { private static final int TOKEN_SIZE = 128; private static final String MSG_LOGIN_FIRST = "You have to log in"; - @Autowired - private ApiKeyRepository apiKeyRepository; + private final ApiKeyRepository apiKeyRepository; - @Autowired - private CurrentUserService currentUserService; + private final CurrentUserService currentUserService; - @Autowired - private MongoAuthenticationService mongoAuthenticationService; + private final AuthenticationService authenticationService; - @Autowired - private ApiKeyMapper apiKeyMapper; + private final ApiKeyMapper apiKeyMapper; public List getAll() { - final Optional user = currentUserService.getCurrentUser(); + final Optional user = currentUserService.getCurrentUser(); if (user.isEmpty()) { throw new UnauthorizedException(MSG_LOGIN_FIRST); } - return apiKeyRepository.findByUserUuid(user.get().getUuid()) + return user.get() + .getApiKeys() .stream() .map(apiKeyMapper::toDTO) .collect(Collectors.toList()); } public ApiKeyDTO create() { - final Optional user = currentUserService.getCurrentUser(); + final Optional user = currentUserService.getCurrentUser(); if (user.isEmpty()) { throw new UnauthorizedException(MSG_LOGIN_FIRST); } final String generatedString = RandomStringUtils.random(TOKEN_SIZE, true, true); - final String uuid = UUID.randomUUID().toString(); - final ApiKey apiKey = new ApiKey(null, uuid, user.get().getUuid(), generatedString); + final ApiKey apiKey = apiKeyMapper.createApiKey(user.get(), generatedString); apiKeyRepository.save(apiKey); return apiKeyMapper.toDTO(apiKey); } - public boolean delete(String uuid) { + public boolean delete(UUID uuid) { final Optional apiKey = apiKeyRepository.findByUuid(uuid); if (apiKey.isEmpty()) { return false; } - final Optional user = currentUserService.getCurrentUser(); + final Optional user = currentUserService.getCurrentUser(); if (user.isEmpty()) { throw new ForbiddenException(MSG_LOGIN_FIRST); } if (user.get().getRole().equals(UserRole.ADMIN) - || apiKey.get().getUserUuid().equals(user.get().getUuid())) { + || apiKey.get().getUserAccount().equals(user.get())) { apiKeyRepository.delete(apiKey.get()); return true; } @@ -107,7 +104,6 @@ public Authentication getAuthentication(String token) { if (apiKey.isEmpty()) { throw new UnauthorizedException("Invalid or non-existing API key"); } - return mongoAuthenticationService.getAuthentication(apiKey.get().getUserUuid()); + return authenticationService.getAuthentication(apiKey.get().getUserAccount().getUuid().toString()); } - } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/dashboard/DashboardService.java b/src/main/java/nl/dtls/fairdatapoint/service/dashboard/DashboardService.java index 0d4a6a07b..888493f75 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/dashboard/DashboardService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/dashboard/DashboardService.java @@ -86,7 +86,7 @@ private DashboardItemDTO getDashboardItem( final DashboardItemDTO child = getDashboardItem( childIri, metadataService.retrieve(childIri), - resourceDefinitionCache.getByUuid(rdChild.getResourceDefinitionUuid()) + resourceDefinitionCache.getByUuid(rdChild.getTarget().getUuid()) ); children.add(child); } @@ -109,6 +109,6 @@ private DashboardItemDTO getDashboardItem( } private boolean childOnDashboard(DashboardItemDTO item) { - return item.getMembership().isPresent() || item.getChildren().size() > 0; + return item.getMembership().isPresent() || !item.getChildren().isEmpty(); } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/form/autocomplete/FormsAutocompleteCache.java b/src/main/java/nl/dtls/fairdatapoint/service/form/autocomplete/FormsAutocompleteCache.java index 98efbbd28..807ce925e 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/form/autocomplete/FormsAutocompleteCache.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/form/autocomplete/FormsAutocompleteCache.java @@ -22,8 +22,8 @@ */ package nl.dtls.fairdatapoint.service.form.autocomplete; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.entity.forms.RdfEntityCacheContainer; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.Cache; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.stereotype.Component; @@ -31,10 +31,10 @@ import static nl.dtls.fairdatapoint.config.CacheConfig.FORMS_AUTOCOMPLETE_CACHE; @Component +@RequiredArgsConstructor public class FormsAutocompleteCache { - @Autowired - private ConcurrentMapCacheManager cacheManager; + private final ConcurrentMapCacheManager cacheManager; public void clear() { cache().clear(); diff --git a/src/main/java/nl/dtls/fairdatapoint/service/form/autocomplete/FormsAutocompleteService.java b/src/main/java/nl/dtls/fairdatapoint/service/form/autocomplete/FormsAutocompleteService.java index 60671d360..982876b47 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/form/autocomplete/FormsAutocompleteService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/form/autocomplete/FormsAutocompleteService.java @@ -22,6 +22,7 @@ */ package nl.dtls.fairdatapoint.service.form.autocomplete; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.form.FormAutocompleteItemDTO; import nl.dtls.fairdatapoint.api.dto.form.FormAutocompleteRequestDTO; import nl.dtls.fairdatapoint.entity.forms.RdfEntityCacheContainer; @@ -30,7 +31,6 @@ import nl.dtls.fairdatapoint.service.form.autocomplete.retrieval.RdfEntitiesRetriever; import nl.dtls.fairdatapoint.service.form.autocomplete.retrieval.RdfEntitiesSparqlRetriever; import nl.dtls.fairdatapoint.service.settings.SettingsService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Collections; @@ -38,19 +38,16 @@ import java.util.Map; @Service +@RequiredArgsConstructor public class FormsAutocompleteService { - @Autowired - private FormsAutocompleteCache cache; + private final FormsAutocompleteCache cache; - @Autowired - private RdfEntitiesNamespaceRetriever namespaceRetriever; + private final RdfEntitiesNamespaceRetriever namespaceRetriever; - @Autowired - private RdfEntitiesSparqlRetriever sparqlRetriever; + private final RdfEntitiesSparqlRetriever sparqlRetriever; - @Autowired - private SettingsService settingsService; + private final SettingsService settingsService; public List searchItems(FormAutocompleteRequestDTO reqDto) { RdfEntityCacheContainer container = cache.get(reqDto.getRdfType()); @@ -77,7 +74,7 @@ public List filterItems(String query, RdfEntityCacheCon public RdfEntityCacheContainer retrieveItems(String rdfType) { final Settings settings = settingsService.getOrDefaults(); RdfEntityCacheContainer container = null; - if (settings.getForms().getAutocomplete().getSearchNamespace()) { + if (settings.getAutocompleteSearchNamespace()) { container = retrieveItems(rdfType, namespaceRetriever); } if (container == null) { diff --git a/src/main/java/nl/dtls/fairdatapoint/service/form/autocomplete/retrieval/RdfEntitiesSparqlRetriever.java b/src/main/java/nl/dtls/fairdatapoint/service/form/autocomplete/retrieval/RdfEntitiesSparqlRetriever.java index b44b92823..0de8b5e83 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/form/autocomplete/retrieval/RdfEntitiesSparqlRetriever.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/form/autocomplete/retrieval/RdfEntitiesSparqlRetriever.java @@ -49,9 +49,7 @@ public class RdfEntitiesSparqlRetriever implements RdfEntitiesRetriever { public Map retrieve(String rdfType) { return settingsService .getOrDefaults() - .getForms() - .getAutocomplete() - .getSources() + .getAutocompleteSources() .stream() .filter(source -> source.getRdfType().equals(rdfType)) .findFirst() diff --git a/src/main/java/nl/dtls/fairdatapoint/service/index/common/IndexFeatureAspect.java b/src/main/java/nl/dtls/fairdatapoint/service/index/common/IndexFeatureAspect.java index e58f42271..aa063d5cc 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/index/common/IndexFeatureAspect.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/index/common/IndexFeatureAspect.java @@ -22,21 +22,21 @@ */ package nl.dtls.fairdatapoint.service.index.common; +import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import nl.dtls.fairdatapoint.config.properties.InstanceProperties; import nl.dtls.fairdatapoint.entity.exception.FeatureDisabledException; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @Aspect @Component +@RequiredArgsConstructor public class IndexFeatureAspect { - @Autowired - private InstanceProperties instanceProperties; + private final InstanceProperties instanceProperties; @SneakyThrows @Around("@annotation(nl.dtls.fairdatapoint.service.index.common.RequiredEnabledIndexFeature)") diff --git a/src/main/java/nl/dtls/fairdatapoint/service/index/entry/IndexEntryMapper.java b/src/main/java/nl/dtls/fairdatapoint/service/index/entry/IndexEntryMapper.java index 4a290519a..e97e4a801 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/index/entry/IndexEntryMapper.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/index/entry/IndexEntryMapper.java @@ -27,7 +27,8 @@ import nl.dtls.fairdatapoint.api.dto.index.entry.IndexEntryStateDTO; import nl.dtls.fairdatapoint.entity.index.entry.IndexEntry; import nl.dtls.fairdatapoint.entity.index.entry.IndexEntryState; -import nl.dtls.fairdatapoint.entity.index.event.Event; +import nl.dtls.fairdatapoint.entity.index.entry.RepositoryMetadata; +import nl.dtls.fairdatapoint.entity.index.event.IndexEvent; import nl.dtls.fairdatapoint.service.index.event.EventMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -46,31 +47,31 @@ public IndexEntryDTO toDTO(IndexEntry indexEntry, Instant validThreshold) { indexEntry.getUuid(), indexEntry.getClientUrl(), toStateDTO(indexEntry.getState(), - indexEntry.getLastRetrievalTime(), + indexEntry.getLastRetrievalAt(), validThreshold), indexEntry.getPermit(), - indexEntry.getRegistrationTime().toString(), - indexEntry.getModificationTime().toString() + indexEntry.getCreatedAt().toString(), + indexEntry.getUpdatedAt().toString() ); } public IndexEntryDetailDTO toDetailDTO( - IndexEntry indexEntry, Iterable events, Instant validThreshold + IndexEntry indexEntry, Iterable events, Instant validThreshold ) { return new IndexEntryDetailDTO( indexEntry.getUuid(), indexEntry.getClientUrl(), toStateDTO(indexEntry.getState(), - indexEntry.getLastRetrievalTime(), + indexEntry.getLastRetrievalAt(), validThreshold), indexEntry.getPermit(), - indexEntry.getCurrentMetadata(), + toRepositoryMetadata(indexEntry), StreamSupport.stream(events.spliterator(), false) .map(eventMapper::toDTO) .toList(), - indexEntry.getRegistrationTime().toString(), - indexEntry.getModificationTime().toString(), - indexEntry.getLastRetrievalTime().toString() + indexEntry.getCreatedAt().toString(), + indexEntry.getUpdatedAt().toString(), + indexEntry.getLastRetrievalAt().toString() ); } @@ -78,13 +79,21 @@ public IndexEntryStateDTO toStateDTO( IndexEntryState state, Instant lastRetrievalTime, Instant validThreshold ) { return switch (state) { - case Unknown -> IndexEntryStateDTO.UNKNOWN; - case Valid -> lastRetrievalTime.isAfter(validThreshold) + case UNKNOWN -> IndexEntryStateDTO.UNKNOWN; + case VALID -> lastRetrievalTime.isAfter(validThreshold) ? IndexEntryStateDTO.ACTIVE : IndexEntryStateDTO.INACTIVE; - case Invalid -> IndexEntryStateDTO.INVALID; - case Unreachable -> IndexEntryStateDTO.UNREACHABLE; + case INVALID -> IndexEntryStateDTO.INVALID; + case UNREACHABLE -> IndexEntryStateDTO.UNREACHABLE; }; } + private RepositoryMetadata toRepositoryMetadata(IndexEntry entry) { + return RepositoryMetadata.builder() + .repositoryUri(entry.getRepositoryUri()) + .metadataVersion(entry.getMetadataVersion()) + .metadata(entry.getMetadata()) + .build(); + } + } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/index/entry/IndexEntryService.java b/src/main/java/nl/dtls/fairdatapoint/service/index/entry/IndexEntryService.java index 34a5cd9b5..17e117e9f 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/index/entry/IndexEntryService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/index/entry/IndexEntryService.java @@ -23,10 +23,12 @@ package nl.dtls.fairdatapoint.service.index.entry; import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import nl.dtls.fairdatapoint.api.dto.index.entry.*; import nl.dtls.fairdatapoint.api.dto.index.ping.PingDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.IndexEntryRepository; +import nl.dtls.fairdatapoint.database.db.repository.IndexEntryRepository; +import nl.dtls.fairdatapoint.database.db.repository.IndexEventRepository; import nl.dtls.fairdatapoint.database.rdf.repository.RepositoryMode; import nl.dtls.fairdatapoint.database.rdf.repository.exception.MetadataRepositoryException; import nl.dtls.fairdatapoint.database.rdf.repository.generic.GenericMetadataRepository; @@ -34,21 +36,21 @@ import nl.dtls.fairdatapoint.entity.index.entry.IndexEntry; import nl.dtls.fairdatapoint.entity.index.entry.IndexEntryPermit; import nl.dtls.fairdatapoint.entity.index.entry.IndexEntryState; +import nl.dtls.fairdatapoint.entity.index.event.IndexEvent; import nl.dtls.fairdatapoint.entity.index.settings.IndexSettings; import nl.dtls.fairdatapoint.service.index.common.RequiredEnabledIndexFeature; -import nl.dtls.fairdatapoint.service.index.event.EventService; import nl.dtls.fairdatapoint.service.index.harvester.HarvesterService; import nl.dtls.fairdatapoint.service.index.settings.IndexSettingsService; import nl.dtls.fairdatapoint.service.user.CurrentUserService; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.impl.TreeModel; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; import org.springframework.scheduling.annotation.Async; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; -import org.springframework.validation.annotation.Validated; import java.time.Instant; import java.util.*; @@ -57,36 +59,30 @@ import static nl.dtls.fairdatapoint.api.dto.index.entry.IndexEntryStateDTO.*; import static nl.dtls.fairdatapoint.util.ValueFactoryHelper.i; +import static org.lwjgl.system.MemoryUtil.PAGE_SIZE; @Slf4j @Service -@Validated +@RequiredArgsConstructor public class IndexEntryService { private static final String MSG_NOT_FOUND = "Index entry not found"; private static final String FILTER_ALL = "ALL"; - @Autowired - private IndexEntryRepository repository; + private final IndexEntryRepository repository; - @Autowired - private IndexSettingsService indexSettingsService; + private final IndexSettingsService indexSettingsService; - @Autowired - private EventService eventService; + private final IndexEventRepository eventRepository; - @Autowired - private IndexEntryMapper mapper; + private final IndexEntryMapper mapper; - @Autowired - private GenericMetadataRepository genericMetadataRepository; + private final GenericMetadataRepository genericMetadataRepository; - @Autowired - private HarvesterService harvesterService; + private final HarvesterService harvesterService; - @Autowired - private CurrentUserService currentUserService; + private final CurrentUserService currentUserService; @RequiredEnabledIndexFeature public Iterable getAllEntries() { @@ -136,28 +132,28 @@ private Page getEntriesPageWithPermits(Pageable pageable, String sta List permit) { final Instant validThreshold = getValidThreshold(); if (state.equalsIgnoreCase(ACTIVE.name())) { - return repository.findAllByStateEqualsAndLastRetrievalTimeAfterAndPermitIn( - pageable, IndexEntryState.Valid, validThreshold, permit + return repository.findAllByStateEqualsAndLastRetrievalAtAfterAndPermitIn( + pageable, IndexEntryState.VALID, validThreshold, permit ); } if (state.equalsIgnoreCase(IndexEntryStateDTO.INACTIVE.name())) { - return repository.findAllByStateEqualsAndLastRetrievalTimeBeforeAndPermitIn( - pageable, IndexEntryState.Valid, validThreshold, permit + return repository.findAllByStateEqualsAndLastRetrievalAtBeforeAndPermitIn( + pageable, IndexEntryState.VALID, validThreshold, permit ); } if (state.equalsIgnoreCase(IndexEntryStateDTO.UNREACHABLE.name())) { return repository.findAllByStateEqualsAndPermitIn( - pageable, IndexEntryState.Unreachable, permit + pageable, IndexEntryState.UNREACHABLE, permit ); } if (state.equalsIgnoreCase(IndexEntryStateDTO.INVALID.name())) { return repository.findAllByStateEqualsAndPermitIn( - pageable, IndexEntryState.Invalid, permit + pageable, IndexEntryState.INVALID, permit ); } if (state.equalsIgnoreCase(IndexEntryStateDTO.UNKNOWN.name())) { return repository.findAllByStateEqualsAndPermitIn( - pageable, IndexEntryState.Unknown, permit + pageable, IndexEntryState.UNKNOWN, permit ); } return repository.findAllByPermitIn(pageable, permit); @@ -171,21 +167,32 @@ public Page getEntriesPageDTOs(Pageable pageable, String state, S } @RequiredEnabledIndexFeature - public Optional getEntry(String uuid) { + public Optional getEntry(UUID uuid) { return repository.findByUuid(uuid); } @RequiredEnabledIndexFeature - public Optional getEntryDetailDTO(String uuid) { + public Optional getEntryDetailDTO(UUID uuid) { final Instant validThreshold = getValidThreshold(); return getEntry(uuid) .map(entry -> { return mapper.toDetailDTO( - entry, eventService.getEvents(entry.getUuid()), validThreshold + entry, getEvents(entry.getUuid()), validThreshold ); }); } + @RequiredEnabledIndexFeature + private Iterable getEvents(UUID indexEntryUuid) { + return getEntry(indexEntryUuid) + .map(this::getEvents).orElse(Collections.emptyList()); + } + + public Iterable getEvents(IndexEntry indexEntry) { + return eventRepository.getAllByRelatedTo(indexEntry, + PageRequest.of(0, PAGE_SIZE, Sort.by(Sort.Direction.DESC, "created"))); + } + @RequiredEnabledIndexFeature public IndexEntryInfoDTO getEntriesInfo(String permitQuery) { final List permit = getPermits(permitQuery); @@ -197,27 +204,27 @@ public IndexEntryInfoDTO getEntriesInfo(String permitQuery) { ); entriesCount.put( UNKNOWN.name(), - repository.countAllByStateEqualsAndPermitIn(IndexEntryState.Unknown, permit) + repository.countAllByStateEqualsAndPermitIn(IndexEntryState.UNKNOWN, permit) ); entriesCount.put( ACTIVE.name(), - repository.countAllByStateEqualsAndLastRetrievalTimeAfterAndPermitIn( - IndexEntryState.Valid, validThreshold, permit + repository.countAllByStateEqualsAndLastRetrievalAtAfterAndPermitIn( + IndexEntryState.VALID, validThreshold, permit ) ); entriesCount.put( INACTIVE.name(), - repository.countAllByStateEqualsAndLastRetrievalTimeBeforeAndPermitIn( - IndexEntryState.Valid, validThreshold, permit + repository.countAllByStateEqualsAndLastRetrievalAtBeforeAndPermitIn( + IndexEntryState.VALID, validThreshold, permit ) ); entriesCount.put( UNREACHABLE.name(), - repository.countAllByStateEqualsAndPermitIn(IndexEntryState.Unreachable, permit) + repository.countAllByStateEqualsAndPermitIn(IndexEntryState.UNREACHABLE, permit) ); entriesCount.put( INVALID.name(), - repository.countAllByStateEqualsAndPermitIn(IndexEntryState.Invalid, permit) + repository.countAllByStateEqualsAndPermitIn(IndexEntryState.INVALID, permit) ); return new IndexEntryInfoDTO(entriesCount); } @@ -226,7 +233,6 @@ public IndexEntryInfoDTO getEntriesInfo(String permitQuery) { public IndexEntry storeEntry(@Valid PingDTO pingDTO) { final String clientUrl = pingDTO.getClientUrl(); final Optional entity = repository.findByClientUrl(clientUrl); - final Instant now = Instant.now(); final IndexSettings settings = indexSettingsService.getOrDefaults(); final IndexEntry entry; @@ -237,9 +243,9 @@ public IndexEntry storeEntry(@Valid PingDTO pingDTO) { else { log.info("Storing new entry {}", clientUrl); entry = new IndexEntry(); - entry.setUuid(UUID.randomUUID().toString()); + entry.setUuid(UUID.randomUUID()); entry.setClientUrl(clientUrl); - entry.setRegistrationTime(now); + entry.setCreatedAt(Instant.now()); if (settings.getAutoPermit()) { entry.setPermit(IndexEntryPermit.ACCEPTED); } @@ -248,13 +254,13 @@ public IndexEntry storeEntry(@Valid PingDTO pingDTO) { } } - entry.setModificationTime(now); - return repository.save(entry); + entry.setUpdatedAt(Instant.now()); + return repository.saveAndFlush(entry); } @RequiredEnabledIndexFeature @PreAuthorize("hasRole('ADMIN')") - public void deleteEntry(String uuid) throws MetadataRepositoryException { + public void deleteEntry(UUID uuid) throws MetadataRepositoryException { final IndexEntry entry = repository.findByUuid(uuid) .orElseThrow(() -> new ResourceNotFoundException(MSG_NOT_FOUND)); harvesterService.deleteHarvestedData(entry.getClientUrl()); @@ -278,7 +284,7 @@ private Instant getValidThreshold() { } @RequiredEnabledIndexFeature - public Model getEntryHarvestedData(String uuid) throws MetadataRepositoryException { + public Model getEntryHarvestedData(UUID uuid) throws MetadataRepositoryException { final IndexEntry entry = repository .findByUuid(uuid) .orElseThrow(() -> new ResourceNotFoundException(MSG_NOT_FOUND)); @@ -287,7 +293,7 @@ public Model getEntryHarvestedData(String uuid) throws MetadataRepositoryExcepti return model; } - public Optional updateEntry(String uuid, IndexEntryUpdateDTO reqDto) { + public Optional updateEntry(UUID uuid, IndexEntryUpdateDTO reqDto) { final Optional entry = getEntry(uuid); if (entry.isPresent() && !reqDto.getPermit().equals(entry.get().getPermit())) { entry.get().setPermit(reqDto.getPermit()); diff --git a/src/main/java/nl/dtls/fairdatapoint/service/index/event/EventMapper.java b/src/main/java/nl/dtls/fairdatapoint/service/index/event/EventMapper.java index 07b7f4280..b34bea19b 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/index/event/EventMapper.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/index/event/EventMapper.java @@ -23,8 +23,8 @@ package nl.dtls.fairdatapoint.service.index.event; import nl.dtls.fairdatapoint.api.dto.index.event.EventDTO; -import nl.dtls.fairdatapoint.entity.index.event.AdminTrigger; -import nl.dtls.fairdatapoint.entity.index.event.Event; +import nl.dtls.fairdatapoint.entity.index.event.payload.AdminTrigger; +import nl.dtls.fairdatapoint.entity.index.event.IndexEvent; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Service; @@ -33,23 +33,23 @@ public class EventMapper { private static final Integer VERSION = 1; - public EventDTO toDTO(Event event) { + public EventDTO toDTO(IndexEvent event) { return new EventDTO( event.getUuid(), event.getType(), - event.getCreated().toString(), - event.getFinished().toString() + event.getCreatedAt().toString(), + event.getFinishedAt().toString() ); } - public Event toAdminTriggerEvent( + public IndexEvent toAdminTriggerEvent( Authentication authentication, String clientUrl, String remoteAddr ) { final AdminTrigger adminTrigger = new AdminTrigger(); adminTrigger.setRemoteAddr(remoteAddr); adminTrigger.setTokenName(authentication.getName()); adminTrigger.setClientUrl(clientUrl); - return new Event(VERSION, adminTrigger); + return new IndexEvent(VERSION, adminTrigger); } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/index/event/EventService.java b/src/main/java/nl/dtls/fairdatapoint/service/index/event/EventService.java index 3ee5b4a80..c49a32ac9 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/index/event/EventService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/index/event/EventService.java @@ -25,30 +25,30 @@ import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.annotation.PostConstruct; import jakarta.servlet.http.HttpServletRequest; +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; import nl.dtls.fairdatapoint.api.dto.index.ping.PingDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.EventRepository; -import nl.dtls.fairdatapoint.database.mongo.repository.IndexEntryRepository; +import nl.dtls.fairdatapoint.database.db.repository.IndexEntryRepository; +import nl.dtls.fairdatapoint.database.db.repository.IndexEventRepository; import nl.dtls.fairdatapoint.entity.index.entry.IndexEntry; import nl.dtls.fairdatapoint.entity.index.entry.IndexEntryState; import nl.dtls.fairdatapoint.entity.index.entry.RepositoryMetadata; -import nl.dtls.fairdatapoint.entity.index.event.Event; -import nl.dtls.fairdatapoint.entity.index.event.EventType; +import nl.dtls.fairdatapoint.entity.index.event.IndexEvent; +import nl.dtls.fairdatapoint.entity.index.event.IndexEventType; import nl.dtls.fairdatapoint.entity.index.exception.IncorrectPingFormatException; import nl.dtls.fairdatapoint.entity.index.exception.PingDeniedException; import nl.dtls.fairdatapoint.entity.index.exception.RateLimitException; import nl.dtls.fairdatapoint.entity.index.http.Exchange; import nl.dtls.fairdatapoint.entity.index.http.ExchangeState; -import nl.dtls.fairdatapoint.entity.index.settings.IndexSettingsPing; -import nl.dtls.fairdatapoint.entity.index.settings.IndexSettingsRetrieval; +import nl.dtls.fairdatapoint.entity.index.settings.SettingsIndexPing; +import nl.dtls.fairdatapoint.entity.index.settings.SettingsIndexRetrieval; import nl.dtls.fairdatapoint.service.UtilityService; import nl.dtls.fairdatapoint.service.index.common.RequiredEnabledIndexFeature; import nl.dtls.fairdatapoint.service.index.entry.IndexEntryService; import nl.dtls.fairdatapoint.service.index.settings.IndexSettingsService; import nl.dtls.fairdatapoint.service.index.webhook.WebhookService; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Lazy; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.http.HttpStatus; @@ -58,70 +58,58 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; -import java.net.http.HttpClient; import java.time.Instant; import java.util.Collections; import java.util.List; import java.util.Optional; +import java.util.UUID; @Slf4j @Service +@RequiredArgsConstructor public class EventService { private static final int PAGE_SIZE = 10; - @Autowired - private ObjectMapper objectMapper; + private final ObjectMapper objectMapper; - @Autowired - private ThreadPoolTaskExecutor executor; + private final ThreadPoolTaskExecutor executor; - @Autowired - private EventRepository eventRepository; + private final IndexEventRepository eventRepository; - @Autowired - private IndexEntryRepository indexEntryRepository; + private final IndexEntryRepository indexEntryRepository; - @Autowired - @Lazy - private IndexEntryService indexEntryService; + private final IndexEntryService indexEntryService; - @Autowired - private WebhookService webhookService; + private final WebhookService webhookService; - @Autowired - private EventMapper eventMapper; + private final EventMapper eventMapper; - @Autowired - private UtilityService utilityService; + private final UtilityService utilityService; - @Autowired - private IncomingPingUtils incomingPingUtils; + private final IncomingPingUtils incomingPingUtils; - @Autowired - private IndexSettingsService indexSettingsService; + private final IndexSettingsService indexSettingsService; - @Autowired - private HttpClient httpClient; - - public Iterable getEvents(IndexEntry indexEntry) { + public Iterable getEvents(IndexEntry indexEntry) { // TODO: make events pagination in the future return eventRepository.getAllByRelatedTo(indexEntry, PageRequest.of(0, PAGE_SIZE, Sort.by(Sort.Direction.DESC, "created"))); } @RequiredEnabledIndexFeature - public Iterable getEvents(String indexEntryUuid) { + public Iterable getEvents(UUID indexEntryUuid) { return indexEntryService .getEntry(indexEntryUuid) .map(this::getEvents).orElse(Collections.emptyList()); } + @Transactional @RequiredEnabledIndexFeature @SneakyThrows - public Event acceptIncomingPing(PingDTO reqDto, HttpServletRequest request) { + public IndexEvent acceptIncomingPing(PingDTO reqDto, HttpServletRequest request) { final String remoteAddr = utilityService.getRemoteAddr(request); - final IndexSettingsPing pingSettings = indexSettingsService.getOrDefaults().getPing(); + final SettingsIndexPing pingSettings = indexSettingsService.getOrDefaults().getPing(); if (indexSettingsService.isPingDenied(reqDto)) { log.info("Received ping is denied"); @@ -129,8 +117,8 @@ public Event acceptIncomingPing(PingDTO reqDto, HttpServletRequest request) { } final Instant rateLimitSince = Instant.now().minus(pingSettings.getRateLimitDuration()); - final List previousPings = - eventRepository.findAllByIncomingPingExchangeRemoteAddrAndCreatedAfter( + final List previousPings = + eventRepository.findAllByRemoteAddrAndCreatedAtAfter( remoteAddr, rateLimitSince ); if (previousPings.size() > pingSettings.getRateLimitHits()) { @@ -141,14 +129,14 @@ public Event acceptIncomingPing(PingDTO reqDto, HttpServletRequest request) { ); } - final Event event = incomingPingUtils.prepareEvent(reqDto, request, remoteAddr); - eventRepository.save(event); + final IndexEvent event = incomingPingUtils.prepareEvent(reqDto, request, remoteAddr); + eventRepository.saveAndFlush(event); event.execute(); try { final IndexEntry indexEntry = indexEntryService.storeEntry(reqDto); - event.getIncomingPing() - .setNewEntry(indexEntry.getRegistrationTime().equals(indexEntry.getModificationTime())); - event.getIncomingPing().getExchange().getResponse() + event.getPayload().getIncomingPing() + .setNewEntry(indexEntry.getCreatedAt().equals(indexEntry.getUpdatedAt())); + event.getPayload().getIncomingPing().getExchange().getResponse() .setCode(HttpStatus.CREATED.value()); event.setRelatedTo(indexEntry); log.info("Accepted incoming ping as a new event"); @@ -156,21 +144,21 @@ public Event acceptIncomingPing(PingDTO reqDto, HttpServletRequest request) { catch (Exception exception) { final IncorrectPingFormatException nextException = new IncorrectPingFormatException("Could not parse PING: " + exception.getMessage()); - event.getIncomingPing().getExchange().getResponse() + event.getPayload().getIncomingPing().getExchange().getResponse() .setCode(HttpStatus.BAD_REQUEST.value()); - event.getIncomingPing().getExchange().getResponse() + event.getPayload().getIncomingPing().getExchange().getResponse() .setBody(objectMapper.writeValueAsString(nextException.getErrorDTO())); - event.setFinished(Instant.now()); + event.setFinishedAt(Instant.now()); eventRepository.save(event); log.info("Incoming ping has incorrect format: {}", exception.getMessage()); throw nextException; } - event.setFinished(Instant.now()); + event.setFinishedAt(Instant.now()); return eventRepository.save(event); } - private void processMetadataRetrieval(Event event) { - final IndexSettingsRetrieval retrievalSettings = indexSettingsService.getOrDefaults().getRetrieval(); + private void processMetadataRetrieval(IndexEvent event) { + final SettingsIndexRetrieval retrievalSettings = indexSettingsService.getOrDefaults().getRetrieval(); final String clientUrl = event.getRelatedTo().getClientUrl(); if (MetadataRetrievalUtils.shouldRetrieve(event, retrievalSettings.getRateLimitWait())) { indexEntryRepository.save(event.getRelatedTo()); @@ -179,53 +167,53 @@ private void processMetadataRetrieval(Event event) { log.info("Retrieving metadata for {}", clientUrl); MetadataRetrievalUtils.retrieveRepositoryMetadata(event, retrievalSettings.getTimeout()); - final Exchange exchange = event.getMetadataRetrieval().getExchange(); + final Exchange exchange = event.getPayload().getMetadataRetrieval().getExchange(); if (exchange.getState() == ExchangeState.Retrieved) { try { log.info("Parsing metadata for {}", clientUrl); final Optional metadata = MetadataRetrievalUtils.parseRepositoryMetadata(exchange.getResponse().getBody()); if (metadata.isPresent()) { - event.getMetadataRetrieval().setMetadata(metadata.get()); + event.getPayload().getMetadataRetrieval().setMetadata(metadata.get()); event.getRelatedTo().setCurrentMetadata(metadata.get()); - event.getRelatedTo().setState(IndexEntryState.Valid); + event.getRelatedTo().setState(IndexEntryState.VALID); log.info("Storing metadata for {}", clientUrl); indexEntryRepository.save(event.getRelatedTo()); } else { log.info("Repository not found in metadata for {}", clientUrl); - event.getRelatedTo().setState(IndexEntryState.Invalid); - event.getMetadataRetrieval().setError("Repository not found in metadata"); + event.getRelatedTo().setState(IndexEntryState.INVALID); + event.getPayload().getMetadataRetrieval().setError("Repository not found in metadata"); } } catch (Exception exception) { log.info("Cannot parse metadata for {}", clientUrl); - event.getRelatedTo().setState(IndexEntryState.Invalid); - event.getMetadataRetrieval().setError("Cannot parse metadata"); + event.getRelatedTo().setState(IndexEntryState.INVALID); + event.getPayload().getMetadataRetrieval().setError("Cannot parse metadata"); } } else { - event.getRelatedTo().setState(IndexEntryState.Unreachable); + event.getRelatedTo().setState(IndexEntryState.UNREACHABLE); log.info("Cannot retrieve metadata for {}: {}", clientUrl, exchange.getError()); } } else { log.info("Rate limit reached for {} (skipping metadata retrieval)", clientUrl); - event.getMetadataRetrieval().setError("Rate limit reached (skipping)"); + event.getPayload().getMetadataRetrieval().setError("Rate limit reached (skipping)"); } - event.getRelatedTo().setLastRetrievalTime(Instant.now()); + event.getRelatedTo().setCreatedAt(Instant.now()); event.finish(); - final Event newEvent = eventRepository.save(event); + final IndexEvent newEvent = eventRepository.save(event); indexEntryRepository.save(newEvent.getRelatedTo()); webhookService.triggerWebhooks(newEvent); } @Async @RequiredEnabledIndexFeature - public void triggerMetadataRetrieval(Event triggerEvent) { + public void triggerMetadataRetrieval(IndexEvent triggerEvent) { log.info("Initiating metadata retrieval triggered by {}", triggerEvent.getUuid()); - final Iterable events = MetadataRetrievalUtils.prepareEvents(triggerEvent, indexEntryService); - for (Event event : events) { + final Iterable events = MetadataRetrievalUtils.prepareEvents(triggerEvent, indexEntryService); + for (IndexEvent event : events) { log.info("Triggering metadata retrieval for {} as {}", event.getRelatedTo().getClientUrl(), event.getUuid()); try { @@ -240,14 +228,14 @@ public void triggerMetadataRetrieval(Event triggerEvent) { private void resumeUnfinishedEvents() { log.info("Resuming unfinished events"); - for (Event event : eventRepository.getAllByFinishedIsNull()) { + for (IndexEvent event : eventRepository.getAllByFinishedAtIsNull()) { log.info("Resuming event {}", event.getUuid()); try { - if (event.getType() == EventType.MetadataRetrieval) { + if (event.getType() == IndexEventType.METADATA_RETRIEVAL) { processMetadataRetrieval(event); } - else if (event.getType() == EventType.WebhookTrigger) { + else if (event.getType() == IndexEventType.WEBHOOK_TRIGGER) { webhookService.processWebhookTrigger(event); } else { @@ -267,9 +255,9 @@ public void startResumeUnfinishedEvents() { } @RequiredEnabledIndexFeature - public Event acceptAdminTrigger(HttpServletRequest request, PingDTO pingDTO) { + public IndexEvent acceptAdminTrigger(HttpServletRequest request, PingDTO pingDTO) { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - final Event event = + final IndexEvent event = eventMapper.toAdminTriggerEvent(authentication, pingDTO.getClientUrl(), utilityService.getRemoteAddr(request)); final IndexEntry entry = indexEntryService.storeEntry(pingDTO); @@ -279,9 +267,9 @@ public Event acceptAdminTrigger(HttpServletRequest request, PingDTO pingDTO) { } @RequiredEnabledIndexFeature - public Event acceptAdminTriggerAll(HttpServletRequest request) { + public IndexEvent acceptAdminTriggerAll(HttpServletRequest request) { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - final Event event = + final IndexEvent event = eventMapper.toAdminTriggerEvent(authentication, null, utilityService.getRemoteAddr(request)); event.finish(); diff --git a/src/main/java/nl/dtls/fairdatapoint/service/index/event/IncomingPingUtils.java b/src/main/java/nl/dtls/fairdatapoint/service/index/event/IncomingPingUtils.java index ee23453f1..19a7c07d7 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/index/event/IncomingPingUtils.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/index/event/IncomingPingUtils.java @@ -25,25 +25,25 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.index.ping.PingDTO; -import nl.dtls.fairdatapoint.entity.index.event.Event; -import nl.dtls.fairdatapoint.entity.index.event.IncomingPing; +import nl.dtls.fairdatapoint.entity.index.event.IndexEvent; +import nl.dtls.fairdatapoint.entity.index.event.payload.IncomingPing; import nl.dtls.fairdatapoint.entity.index.http.Exchange; import nl.dtls.fairdatapoint.entity.index.http.ExchangeDirection; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.*; @Service +@RequiredArgsConstructor public class IncomingPingUtils { private static final Integer VERSION = 1; - @Autowired - private ObjectMapper objectMapper; + private final ObjectMapper objectMapper; - public Event prepareEvent(PingDTO reqDto, HttpServletRequest request, String remoteAddr) { + public IndexEvent prepareEvent(PingDTO reqDto, HttpServletRequest request, String remoteAddr) { final IncomingPing incomingPing = new IncomingPing(); final Exchange ex = new Exchange(ExchangeDirection.INCOMING, remoteAddr); incomingPing.setExchange(ex); @@ -57,7 +57,7 @@ public Event prepareEvent(PingDTO reqDto, HttpServletRequest request, String rem ex.getRequest().setBody(null); } - return new Event(VERSION, incomingPing); + return new IndexEvent(VERSION, incomingPing); } private Map> getHeaders(HttpServletRequest request) { diff --git a/src/main/java/nl/dtls/fairdatapoint/service/index/event/MetadataRetrievalUtils.java b/src/main/java/nl/dtls/fairdatapoint/service/index/event/MetadataRetrievalUtils.java index 5fce7c74d..4699c704b 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/index/event/MetadataRetrievalUtils.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/index/event/MetadataRetrievalUtils.java @@ -23,9 +23,9 @@ package nl.dtls.fairdatapoint.service.index.event; import nl.dtls.fairdatapoint.entity.index.entry.RepositoryMetadata; -import nl.dtls.fairdatapoint.entity.index.event.Event; -import nl.dtls.fairdatapoint.entity.index.event.EventType; -import nl.dtls.fairdatapoint.entity.index.event.MetadataRetrieval; +import nl.dtls.fairdatapoint.entity.index.event.IndexEvent; +import nl.dtls.fairdatapoint.entity.index.event.IndexEventType; +import nl.dtls.fairdatapoint.entity.index.event.payload.MetadataRetrieval; import nl.dtls.fairdatapoint.entity.index.http.Exchange; import nl.dtls.fairdatapoint.entity.index.http.ExchangeDirection; import nl.dtls.fairdatapoint.entity.index.http.ExchangeState; @@ -62,7 +62,7 @@ public class MetadataRetrievalUtils { - private static final EventType EVENT_TYPE = EventType.MetadataRetrieval; + private static final IndexEventType EVENT_TYPE = IndexEventType.METADATA_RETRIEVAL; private static final Integer VERSION = 1; @@ -84,50 +84,50 @@ public class MetadataRetrievalUtils { .followRedirects(HttpClient.Redirect.ALWAYS) .build(); - public static boolean shouldRetrieve(Event triggerEvent, Duration rateLimitWait) { + public static boolean shouldRetrieve(IndexEvent triggerEvent, Duration rateLimitWait) { if (triggerEvent.getRelatedTo() == null) { return false; } - final Instant lastRetrieval = triggerEvent.getRelatedTo().getLastRetrievalTime(); + final Instant lastRetrieval = triggerEvent.getRelatedTo().getLastRetrievalAt(); if (lastRetrieval == null) { return true; } return Duration.between(lastRetrieval, Instant.now()).compareTo(rateLimitWait) > 0; } - public static Iterable prepareEvents( - Event triggerEvent, IndexEntryService indexEntryService + public static Iterable prepareEvents( + IndexEvent triggerEvent, IndexEntryService indexEntryService ) { - final ArrayList events = new ArrayList<>(); - if (triggerEvent.getType() == EventType.IncomingPing) { - events.add(new Event(VERSION, triggerEvent, + final ArrayList events = new ArrayList<>(); + if (triggerEvent.getType() == IndexEventType.INCOMING_PING) { + events.add(new IndexEvent(VERSION, triggerEvent, triggerEvent.getRelatedTo(), new MetadataRetrieval())); } - else if (triggerEvent.getType() == EventType.AdminTrigger) { - if (triggerEvent.getAdminTrigger().getClientUrl() == null) { + else if (triggerEvent.getType() == IndexEventType.ADMIN_TRIGGER) { + if (triggerEvent.getPayload().getAdminTrigger().getClientUrl() == null) { indexEntryService.getAllEntries().forEach( entry -> { events.add( - new Event(VERSION, triggerEvent, + new IndexEvent(VERSION, triggerEvent, entry, new MetadataRetrieval()) ); } ); } else { - events.add(new Event(VERSION, triggerEvent, + events.add(new IndexEvent(VERSION, triggerEvent, triggerEvent.getRelatedTo(), new MetadataRetrieval())); } } return events; } - public static void retrieveRepositoryMetadata(Event event, Duration timeout) { + public static void retrieveRepositoryMetadata(IndexEvent event, Duration timeout) { if (event.getType() != EVENT_TYPE) { throw new IllegalArgumentException("Invalid event type"); } final Exchange ex = new Exchange(ExchangeDirection.OUTGOING); - event.getMetadataRetrieval().setExchange(ex); + event.getPayload().getMetadataRetrieval().setExchange(ex); try { final HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(event.getRelatedTo().getClientUrl())) diff --git a/src/main/java/nl/dtls/fairdatapoint/service/index/harvester/HarvesterService.java b/src/main/java/nl/dtls/fairdatapoint/service/index/harvester/HarvesterService.java index 7460d4fcd..08975b3d4 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/index/harvester/HarvesterService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/index/harvester/HarvesterService.java @@ -22,6 +22,7 @@ */ package nl.dtls.fairdatapoint.service.index.harvester; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import nl.dtls.fairdatapoint.database.rdf.repository.RepositoryMode; import nl.dtls.fairdatapoint.database.rdf.repository.exception.MetadataRepositoryException; @@ -33,7 +34,6 @@ import org.eclipse.rdf4j.model.vocabulary.LDP; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.rio.RDFFormat; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.*; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; @@ -54,15 +54,14 @@ @Slf4j @Service +@RequiredArgsConstructor public class HarvesterService { private static final String DEFAULT_NAVIGATION_SHACL = "defaultNavigationShacl.ttl"; - @Autowired - private GenericMetadataRepository genericMetadataRepository; + private final GenericMetadataRepository genericMetadataRepository; - @Autowired - private RestTemplate restTemplate; + private final RestTemplate restTemplate; public void deleteHarvestedData(String clientUrl) throws MetadataRepositoryException { genericMetadataRepository.remove(i(clientUrl), RepositoryMode.MAIN); diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/settings/SettingsMigration.java b/src/main/java/nl/dtls/fairdatapoint/service/index/settings/IndexSettingsDefaults.java similarity index 56% rename from src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/settings/SettingsMigration.java rename to src/main/java/nl/dtls/fairdatapoint/service/index/settings/IndexSettingsDefaults.java index 06d8a7115..1d999cd8d 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/migration/development/settings/SettingsMigration.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/index/settings/IndexSettingsDefaults.java @@ -20,21 +20,28 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.database.mongo.migration.development.settings; +package nl.dtls.fairdatapoint.service.index.settings; -import nl.dtls.fairdatapoint.database.mongo.migration.development.settings.data.SettingsFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.SettingsRepository; -import org.springframework.beans.factory.annotation.Autowired; +import lombok.RequiredArgsConstructor; +import nl.dtls.fairdatapoint.config.properties.InstanceProperties; +import nl.dtls.fairdatapoint.entity.index.settings.IndexSettings; +import nl.dtls.fairdatapoint.entity.index.settings.SettingsIndexPing; +import nl.dtls.fairdatapoint.entity.index.settings.SettingsIndexRetrieval; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.springframework.stereotype.Component; @Component -public class SettingsMigration { +@RequiredArgsConstructor +public class IndexSettingsDefaults { - @Autowired - private SettingsRepository settingsRepository; + private final InstanceProperties instanceProperties; - public void runMigration() { - settingsRepository.deleteAll(); - settingsRepository.save(SettingsFixtures.settings()); + public IndexSettings getDefaults() { + final IndexSettings indexSettings = new IndexSettings(); + indexSettings.setUuid(KnownUUIDs.SETTINGS_UUID); + indexSettings.setPing(SettingsIndexPing.getDefault()); + indexSettings.setRetrieval(SettingsIndexRetrieval.getDefault()); + indexSettings.setAutoPermit(instanceProperties.isIndexAutoPermit()); + return indexSettings; } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/index/settings/IndexSettingsMapper.java b/src/main/java/nl/dtls/fairdatapoint/service/index/settings/IndexSettingsMapper.java index adb680da6..a803fcad3 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/index/settings/IndexSettingsMapper.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/index/settings/IndexSettingsMapper.java @@ -27,16 +27,17 @@ import nl.dtls.fairdatapoint.api.dto.index.settings.IndexSettingsRetrievalDTO; import nl.dtls.fairdatapoint.api.dto.index.settings.IndexSettingsUpdateDTO; import nl.dtls.fairdatapoint.entity.index.settings.IndexSettings; -import nl.dtls.fairdatapoint.entity.index.settings.IndexSettingsPing; -import nl.dtls.fairdatapoint.entity.index.settings.IndexSettingsRetrieval; +import nl.dtls.fairdatapoint.entity.index.settings.SettingsIndexPing; +import nl.dtls.fairdatapoint.entity.index.settings.SettingsIndexRetrieval; import org.springframework.stereotype.Service; import java.time.Duration; +import java.time.Instant; @Service public class IndexSettingsMapper { - private IndexSettingsPingDTO toPingDTO(IndexSettingsPing indexSettingsPing) { + private IndexSettingsPingDTO toPingDTO(SettingsIndexPing indexSettingsPing) { return new IndexSettingsPingDTO( indexSettingsPing.getValidDuration().toString(), indexSettingsPing.getRateLimitDuration().toString(), @@ -46,7 +47,7 @@ private IndexSettingsPingDTO toPingDTO(IndexSettingsPing indexSettingsPing) { } private IndexSettingsRetrievalDTO toRetrievalDTO( - IndexSettingsRetrieval indexSettingsRetrieval + SettingsIndexRetrieval indexSettingsRetrieval ) { return new IndexSettingsRetrievalDTO( indexSettingsRetrieval.getRateLimitWait().toString(), @@ -59,7 +60,7 @@ public IndexSettingsDTO toDTO(IndexSettings indexSettings, IndexSettings default toRetrievalDTO(indexSettings.getRetrieval()), toPingDTO(indexSettings.getPing()), indexSettings.getAutoPermit(), - indexSettings.equals(defaults) + indexSettings.isSameAs(defaults) ); } @@ -71,7 +72,7 @@ public IndexSettingsUpdateDTO toUpdateDTO(IndexSettings indexSettings) { ); } - private IndexSettingsPing fromDTO(IndexSettingsPingDTO dto, IndexSettingsPing ping) { + private SettingsIndexPing fromDTO(IndexSettingsPingDTO dto, SettingsIndexPing ping) { return ping .toBuilder() @@ -82,8 +83,8 @@ private IndexSettingsPing fromDTO(IndexSettingsPingDTO dto, IndexSettingsPing pi .build(); } - private IndexSettingsRetrieval fromDTO( - IndexSettingsRetrievalDTO dto, IndexSettingsRetrieval retrieval + private SettingsIndexRetrieval fromDTO( + IndexSettingsRetrievalDTO dto, SettingsIndexRetrieval retrieval ) { return retrieval @@ -97,9 +98,15 @@ public IndexSettings fromUpdateDTO(IndexSettingsUpdateDTO dto, IndexSettings ind return indexSettings .toBuilder() - .ping(fromDTO(dto.getPing(), indexSettings.getPing())) - .retrieval(fromDTO(dto.getRetrieval(), indexSettings.getRetrieval())) + .pingValidDuration(dto.getPing().getValidDuration()) + .pingRateLimitDuration(dto.getPing().getRateLimitDuration()) + .pingValidDuration(dto.getPing().getValidDuration()) + .pingDenyList(dto.getPing().getDenyList()) + .pingRateLimitHits(dto.getPing().getRateLimitHits()) + .retrievalRateLimitWait(dto.getRetrieval().getRateLimitWait()) + .retrievalTimeout(dto.getRetrieval().getTimeout()) .autoPermit(dto.getAutoPermit()) + .updatedAt(Instant.now()) .build(); } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/index/settings/IndexSettingsService.java b/src/main/java/nl/dtls/fairdatapoint/service/index/settings/IndexSettingsService.java index 1cb93be00..212c3a24b 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/index/settings/IndexSettingsService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/index/settings/IndexSettingsService.java @@ -22,33 +22,29 @@ */ package nl.dtls.fairdatapoint.service.index.settings; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import nl.dtls.fairdatapoint.api.dto.index.ping.PingDTO; import nl.dtls.fairdatapoint.api.dto.index.settings.IndexSettingsDTO; import nl.dtls.fairdatapoint.api.dto.index.settings.IndexSettingsUpdateDTO; -import nl.dtls.fairdatapoint.config.properties.InstanceProperties; -import nl.dtls.fairdatapoint.database.mongo.repository.IndexSettingsRepository; +import nl.dtls.fairdatapoint.database.db.repository.IndexSettingsRepository; import nl.dtls.fairdatapoint.entity.index.settings.IndexSettings; -import nl.dtls.fairdatapoint.entity.index.settings.IndexSettingsPing; -import nl.dtls.fairdatapoint.entity.index.settings.IndexSettingsRetrieval; import nl.dtls.fairdatapoint.service.index.common.RequiredEnabledIndexFeature; -import org.springframework.beans.factory.annotation.Autowired; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.springframework.stereotype.Service; import java.util.regex.Pattern; -@Service @Slf4j +@Service +@RequiredArgsConstructor public class IndexSettingsService { - @Autowired - private IndexSettingsRepository repository; + private final IndexSettingsRepository repository; - @Autowired - private IndexSettingsMapper mapper; + private final IndexSettingsMapper mapper; - @Autowired - private InstanceProperties instanceProperties; + private final IndexSettingsDefaults defaults; @RequiredEnabledIndexFeature public boolean isPingDenied(PingDTO ping) { @@ -62,33 +58,24 @@ public boolean isPingDenied(PingDTO ping) { @RequiredEnabledIndexFeature public IndexSettings getOrDefaults() { - return repository.findFirstBy().orElse(getDefaults()); + return repository.findByUuid(KnownUUIDs.SETTINGS_UUID).orElse(defaults.getDefaults()); } @RequiredEnabledIndexFeature public IndexSettingsDTO getCurrentSettings() { - return mapper.toDTO(getOrDefaults(), getDefaults()); - } - - @RequiredEnabledIndexFeature - public IndexSettings getDefaults() { - final IndexSettings settings = new IndexSettings(); - settings.setPing(IndexSettingsPing.getDefault()); - settings.setRetrieval(IndexSettingsRetrieval.getDefault()); - settings.setAutoPermit(instanceProperties.isIndexAutoPermit()); - return settings; + return mapper.toDTO(getOrDefaults(), defaults.getDefaults()); } @RequiredEnabledIndexFeature public IndexSettingsDTO updateSettings(IndexSettingsUpdateDTO dto) { return mapper.toDTO( repository.save(mapper.fromUpdateDTO(dto, getOrDefaults())), - getDefaults() + defaults.getDefaults() ); } @RequiredEnabledIndexFeature public IndexSettingsDTO resetSettings() { - return updateSettings(mapper.toUpdateDTO(getDefaults())); + return updateSettings(mapper.toUpdateDTO(defaults.getDefaults())); } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/index/webhook/WebhookMapper.java b/src/main/java/nl/dtls/fairdatapoint/service/index/webhook/WebhookMapper.java index bebb4d032..64f012866 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/index/webhook/WebhookMapper.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/index/webhook/WebhookMapper.java @@ -23,11 +23,11 @@ package nl.dtls.fairdatapoint.service.index.webhook; import nl.dtls.fairdatapoint.api.dto.index.webhook.WebhookPayloadDTO; -import nl.dtls.fairdatapoint.entity.index.event.Event; -import nl.dtls.fairdatapoint.entity.index.event.WebhookPing; -import nl.dtls.fairdatapoint.entity.index.event.WebhookTrigger; -import nl.dtls.fairdatapoint.entity.index.webhook.Webhook; -import nl.dtls.fairdatapoint.entity.index.webhook.WebhookEvent; +import nl.dtls.fairdatapoint.entity.index.event.IndexEvent; +import nl.dtls.fairdatapoint.entity.index.event.payload.WebhookPing; +import nl.dtls.fairdatapoint.entity.index.event.payload.WebhookTrigger; +import nl.dtls.fairdatapoint.entity.index.webhook.IndexWebhook; +import nl.dtls.fairdatapoint.entity.index.webhook.IndexWebhookEvent; import org.springframework.security.core.Authentication; import org.springframework.stereotype.Service; @@ -39,28 +39,28 @@ public class WebhookMapper { private static final Integer VERSION = 1; - public Event toTriggerEvent(Webhook webhook, WebhookEvent webhookEvent, Event triggerEvent) { + public IndexEvent toTriggerEvent(IndexWebhook webhook, IndexWebhookEvent webhookEvent, IndexEvent triggerEvent) { final WebhookTrigger webhookTrigger = new WebhookTrigger(); webhookTrigger.setWebhook(webhook); webhookTrigger.setMatchedEvent(webhookEvent); - return new Event(VERSION, webhookTrigger, triggerEvent); + return new IndexEvent(VERSION, webhookTrigger, triggerEvent); } - public Event toPingEvent( + public IndexEvent toPingEvent( Authentication authentication, UUID webhookUuid, String remoteAddr ) { final WebhookPing webhookPing = new WebhookPing(); webhookPing.setWebhookUuid(webhookUuid); webhookPing.setRemoteAddr(remoteAddr); webhookPing.setTokenName(authentication.getName()); - return new Event(VERSION, webhookPing); + return new IndexEvent(VERSION, webhookPing); } - public WebhookPayloadDTO toWebhookPayloadDTO(Event event) { + public WebhookPayloadDTO toWebhookPayloadDTO(IndexEvent event) { final WebhookPayloadDTO webhookPayload = new WebhookPayloadDTO(); - webhookPayload.setEvent(event.getWebhookTrigger().getMatchedEvent()); + webhookPayload.setEvent(event.getPayload().getWebhookTrigger().getMatchedEvent()); webhookPayload.setClientUrl(event.getRelatedTo().getClientUrl()); - webhookPayload.setSecret(event.getWebhookTrigger().getWebhook().getSecret()); + webhookPayload.setSecret(event.getPayload().getWebhookTrigger().getWebhook().getSecret()); webhookPayload.setUuid(event.getUuid().toString()); webhookPayload.setTimestamp(Instant.now().toString()); return webhookPayload; diff --git a/src/main/java/nl/dtls/fairdatapoint/service/index/webhook/WebhookService.java b/src/main/java/nl/dtls/fairdatapoint/service/index/webhook/WebhookService.java index 4a6001b58..ae99f7826 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/index/webhook/WebhookService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/index/webhook/WebhookService.java @@ -25,19 +25,19 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import nl.dtls.fairdatapoint.api.dto.index.webhook.WebhookPayloadDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.EventRepository; -import nl.dtls.fairdatapoint.database.mongo.repository.WebhookRepository; +import nl.dtls.fairdatapoint.database.db.repository.IndexEventRepository; +import nl.dtls.fairdatapoint.database.db.repository.IndexWebhookRepository; import nl.dtls.fairdatapoint.entity.exception.ResourceNotFoundException; -import nl.dtls.fairdatapoint.entity.index.event.Event; -import nl.dtls.fairdatapoint.entity.index.settings.IndexSettingsRetrieval; -import nl.dtls.fairdatapoint.entity.index.webhook.Webhook; -import nl.dtls.fairdatapoint.entity.index.webhook.WebhookEvent; +import nl.dtls.fairdatapoint.entity.index.event.IndexEvent; +import nl.dtls.fairdatapoint.entity.index.settings.SettingsIndexRetrieval; +import nl.dtls.fairdatapoint.entity.index.webhook.IndexWebhook; +import nl.dtls.fairdatapoint.entity.index.webhook.IndexWebhookEvent; import nl.dtls.fairdatapoint.service.UtilityService; import nl.dtls.fairdatapoint.service.index.common.RequiredEnabledIndexFeature; import nl.dtls.fairdatapoint.service.index.settings.IndexSettingsService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; @@ -49,31 +49,26 @@ @Slf4j @Service +@RequiredArgsConstructor public class WebhookService { private static final String SECRET_PLACEHOLDER = "*** HIDDEN ***"; - @Autowired - private WebhookMapper webhookMapper; + private final WebhookMapper webhookMapper; - @Autowired - private ObjectMapper objectMapper; + private final ObjectMapper objectMapper; - @Autowired - private WebhookRepository webhookRepository; + private final IndexWebhookRepository webhookRepository; - @Autowired - private EventRepository eventRepository; + private final IndexEventRepository eventRepository; - @Autowired - private IndexSettingsService indexSettingsService; + private final IndexSettingsService indexSettingsService; - @Autowired - private UtilityService utilityService; + private final UtilityService utilityService; @RequiredEnabledIndexFeature - public void processWebhookTrigger(Event event) { - final IndexSettingsRetrieval retrievalSettings = + public void processWebhookTrigger(IndexEvent event) { + final SettingsIndexRetrieval retrievalSettings = indexSettingsService.getOrDefaults().getRetrieval(); event.execute(); eventRepository.save(event); @@ -102,14 +97,14 @@ public void processWebhookTrigger(Event event) { @Async @RequiredEnabledIndexFeature - public void triggerWebhook(Webhook webhook, WebhookEvent webhookEvent, Event triggerEvent) { - final Event event = webhookMapper.toTriggerEvent(webhook, webhookEvent, triggerEvent); + public void triggerWebhook(IndexWebhook webhook, IndexWebhookEvent webhookEvent, IndexEvent triggerEvent) { + final IndexEvent event = webhookMapper.toTriggerEvent(webhook, webhookEvent, triggerEvent); processWebhookTrigger(event); } @Async @RequiredEnabledIndexFeature - public void triggerWebhooks(WebhookEvent webhookEvent, Event triggerEvent) { + public void triggerWebhooks(IndexWebhookEvent webhookEvent, IndexEvent triggerEvent) { log.info("Triggered webhook event {} by event {}", webhookEvent, triggerEvent.getUuid()); WebhookUtils .filterMatching(webhookRepository.findAll(), webhookEvent, triggerEvent) @@ -118,30 +113,30 @@ public void triggerWebhooks(WebhookEvent webhookEvent, Event triggerEvent) { @Async @RequiredEnabledIndexFeature - public void triggerWebhooks(Event triggerEvent) { + public void triggerWebhooks(IndexEvent triggerEvent) { switch (triggerEvent.getType()) { - case AdminTrigger: - triggerWebhooks(WebhookEvent.AdminTrigger, triggerEvent); + case ADMIN_TRIGGER: + triggerWebhooks(IndexWebhookEvent.ADMIN_TRIGGER, triggerEvent); break; - case IncomingPing: - triggerWebhooks(WebhookEvent.IncomingPing, triggerEvent); - if (triggerEvent.getIncomingPing().getNewEntry()) { - triggerWebhooks(WebhookEvent.NewEntry, triggerEvent); + case INCOMING_PING: + triggerWebhooks(IndexWebhookEvent.INCOMING_PING, triggerEvent); + if (triggerEvent.getPayload().getIncomingPing().getNewEntry()) { + triggerWebhooks(IndexWebhookEvent.NEW_ENTRY, triggerEvent); } break; - case MetadataRetrieval: + case METADATA_RETRIEVAL: switch (triggerEvent.getRelatedTo().getState()) { - case Valid -> triggerWebhooks(WebhookEvent.EntryValid, triggerEvent); - case Invalid -> triggerWebhooks(WebhookEvent.EntryInvalid, triggerEvent); - case Unreachable -> triggerWebhooks( - WebhookEvent.EntryUnreachable, triggerEvent + case VALID -> triggerWebhooks(IndexWebhookEvent.ENTRY_VALID, triggerEvent); + case INVALID -> triggerWebhooks(IndexWebhookEvent.ENTRY_INVALID, triggerEvent); + case UNREACHABLE -> triggerWebhooks( + IndexWebhookEvent.ENTRY_UNREACHABLE, triggerEvent ); default -> log.warn("Invalid state of MetadataRetrieval: {}", triggerEvent.getRelatedTo().getState()); } break; - case WebhookPing: - triggerWebhooks(WebhookEvent.WebhookPing, triggerEvent); + case WEBHOOK_PING: + triggerWebhooks(IndexWebhookEvent.WEBHOOK_PING, triggerEvent); break; default: log.warn("Invalid event type for webhook trigger: {}", triggerEvent.getType()); @@ -149,11 +144,11 @@ public void triggerWebhooks(Event triggerEvent) { } @RequiredEnabledIndexFeature - public Event handleWebhookPing(HttpServletRequest request, UUID webhookUuid) { + public IndexEvent handleWebhookPing(HttpServletRequest request, UUID webhookUuid) { final Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); - final Optional webhook = webhookRepository.findByUuid(webhookUuid); - final Event event = eventRepository.save( + final Optional webhook = webhookRepository.findByUuid(webhookUuid); + final IndexEvent event = eventRepository.save( webhookMapper.toPingEvent( authentication, webhookUuid, diff --git a/src/main/java/nl/dtls/fairdatapoint/service/index/webhook/WebhookUtils.java b/src/main/java/nl/dtls/fairdatapoint/service/index/webhook/WebhookUtils.java index cb44f4d66..d4ee7e931 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/index/webhook/WebhookUtils.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/index/webhook/WebhookUtils.java @@ -22,12 +22,12 @@ */ package nl.dtls.fairdatapoint.service.index.webhook; -import nl.dtls.fairdatapoint.entity.index.event.Event; +import nl.dtls.fairdatapoint.entity.index.event.IndexEvent; import nl.dtls.fairdatapoint.entity.index.http.Exchange; import nl.dtls.fairdatapoint.entity.index.http.ExchangeDirection; import nl.dtls.fairdatapoint.entity.index.http.ExchangeState; -import nl.dtls.fairdatapoint.entity.index.webhook.Webhook; -import nl.dtls.fairdatapoint.entity.index.webhook.WebhookEvent; +import nl.dtls.fairdatapoint.entity.index.webhook.IndexWebhook; +import nl.dtls.fairdatapoint.entity.index.webhook.IndexWebhookEvent; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; @@ -52,20 +52,20 @@ public class WebhookUtils { .build(); private static boolean webhookMatches( - Webhook webhook, WebhookEvent webhookEvent, Event triggerEvent + IndexWebhook webhook, IndexWebhookEvent webhookEvent, IndexEvent triggerEvent ) { - final boolean matchEvent = webhook.isAllEvents() + final boolean matchEvent = webhook.getAllEvents() || webhook.getEvents().contains(webhookEvent); final boolean matchEntry = - webhook.isAllEntries() + webhook.getAllEntries() || triggerEvent.getRelatedTo() == null || webhook.getEntries().contains( triggerEvent.getRelatedTo().getClientUrl()); - return matchEvent && matchEntry && webhook.isEnabled(); + return matchEvent && matchEntry && webhook.getEnabled(); } - public static Stream filterMatching(List webhooks, WebhookEvent webhookEvent, - Event triggerEvent) { + public static Stream filterMatching(List webhooks, IndexWebhookEvent webhookEvent, + IndexEvent triggerEvent) { return webhooks .parallelStream() .filter(webhook -> { @@ -81,13 +81,13 @@ public static String computeHashSignature(String value) throws NoSuchAlgorithmEx } public static void postWebhook( - Event event, Duration timeout, String payload, String signature + IndexEvent event, Duration timeout, String payload, String signature ) { final Exchange ex = new Exchange(ExchangeDirection.OUTGOING); - event.getWebhookTrigger().setExchange(ex); + event.getPayload().getWebhookTrigger().setExchange(ex); try { final HttpRequest request = HttpRequest.newBuilder() - .uri(URI.create(event.getWebhookTrigger().getWebhook().getPayloadUrl())) + .uri(URI.create(event.getPayload().getWebhookTrigger().getWebhook().getPayloadUrl())) .timeout(timeout) .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON.toString()) .header("X-Signature", signature) diff --git a/src/main/java/nl/dtls/fairdatapoint/service/jwt/JwtService.java b/src/main/java/nl/dtls/fairdatapoint/service/jwt/JwtService.java index 970c286e7..ac4d26754 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/jwt/JwtService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/jwt/JwtService.java @@ -25,18 +25,17 @@ import io.jsonwebtoken.*; import jakarta.annotation.PostConstruct; import nl.dtls.fairdatapoint.api.dto.auth.AuthDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.UserRepository; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; import nl.dtls.fairdatapoint.entity.exception.UnauthorizedException; -import nl.dtls.fairdatapoint.entity.user.User; -import nl.dtls.fairdatapoint.service.security.MongoAuthenticationService; -import org.springframework.beans.factory.annotation.Autowired; +import nl.dtls.fairdatapoint.entity.user.UserAccount; +import nl.dtls.fairdatapoint.service.security.AuthenticationService; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Lazy; import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UsernameNotFoundException; -import org.springframework.stereotype.Component; +import org.springframework.stereotype.Service; import javax.crypto.spec.SecretKeySpec; import java.security.Key; @@ -44,7 +43,7 @@ import java.util.Date; import java.util.Optional; -@Component +@Service public class JwtService { private static final Long DAY_MS = 24 * 60 * 60 * 1000L; @@ -55,20 +54,24 @@ public class JwtService { @Value("${security.jwt.token.expiration:14}") private long expiration; - @Autowired - private UserRepository userRepository; + private final UserAccountRepository userAccountRepository; @Lazy - @Autowired - private AuthenticationManager authenticationManager; + private final AuthenticationManager authenticationManager; - @Autowired - private MongoAuthenticationService mongoAuthenticationService; + private final AuthenticationService authenticationService; private JwtParser parser; private Key key; + public JwtService(UserAccountRepository userAccountRepository, AuthenticationManager authenticationManager, + AuthenticationService authenticationService) { + this.userAccountRepository = userAccountRepository; + this.authenticationManager = authenticationManager; + this.authenticationService = authenticationService; + } + @PostConstruct protected void init() { secretKey = Base64.getEncoder().encodeToString(secretKey.getBytes()); @@ -77,7 +80,7 @@ protected void init() { } public String createToken(AuthDTO authDTO) { - final Optional user = userRepository.findByEmail(authDTO.getEmail()); + final Optional user = userAccountRepository.findByEmail(authDTO.getEmail()); if (user.isEmpty()) { throw new UsernameNotFoundException("User not found"); } @@ -90,7 +93,7 @@ public String createToken(AuthDTO authDTO) { } public Authentication getAuthentication(String token) { - return mongoAuthenticationService.getAuthentication(getUserUuid(token)); + return authenticationService.getAuthentication(getUserUuid(token)); } public String getUserUuid(String token) { @@ -107,8 +110,8 @@ public boolean validateToken(String token) { } } - private String buildToken(User user) { - final Claims claims = Jwts.claims().subject(user.getUuid()).build(); + private String buildToken(UserAccount user) { + final Claims claims = Jwts.claims().subject(user.getUuid().toString()).build(); final Date now = new Date(); final Date validity = new Date(now.getTime() + (expiration * DAY_MS)); return Jwts.builder() diff --git a/src/main/java/nl/dtls/fairdatapoint/service/member/MemberMapper.java b/src/main/java/nl/dtls/fairdatapoint/service/member/MemberMapper.java index 1592324b8..ca1d7b5f7 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/member/MemberMapper.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/member/MemberMapper.java @@ -22,24 +22,23 @@ */ package nl.dtls.fairdatapoint.service.member; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.member.MemberDTO; import nl.dtls.fairdatapoint.entity.membership.Membership; -import nl.dtls.fairdatapoint.entity.user.User; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import nl.dtls.fairdatapoint.service.membership.MembershipMapper; import nl.dtls.fairdatapoint.service.user.UserMapper; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Service; +import org.springframework.stereotype.Component; -@Service +@Component +@RequiredArgsConstructor public class MemberMapper { - @Autowired - private MembershipMapper membershipMapper; + private final MembershipMapper membershipMapper; - @Autowired - private UserMapper userMapper; + private final UserMapper userMapper; - public MemberDTO toDTO(User user, Membership membership) { + public MemberDTO toDTO(UserAccount user, Membership membership) { return new MemberDTO( userMapper.toSimpleDTO(user), diff --git a/src/main/java/nl/dtls/fairdatapoint/service/member/MemberService.java b/src/main/java/nl/dtls/fairdatapoint/service/member/MemberService.java index acfd17341..413f36809 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/member/MemberService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/member/MemberService.java @@ -22,58 +22,52 @@ */ package nl.dtls.fairdatapoint.service.member; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.member.MemberDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.MembershipRepository; -import nl.dtls.fairdatapoint.database.mongo.repository.UserRepository; +import nl.dtls.fairdatapoint.database.db.repository.MembershipRepository; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; import nl.dtls.fairdatapoint.entity.exception.ValidationException; import nl.dtls.fairdatapoint.entity.membership.Membership; import nl.dtls.fairdatapoint.entity.membership.MembershipPermission; -import nl.dtls.fairdatapoint.entity.user.User; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import nl.dtls.fairdatapoint.entity.user.UserRole; import nl.dtls.fairdatapoint.service.membership.PermissionService; import nl.dtls.fairdatapoint.service.user.CurrentUserService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.security.acls.dao.AclRepository; import org.springframework.security.acls.domain.BasePermission; -import org.springframework.security.acls.domain.MongoAcl; import org.springframework.security.acls.domain.ObjectIdentityImpl; import org.springframework.security.acls.domain.PrincipalSid; import org.springframework.security.acls.model.*; -import org.springframework.security.acls.mongodb.MongoDBMutableAclService; import org.springframework.stereotype.Service; import java.util.List; import java.util.Optional; +import java.util.UUID; import java.util.stream.Collectors; @Service +@RequiredArgsConstructor public class MemberService { - @Autowired - private MongoDBMutableAclService aclService; + private final MutableAclService aclService; - @Autowired - private MembershipRepository membershipRepository; + private final MembershipRepository membershipRepository; - @Autowired - private UserRepository userRepository; + private final UserAccountRepository userAccountRepository; - @Autowired - private CurrentUserService currentUserService; + private final CurrentUserService currentUserService; - @Autowired - private PermissionService permissionService; + private final PermissionService permissionService; - @Autowired - private MemberMapper memberMapper; + private final MemberMapper memberMapper; - @Autowired - private AclRepository aclRepository; + private final AclCache aclCache; - @Autowired - private AclCache aclCache; + private final EntityManager entityManager; + @Transactional @PreAuthorize("hasPermission(#entityId, #entityType.getName(), 'WRITE') or hasRole('ADMIN')") public List getMembers(String entityId, Class entityType) { final MutableAcl acl = retrieveAcl(entityId, entityType); @@ -85,37 +79,39 @@ public List getMembers(String entityId, Class entityType) { .stream() .map(entry -> { final Membership membership = deriveMembership(entry.getValue()); - final User user = userRepository.findByUuid( - ((PrincipalSid) entry.getKey()).getPrincipal() + final UserAccount user = userAccountRepository.findByUuid( + UUID.fromString(((PrincipalSid) entry.getKey()).getPrincipal()) ).get(); return memberMapper.toDTO(user, membership); }) .toList(); } + @Transactional public Optional getMemberForCurrentUser(String entityId, Class entityType) { final MutableAcl acl = retrieveAcl(entityId, entityType); - final Optional oUser = currentUserService.getCurrentUser(); + final Optional oUser = currentUserService.getCurrentUser(); if (oUser.isEmpty()) { return Optional.empty(); } - final User user = oUser.get(); + final UserAccount user = oUser.get(); final List permissions = acl.getEntries() .stream() - .filter(ace -> ace.getSid().equals(new PrincipalSid(user.getUuid()))) + .filter(ace -> ace.getSid().equals(new PrincipalSid(user.getUuid().toString()))) .map(AccessControlEntry::getPermission) - .collect(Collectors.toList()); + .toList(); - if (permissions.size() > 0) { + if (!permissions.isEmpty()) { final Membership membership = deriveMembership(permissions); return Optional.of(memberMapper.toDTO(user, membership)); } return Optional.empty(); } + @Transactional @PreAuthorize("hasPermission(#entityId, #entityType.getName(), 'WRITE') or hasRole('ADMIN')") - public MemberDTO createOrUpdateMember(String entityId, Class entityType, String userUuid, - String membershipUuid) { + public MemberDTO createOrUpdateMember(String entityId, Class entityType, UUID userUuid, + UUID membershipUuid) { // Get membership final Optional oMembership = membershipRepository.findByUuid(membershipUuid); if (oMembership.isEmpty()) { @@ -124,11 +120,11 @@ public MemberDTO createOrUpdateMember(String entityId, Class entityType, final Membership membership = oMembership.get(); // Get user - final Optional oUser = userRepository.findByUuid(userUuid); + final Optional oUser = userAccountRepository.findByUuid(userUuid); if (oUser.isEmpty()) { throw new ValidationException("User doesn't exist"); } - final User user = oUser.get(); + final UserAccount user = oUser.get(); // Get ACL final MutableAcl acl = retrieveAcl(entityId, entityType); @@ -148,15 +144,19 @@ public MemberDTO createOrUpdateMember(String entityId, Class entityType, return memberMapper.toDTO(user, membership); } - public void createOwner(String entityId, Class entityType, String userUuid) { + @Transactional + public void createOwner(String entityId, Class entityType, UUID userUuid) { createPermission(entityId, entityType, userUuid, BasePermission.WRITE); createPermission(entityId, entityType, userUuid, BasePermission.CREATE); createPermission(entityId, entityType, userUuid, BasePermission.DELETE); createPermission(entityId, entityType, userUuid, BasePermission.ADMINISTRATION); + + entityManager.flush(); } + @Transactional public void createPermission( - String entityId, Class entityType, String userUuid, Permission permission + String entityId, Class entityType, UUID userUuid, Permission permission ) { final MutableAcl acl = retrieveAcl(entityId, entityType); if (acl.getEntries().stream() @@ -169,58 +169,60 @@ public void createPermission( } public boolean checkRole(UserRole role) { - // 1. Get user - final Optional user = currentUserService.getCurrentUser(); - if (user.isEmpty()) { - return false; - } - - // 2. Validate - return user.get().getRole().equals(role); + return currentUserService.getCurrentUser() + .map(userAccount -> userAccount.getRole().equals(role)) + .orElse(false); } + @Transactional public boolean checkPermission( String entityId, Class entityType, Permission permission ) { - final Optional oUser = currentUserService.getCurrentUser(); + final Optional oUser = currentUserService.getCurrentUser(); if (oUser.isEmpty()) { return false; } - final User user = oUser.get(); + final UserAccount user = oUser.get(); final MutableAcl acl = retrieveAcl(entityId, entityType); return acl.getEntries() .stream() - .filter(ace -> ((PrincipalSid) ace.getSid()).getPrincipal().equals(user.getUuid())) + .filter(ace -> ((PrincipalSid) ace.getSid()).getPrincipal().equals(user.getUuid().toString())) .map(AccessControlEntry::getPermission) .anyMatch(permission2 -> permission2.getMask() == permission.getMask()); } - public void deleteMembers(User user) { - final List acls = aclRepository.findAll(); - for (MongoAcl acl : acls) { - acl.getPermissions() - .removeIf(permission -> permission.getSid().getName().equals(user.getUuid())); - aclRepository.save(acl); - } + public void deleteMembers(UserAccount user) { + Integer sid = (Integer) entityManager + .createNativeQuery("SELECT s.id FROM acl_sid s WHERE s.sid = :sid") + .setParameter("sid", user.getUuid().toString()) + .getSingleResult(); + + entityManager.createNativeQuery("DELETE FROM acl_entry WHERE sid = :sid") + .setParameter("sid", sid) + .executeUpdate(); + aclCache.clearCache(); } + @Transactional @PreAuthorize("hasPermission(#entityId, #entityType.getName(), 'WRITE') or hasRole('ADMIN')") - public void deleteMember(String entityId, Class entityType, String userUuid) { + public void deleteMember(String entityId, Class entityType, UUID userUuid) { // Get ACL final MutableAcl acl = retrieveAcl(entityId, entityType); for (int i = acl.getEntries().size() - 1; i >= 0; i--) { final AccessControlEntry ace = acl.getEntries().get(i); - if (ace.getSid().equals(new PrincipalSid(userUuid))) { + if (ace.getSid().equals(new PrincipalSid(userUuid.toString()))) { acl.deleteAce(i); } } aclService.updateAcl(acl); + entityManager.flush(); } - private Membership deriveMembership(List permissions) { + @Transactional + protected Membership deriveMembership(List permissions) { final List memberships = membershipRepository.findAll(); for (Membership membership : memberships) { final List membershipPermissions = membership.getPermissions(); @@ -241,7 +243,8 @@ private Membership deriveMembership(List permissions) { throw new IllegalArgumentException("Non-existing combination of permissions"); } - private MutableAcl retrieveAcl(String entityId, Class entityType) { + @Transactional + protected MutableAcl retrieveAcl(String entityId, Class entityType) { final ObjectIdentity identity = new ObjectIdentityImpl(entityType, entityId); try { return (MutableAcl) aclService.readAclById(identity); @@ -251,8 +254,7 @@ private MutableAcl retrieveAcl(String entityId, Class entityType) { } } - private void insertAce(MutableAcl acl, String userUuid, Permission permission) { - acl.insertAce(acl.getEntries().size(), permission, new PrincipalSid(userUuid), true); + private void insertAce(MutableAcl acl, UUID userUuid, Permission permission) { + acl.insertAce(acl.getEntries().size(), permission, new PrincipalSid(userUuid.toString()), true); } - } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/membership/MembershipService.java b/src/main/java/nl/dtls/fairdatapoint/service/membership/MembershipService.java index 5cfee58e6..bf16a6701 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/membership/MembershipService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/membership/MembershipService.java @@ -22,26 +22,26 @@ */ package nl.dtls.fairdatapoint.service.membership; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.membership.MembershipDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.MembershipRepository; +import nl.dtls.fairdatapoint.database.db.repository.MembershipRepository; import nl.dtls.fairdatapoint.entity.membership.Membership; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; import nl.dtls.fairdatapoint.util.KnownUUIDs; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; +import java.util.UUID; import static java.util.stream.Collectors.toList; @Service +@RequiredArgsConstructor public class MembershipService { - @Autowired - private MembershipRepository membershipRepository; + private final MembershipRepository membershipRepository; - @Autowired - private MembershipMapper membershipMapper; + private final MembershipMapper membershipMapper; public List getMemberships() { final List memberships = membershipRepository.findAll(); @@ -53,37 +53,37 @@ public List getMemberships() { } public void addToMembership(ResourceDefinition resourceDefinition) { - final String uuid = resourceDefinition.getUuid(); + final UUID uuid = resourceDefinition.getUuid(); // Add to owner final Membership owner = membershipRepository.findByUuid(KnownUUIDs.MEMBERSHIP_OWNER_UUID).get(); - addEntityIfMissing(owner, uuid); + addEntityIfMissing(owner, uuid.toString()); membershipRepository.save(owner); // Add to data provider if (resourceDefinition.isCatalog()) { final Membership dataProvider = membershipRepository.findByUuid(KnownUUIDs.MEMBERSHIP_DATAPROVIDER_UUID).get(); - addEntityIfMissing(dataProvider, uuid); + addEntityIfMissing(dataProvider, uuid.toString()); membershipRepository.save(dataProvider); } } public void removeFromMembership(ResourceDefinition resourceDefinition) { - final String uuid = resourceDefinition.getUuid(); + final UUID uuid = resourceDefinition.getUuid(); // Add to owner final Membership owner = membershipRepository.findByUuid(KnownUUIDs.MEMBERSHIP_OWNER_UUID).get(); - removeEntityIfPresent(owner, uuid); + removeEntityIfPresent(owner, uuid.toString()); membershipRepository.save(owner); // Add to data provider if (resourceDefinition.isCatalog()) { final Membership dataProvider = membershipRepository.findByUuid(KnownUUIDs.MEMBERSHIP_DATAPROVIDER_UUID).get(); - removeEntityIfPresent(dataProvider, uuid); + removeEntityIfPresent(dataProvider, uuid.toString()); membershipRepository.save(dataProvider); } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/metadata/catalog/CatalogMetadataService.java b/src/main/java/nl/dtls/fairdatapoint/service/metadata/catalog/CatalogMetadataService.java index dbb562f52..c4dd75d36 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/metadata/catalog/CatalogMetadataService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/metadata/catalog/CatalogMetadataService.java @@ -22,6 +22,7 @@ */ package nl.dtls.fairdatapoint.service.metadata.catalog; +import jakarta.annotation.Nonnull; import lombok.extern.slf4j.Slf4j; import nl.dtls.fairdatapoint.database.rdf.repository.RepositoryMode; import nl.dtls.fairdatapoint.database.rdf.repository.catalog.CatalogMetadataRepository; @@ -35,13 +36,12 @@ import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; -import javax.annotation.Nonnull; import java.util.List; import static nl.dtls.fairdatapoint.entity.metadata.MetadataSetter.setThemeTaxonomies; -@Service("catalogMetadataService") @Slf4j +@Service("catalogMetadataService") public class CatalogMetadataService extends AbstractMetadataService { @Autowired diff --git a/src/main/java/nl/dtls/fairdatapoint/service/metadata/common/AbstractMetadataService.java b/src/main/java/nl/dtls/fairdatapoint/service/metadata/common/AbstractMetadataService.java index 0307a79ce..5cb468f3c 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/metadata/common/AbstractMetadataService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/metadata/common/AbstractMetadataService.java @@ -32,7 +32,7 @@ import nl.dtls.fairdatapoint.entity.metadata.MetadataGetter; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinitionChild; -import nl.dtls.fairdatapoint.entity.user.User; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import nl.dtls.fairdatapoint.service.member.MemberService; import nl.dtls.fairdatapoint.service.metadata.enhance.MetadataEnhancer; import nl.dtls.fairdatapoint.service.metadata.exception.MetadataServiceException; @@ -187,7 +187,7 @@ public void delete(IRI uri, ResourceDefinition rd) throws MetadataServiceExcepti // Delete all children for (ResourceDefinitionChild child : rd.getChildren()) { - final String childRdUuid = child.getResourceDefinitionUuid(); + final UUID childRdUuid = child.getTarget().getUuid(); final ResourceDefinition rdChild = resourceDefinitionCache.getByUuid(childRdUuid); if (rdChild != null) { final List children = getChildren(metadata, i(child.getRelationUri())); @@ -205,7 +205,7 @@ public void delete(IRI uri, ResourceDefinition rd) throws MetadataServiceExcepti final IRI parentUri = getParent(metadata); final Model parentMetadata = retrieve(parentUri); for (ResourceDefinitionChild rdChild : rdParent.getChildren()) { - if (rdChild.getResourceDefinitionUuid().equals(rd.getUuid())) { + if (rdChild.getTarget().getUuid().equals(rd.getUuid())) { parentMetadata.remove(null, i(rdChild.getRelationUri()), uri); update(parentMetadata, parentUri, rdParent, false); } @@ -232,8 +232,7 @@ protected void updateParent( try { final List statements = new ArrayList<>(); for (ResourceDefinitionChild rdChild : rdParent.getChildren()) { - if (rdChild.getResourceDefinitionUuid() - .equals(resourceDefinition.getUuid())) { + if (rdChild.getTarget().getUuid().equals(resourceDefinition.getUuid())) { statements.add(s(parent, i(rdChild.getRelationUri()), uri)); } } @@ -263,7 +262,7 @@ protected void updateParent( } private void addPermissions(IRI uri) { - final Optional user = currentUserService.getCurrentUser(); + final Optional user = currentUserService.getCurrentUser(); if (user.isEmpty()) { return; } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/metadata/enhance/MetadataEnhancer.java b/src/main/java/nl/dtls/fairdatapoint/service/metadata/enhance/MetadataEnhancer.java index c6491e542..4f6c5e84e 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/metadata/enhance/MetadataEnhancer.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/metadata/enhance/MetadataEnhancer.java @@ -145,11 +145,11 @@ public void enhance(Model metadata, IRI uri, ResourceDefinition definition) { public void enhanceWithLinks(IRI entityUri, Model entity, ResourceDefinition definition, String url, Model resultRdf) { for (ResourceDefinitionChild child : definition.getChildren()) { - final ResourceDefinition rdChild = resourceDefinitionCache.getByUuid(child.getResourceDefinitionUuid()); + final ResourceDefinition rdChild = resourceDefinitionCache.getByUuid(child.getTarget().getUuid()); final IRI container = i(format("%s/%s/", url, rdChild.getUrlPrefix())); resultRdf.add(container, RDF.TYPE, LDP.DIRECT_CONTAINER); - resultRdf.add(container, DCTERMS.TITLE, l(child.getListView().getTitle())); + resultRdf.add(container, DCTERMS.TITLE, l(child.getTitle())); resultRdf.add(container, LDP.MEMBERSHIP_RESOURCE, entityUri); resultRdf.add(container, LDP.HAS_MEMBER_RELATION, i(child.getRelationUri())); for (org.eclipse.rdf4j.model.Value childUri : getObjectsBy(entity, entityUri, i(child.getRelationUri()))) { diff --git a/src/main/java/nl/dtls/fairdatapoint/service/metadata/metric/MetricsMetadataService.java b/src/main/java/nl/dtls/fairdatapoint/service/metadata/metric/MetricsMetadataService.java index 66cfc944a..e4bd1949d 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/metadata/metric/MetricsMetadataService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/metadata/metric/MetricsMetadataService.java @@ -27,16 +27,16 @@ */ package nl.dtls.fairdatapoint.service.metadata.metric; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import nl.dtls.fairdatapoint.entity.metadata.Metric; import nl.dtls.fairdatapoint.entity.settings.Settings; +import nl.dtls.fairdatapoint.entity.settings.SettingsMetric; import nl.dtls.fairdatapoint.service.settings.SettingsService; import org.apache.commons.codec.digest.DigestUtils; import org.eclipse.rdf4j.model.IRI; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import javax.annotation.Nonnull; import java.util.List; import static java.lang.String.format; @@ -44,21 +44,23 @@ @Slf4j @Service +@RequiredArgsConstructor public class MetricsMetadataService { - @Autowired - private SettingsService settingsService; + private final SettingsService settingsService; - public List generateMetrics(@Nonnull IRI metadataURI) { + public List generateMetrics(IRI metadataURI) { final Settings settings = settingsService.getOrDefaults(); - return settings.getMetadataMetrics().stream() - .map(entry -> { - return new Metric( - i(format("%s/metrics/%s", metadataURI, DigestUtils.md5Hex(entry.getMetricUri()))), - i(entry.getResourceUri()), - i(entry.getResourceUri())); - }) + return settings.getMetrics().stream() + .map(entry -> toMetric(entry, metadataURI)) .toList(); } + private Metric toMetric(SettingsMetric metric, IRI metadataURI) { + return new Metric( + i(format("%s/metrics/%s", metadataURI, DigestUtils.md5Hex(metric.getMetricUri()))), + i(metric.getResourceUri()), + i(metric.getResourceUri()) + ); + } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/metadata/validator/MetadataValidator.java b/src/main/java/nl/dtls/fairdatapoint/service/metadata/validator/MetadataValidator.java index 5fbd9b854..0fda41c2f 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/metadata/validator/MetadataValidator.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/metadata/validator/MetadataValidator.java @@ -82,7 +82,7 @@ private void validateParent(Model metadata, ResourceDefinition definition) throw if (rdParent .getChildren() .stream() - .noneMatch(rdChild -> rdChild.getResourceDefinitionUuid().equals(definition.getUuid())) + .noneMatch(rdChild -> rdChild.getTarget().equals(definition)) ) { throw new ValidationException(format("Parent is not of correct type (RD: %s)", rdParent.getName())); } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/openapi/OpenApiService.java b/src/main/java/nl/dtls/fairdatapoint/service/openapi/OpenApiService.java index 1c4cfc6fc..1d05168ba 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/openapi/OpenApiService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/openapi/OpenApiService.java @@ -26,36 +26,36 @@ import io.swagger.v3.oas.models.PathItem; import io.swagger.v3.oas.models.Paths; import jakarta.annotation.PostConstruct; -import lombok.extern.log4j.Log4j2; -import nl.dtls.fairdatapoint.database.mongo.repository.ResourceDefinitionRepository; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import nl.dtls.fairdatapoint.database.db.repository.ResourceDefinitionRepository; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.UUID; import java.util.stream.Collectors; +@Slf4j @Service -@Log4j2 +@RequiredArgsConstructor public class OpenApiService { private static final String MSG_ADD = "Adding OpenAPI paths: {}"; private static final String MSG_REMOVE = "Removing OpenAPI paths: {}"; - @Autowired - private OpenAPI openAPI; + private final OpenAPI openAPI; - @Autowired - private ResourceDefinitionRepository resourceDefinitionRepository; + private final ResourceDefinitionRepository resourceDefinitionRepository; private Paths getGenericPaths() { return (Paths) openAPI.getExtensions().get("fdpGenericPaths"); } private boolean isRelatedToResourceDefinition(PathItem pathItem, ResourceDefinition definition) { - final String rdUuid = (String) pathItem.getExtensions().getOrDefault("fdpResourceDefinition", ""); + final UUID rdUuid = (UUID) pathItem.getExtensions().getOrDefault("fdpResourceDefinition", ""); return rdUuid.equals(definition.getUuid()); } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/ping/PingService.java b/src/main/java/nl/dtls/fairdatapoint/service/ping/PingService.java index d3a47b962..b95b92efe 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/ping/PingService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/ping/PingService.java @@ -22,12 +22,12 @@ */ package nl.dtls.fairdatapoint.service.ping; -import lombok.extern.log4j.Log4j2; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import nl.dtls.fairdatapoint.config.properties.InstanceProperties; import nl.dtls.fairdatapoint.config.properties.PingProperties; import nl.dtls.fairdatapoint.entity.settings.Settings; import nl.dtls.fairdatapoint.service.settings.SettingsService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.scheduling.annotation.Async; import org.springframework.scheduling.annotation.Scheduled; @@ -38,22 +38,19 @@ import java.util.Map; import java.util.stream.Stream; -@Log4j2 +@Slf4j @Service +@RequiredArgsConstructor @ConditionalOnProperty(name = "ping.enabled", havingValue = "true", matchIfMissing = true) public class PingService { - @Autowired - private PingProperties pingProperties; + private final PingProperties pingProperties; - @Autowired - private InstanceProperties instanceProperties; + private final InstanceProperties instanceProperties; - @Autowired - private SettingsService settingsService; + private final SettingsService settingsService; - @Autowired - private RestTemplate client; + private final RestTemplate client; @Scheduled( initialDelayString = "${ping.initDelay:#{10*1000}}", @@ -61,12 +58,12 @@ public class PingService { ) public void ping() { final Settings settings = settingsService.getOrDefaults(); - if (!settings.getPing().isEnabled() || !pingProperties.isEnabled()) { + if (!settings.getPingEnabled() || !pingProperties.isEnabled()) { return; } final List endpoints = Stream.concat( pingProperties.getEndpoints().stream(), - settings.getPing().getEndpoints().stream() + settings.getPingEndpoints().stream() ).distinct().toList(); for (String endpoint : endpoints) { pingEndpoint( diff --git a/src/main/java/nl/dtls/fairdatapoint/service/profile/ProfileService.java b/src/main/java/nl/dtls/fairdatapoint/service/profile/ProfileService.java index cec153351..b71b908bb 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/profile/ProfileService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/profile/ProfileService.java @@ -22,9 +22,10 @@ */ package nl.dtls.fairdatapoint.service.profile; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaRepository; +import lombok.RequiredArgsConstructor; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaVersionRepository; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaVersion; import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionService; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Model; @@ -34,30 +35,26 @@ import org.eclipse.rdf4j.model.vocabulary.DCTERMS; import org.eclipse.rdf4j.model.vocabulary.RDF; import org.eclipse.rdf4j.model.vocabulary.RDFS; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.Optional; +import java.util.UUID; import static java.lang.String.format; import static nl.dtls.fairdatapoint.util.ValueFactoryHelper.*; @Service +@RequiredArgsConstructor public class ProfileService { private static final String PROFILE_PREFIX = "http://www.w3.org/ns/dx/prof/"; - @Autowired - @Qualifier("persistentUrl") - private String persistentUrl; + private final String persistentUrl; - @Autowired - private MetadataSchemaRepository metadataSchemaRepository; + private final MetadataSchemaVersionRepository metadataSchemaRepository; - @Autowired - private ResourceDefinitionService resourceDefinitionService; + private final ResourceDefinitionService resourceDefinitionService; private Model getProfileForResourceDefinition( ResourceDefinition resourceDefinition, IRI uri @@ -71,16 +68,17 @@ private Model getProfileForResourceDefinition( i(format("%s/profile/core", persistentUrl)) ); resourceDefinition - .getMetadataSchemaUuids() - .forEach(schemaUuid -> { - metadataSchemaRepository.findByUuidAndLatestIsTrue(schemaUuid).ifPresent(schema -> { - addSchemaToProfile(uri, profile, schema); - }); + .getMetadataSchemaUsages() + .forEach(usage -> { + metadataSchemaRepository + .getLatestBySchemaUuid(usage.getUsedMetadataSchema().getUuid()).ifPresent(schema -> { + addSchemaToProfile(uri, profile, schema); + }); }); return profile; } - private void addSchemaToProfile(IRI uri, Model profile, MetadataSchema schema) { + private void addSchemaToProfile(IRI uri, Model profile, MetadataSchemaVersion schema) { final ModelBuilder modelBuilder = new ModelBuilder(); final Resource resource = bn(); modelBuilder.subject(resource); @@ -96,7 +94,7 @@ private void addSchemaToProfile(IRI uri, Model profile, MetadataSchema schema) { profile.addAll(new ArrayList<>(modelBuilder.build())); } - public Optional getProfileByUuid(String uuid, IRI uri) { + public Optional getProfileByUuid(UUID uuid, IRI uri) { return resourceDefinitionService .getByUuid(uuid) .map(definition -> getProfileForResourceDefinition(definition, uri)); diff --git a/src/main/java/nl/dtls/fairdatapoint/service/reset/FactoryDefaults.java b/src/main/java/nl/dtls/fairdatapoint/service/reset/FactoryDefaults.java index 7c085d106..df3e6c2a0 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/reset/FactoryDefaults.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/reset/FactoryDefaults.java @@ -22,33 +22,19 @@ */ package nl.dtls.fairdatapoint.service.reset; -import nl.dtls.fairdatapoint.entity.membership.Membership; -import nl.dtls.fairdatapoint.entity.membership.MembershipPermission; -import nl.dtls.fairdatapoint.entity.resource.*; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaType; import nl.dtls.fairdatapoint.entity.schema.SemVer; -import nl.dtls.fairdatapoint.entity.user.User; -import nl.dtls.fairdatapoint.entity.user.UserRole; -import nl.dtls.fairdatapoint.service.schema.MetadataSchemaShaclUtils; -import nl.dtls.fairdatapoint.util.KnownUUIDs; import nl.dtls.fairdatapoint.vocabulary.DATACITE; import nl.dtls.fairdatapoint.vocabulary.DCAT3; import nl.dtls.fairdatapoint.vocabulary.FDP; import nl.dtls.fairdatapoint.vocabulary.R3D; -import org.bson.BasicBSONObject; -import org.bson.Document; -import org.bson.types.BasicBSONList; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.vocabulary.*; import java.time.OffsetDateTime; import java.util.ArrayList; -import java.util.Collections; import java.util.List; -import static nl.dtls.fairdatapoint.util.ResourceReader.loadClassResource; import static nl.dtls.fairdatapoint.util.ValueFactoryHelper.*; public class FactoryDefaults { @@ -78,367 +64,6 @@ public class FactoryDefaults { public static final SemVer SEMVER_V1 = new SemVer("1.0.0"); - // == USERS - // Changes: Migration_0001_Init - public static final User USER_ALBERT = User.builder() - .uuid(KnownUUIDs.USER_ALBERT_UUID) - .firstName("Albert") - .lastName("Einstein") - .email("albert.einstein@example.com") - .passwordHash(PASSWORD_HASH) - .role(UserRole.ADMIN) - .build(); - - public static final User USER_NIKOLA = User.builder() - .uuid(KnownUUIDs.USER_NIKOLA_UUID) - .firstName("Nikola") - .lastName("Tesla") - .email("nikola.tesla@example.com") - .passwordHash(PASSWORD_HASH) - .role(UserRole.USER) - .build(); - - // == MEMBERSHIPS - // Changes: Migration_0001_Init, Migration_0004_ResourceDefinition - public static final int MASK_W = 2; - public static final int MASK_C = 4; - public static final int MASK_D = 8; - public static final int MASK_A = 16; - - public static final Membership MEMBERSHIP_OWNER = Membership.builder() - .uuid(KnownUUIDs.MEMBERSHIP_OWNER_UUID) - .name("Owner") - .permissions(List.of( - new MembershipPermission(MASK_W, 'W'), - new MembershipPermission(MASK_C, 'C'), - new MembershipPermission(MASK_D, 'D'), - new MembershipPermission(MASK_A, 'A') - )) - .allowedEntities(List.of( - KnownUUIDs.RD_CATALOG_UUID, - KnownUUIDs.RD_DATASET_UUID, - KnownUUIDs.RD_DISTRIBUTION_UUID - )) - .build(); - - public static final Membership MEMBERSHIP_DATA_PROVIDER = Membership.builder() - .uuid(KnownUUIDs.MEMBERSHIP_DATAPROVIDER_UUID) - .name("Data Provider") - .permissions(List.of( - new MembershipPermission(MASK_C, 'C') - )) - .allowedEntities(List.of( - KnownUUIDs.RD_CATALOG_UUID - )) - .build(); - - // == RESOURCE DEFINITIONS - // Changes: Migration_0002_CustomMetamodel, Migration_0004_ResourceDefinition, Migration_0010_ComplyFDPO - public static final String FDP_TITLE = "FAIR Data Point"; - public static final String FDP_PREFIX = ""; - public static final String CATALOG_TITLE = "Catalog"; - public static final String CATALOG_PREFIX = "catalog"; - public static final String DATASET_TITLE = "Dataset"; - public static final String DATASET_PREFIX = "dataset"; - public static final String DISTRIBUTION_TITLE = "Distribution"; - public static final String DISTRIBUTION_PREFIX = "distribution"; - public static final String DATASERVICE_TITLE = "Data Service"; - public static final String DATASERVICE_PREFIX = "data-service"; - public static final String METADATASERVICE_TITLE = "Metadata Service"; - public static final String METADATASERVICE_PREFIX = "metadata-service"; - - public static final ResourceDefinition RESOURCE_DEFINITION_FDP = ResourceDefinition.builder() - .uuid(KnownUUIDs.RD_FDP_UUID) - .name(FDP_TITLE) - .urlPrefix(FDP_PREFIX) - .metadataSchemaUuids(List.of(KnownUUIDs.SCHEMA_FDP_UUID)) - .children(List.of( - ResourceDefinitionChild.builder() - .resourceDefinitionUuid(KnownUUIDs.RD_CATALOG_UUID) - .relationUri(FDP.METADATACATALOG.stringValue()) - .listView( - ResourceDefinitionChildListView.builder() - .title("Catalogs") - .tagsUri(DCAT.THEME_TAXONOMY.stringValue()) - .metadata(List.of()) - .build() - ) - .build() - )) - .externalLinks(List.of()) - .build(); - - public static final ResourceDefinition RESOURCE_DEFINITION_CATALOG = ResourceDefinition.builder() - .uuid(KnownUUIDs.RD_CATALOG_UUID) - .name(CATALOG_TITLE) - .urlPrefix(CATALOG_PREFIX) - .metadataSchemaUuids(List.of(KnownUUIDs.SCHEMA_CATALOG_UUID)) - .children(List.of( - ResourceDefinitionChild.builder() - .resourceDefinitionUuid(KnownUUIDs.RD_DATASET_UUID) - .relationUri(DCAT.HAS_DATASET.stringValue()) - .listView( - ResourceDefinitionChildListView.builder() - .title("Datasets") - .tagsUri(DCAT.THEME.stringValue()) - .metadata(List.of()) - .build() - ) - .build() - )) - .externalLinks(List.of()) - .build(); - - public static final ResourceDefinition RESOURCE_DEFINITION_DATASET = ResourceDefinition.builder() - .uuid(KnownUUIDs.RD_DATASET_UUID) - .name(DATASET_TITLE) - .urlPrefix(DATASET_PREFIX) - .metadataSchemaUuids(List.of(KnownUUIDs.SCHEMA_DATASET_UUID)) - .children(List.of( - ResourceDefinitionChild.builder() - .resourceDefinitionUuid(KnownUUIDs.RD_DISTRIBUTION_UUID) - .relationUri(DCAT.HAS_DISTRIBUTION.stringValue()) - .listView( - ResourceDefinitionChildListView.builder() - .title("Distributions") - .tagsUri(null) - .metadata(List.of( - new ResourceDefinitionChildListViewMetadata( - "Media Type", - DCAT.MEDIA_TYPE.stringValue() - ) - )) - .build() - ) - .build() - )) - .externalLinks(List.of()) - .build(); - - public static final ResourceDefinition RESOURCE_DEFINITION_DISTRIBUTION = ResourceDefinition.builder() - .uuid(KnownUUIDs.RD_DISTRIBUTION_UUID) - .name(DISTRIBUTION_TITLE) - .urlPrefix(DISTRIBUTION_PREFIX) - .metadataSchemaUuids(List.of(KnownUUIDs.SCHEMA_DISTRIBUTION_UUID)) - .children(List.of()) - .externalLinks(List.of( - new ResourceDefinitionLink( - "Access online", - DCAT.ACCESS_URL.stringValue() - ), - new ResourceDefinitionLink( - "Download", - DCAT.DOWNLOAD_URL.stringValue() - ) - )) - .build(); - - // == SHAPES - // == Changes: Migration_0003_ShapeDefinition, Migration_0005_UpdateShapeDefinition, - // Migration_0006_ShapesSharing, Migration_0010_ComplyFDPO - public static MetadataSchema schemaResource() throws Exception { - final String definition = loadClassResource("shape-resource.ttl", FactoryDefaults.class); - return MetadataSchema.builder() - .uuid(KnownUUIDs.SCHEMA_RESOURCE_UUID) - .name("Resource") - .type(MetadataSchemaType.INTERNAL) - .published(false) - .latest(true) - .version(SEMVER_V1) - .versionString(SEMVER_V1.toString()) - .versionUuid(KnownUUIDs.SCHEMA_V1_RESOURCE_UUID) - .previousVersionUuid(null) - .origin(FDP_APP_URL) - .importedFrom(FDP_APP_URL) - .extendSchemas(Collections.emptyList()) - .abstractSchema(true) - .definition(definition) - .targetClasses(MetadataSchemaShaclUtils.extractTargetClasses(definition)) - .build(); - } - - public static MetadataSchema schemaFDP() throws Exception { - final String definition = loadClassResource("shape-fdp.ttl", FactoryDefaults.class); - return MetadataSchema.builder() - .uuid(KnownUUIDs.SCHEMA_FDP_UUID) - .name(FDP_TITLE) - .type(MetadataSchemaType.INTERNAL) - .published(false) - .latest(true) - .version(SEMVER_V1) - .versionString(SEMVER_V1.toString()) - .versionUuid(KnownUUIDs.SCHEMA_V1_FDP_UUID) - .previousVersionUuid(null) - .origin(FDP_APP_URL) - .importedFrom(FDP_APP_URL) - .extendSchemas(List.of(KnownUUIDs.SCHEMA_METADATASERVICE_UUID)) - .abstractSchema(false) - .definition(definition) - .targetClasses(MetadataSchemaShaclUtils.extractTargetClasses(definition)) - .suggestedResourceName(FDP_TITLE) - .suggestedUrlPrefix(FDP_PREFIX) - .build(); - } - - public static MetadataSchema schemaDataService() throws Exception { - final String definition = loadClassResource("shape-data-service.ttl", FactoryDefaults.class); - return MetadataSchema.builder() - .uuid(KnownUUIDs.SCHEMA_DATASERVICE_UUID) - .name(DATASERVICE_TITLE) - .type(MetadataSchemaType.INTERNAL) - .published(false) - .latest(true) - .version(SEMVER_V1) - .versionString(SEMVER_V1.toString()) - .versionUuid(KnownUUIDs.SCHEMA_V1_DATASERVICE_UUID) - .previousVersionUuid(null) - .origin(FDP_APP_URL) - .importedFrom(FDP_APP_URL) - .extendSchemas(List.of(KnownUUIDs.SCHEMA_RESOURCE_UUID)) - .abstractSchema(false) - .definition(definition) - .targetClasses(MetadataSchemaShaclUtils.extractTargetClasses(definition)) - .suggestedResourceName(DATASERVICE_TITLE) - .suggestedUrlPrefix(DATASERVICE_PREFIX) - .build(); - } - - public static MetadataSchema schemaMetadataService() throws Exception { - final String definition = loadClassResource("shape-metadata-service.ttl", FactoryDefaults.class); - return MetadataSchema.builder() - .uuid(KnownUUIDs.SCHEMA_METADATASERVICE_UUID) - .name(METADATASERVICE_TITLE) - .type(MetadataSchemaType.INTERNAL) - .published(false) - .latest(true) - .version(SEMVER_V1) - .versionString(SEMVER_V1.toString()) - .versionUuid(KnownUUIDs.SCHEMA_V1_METADATASERVICE_UUID) - .previousVersionUuid(null) - .origin(FDP_APP_URL) - .importedFrom(FDP_APP_URL) - .extendSchemas(List.of(KnownUUIDs.SCHEMA_DATASERVICE_UUID)) - .abstractSchema(false) - .definition(definition) - .targetClasses(MetadataSchemaShaclUtils.extractTargetClasses(definition)) - .suggestedResourceName(METADATASERVICE_TITLE) - .suggestedUrlPrefix(METADATASERVICE_PREFIX) - .build(); - } - - public static MetadataSchema schemaCatalog() throws Exception { - final String definition = loadClassResource("shape-catalog.ttl", FactoryDefaults.class); - return MetadataSchema.builder() - .uuid(KnownUUIDs.SCHEMA_CATALOG_UUID) - .name(CATALOG_TITLE) - .type(MetadataSchemaType.INTERNAL) - .published(false) - .latest(true) - .version(SEMVER_V1) - .versionString(SEMVER_V1.toString()) - .versionUuid(KnownUUIDs.SCHEMA_V1_CATALOG_UUID) - .previousVersionUuid(null) - .origin(FDP_APP_URL) - .importedFrom(FDP_APP_URL) - .extendSchemas(List.of(KnownUUIDs.SCHEMA_RESOURCE_UUID)) - .abstractSchema(false) - .definition(definition) - .targetClasses(MetadataSchemaShaclUtils.extractTargetClasses(definition)) - .suggestedResourceName(CATALOG_TITLE) - .suggestedUrlPrefix(CATALOG_PREFIX) - .build(); - } - - public static MetadataSchema schemaDataset() throws Exception { - final String definition = loadClassResource("shape-dataset.ttl", FactoryDefaults.class); - return MetadataSchema.builder() - .uuid(KnownUUIDs.SCHEMA_DATASET_UUID) - .name(DATASET_TITLE) - .type(MetadataSchemaType.CUSTOM) - .published(false) - .latest(true) - .version(SEMVER_V1) - .versionString(SEMVER_V1.toString()) - .versionUuid(KnownUUIDs.SCHEMA_V1_DATASET_UUID) - .previousVersionUuid(null) - .origin(FDP_APP_URL) - .importedFrom(FDP_APP_URL) - .extendSchemas(List.of(KnownUUIDs.SCHEMA_RESOURCE_UUID)) - .abstractSchema(false) - .definition(definition) - .targetClasses(MetadataSchemaShaclUtils.extractTargetClasses(definition)) - .suggestedResourceName(DATASET_TITLE) - .suggestedUrlPrefix(DATASET_PREFIX) - .build(); - } - - public static MetadataSchema schemaDistribution() throws Exception { - final String definition = loadClassResource("shape-distribution.ttl", FactoryDefaults.class); - return MetadataSchema.builder() - .uuid(KnownUUIDs.SCHEMA_DISTRIBUTION_UUID) - .name(DISTRIBUTION_TITLE) - .type(MetadataSchemaType.CUSTOM) - .published(false) - .latest(true) - .version(SEMVER_V1) - .versionString(SEMVER_V1.toString()) - .versionUuid(KnownUUIDs.SCHEMA_V1_DISTRIBUTION_UUID) - .previousVersionUuid(null) - .origin(FDP_APP_URL) - .importedFrom(FDP_APP_URL) - .extendSchemas(List.of(KnownUUIDs.SCHEMA_RESOURCE_UUID)) - .abstractSchema(false) - .definition(definition) - .targetClasses(MetadataSchemaShaclUtils.extractTargetClasses(definition)) - .suggestedResourceName(DISTRIBUTION_TITLE) - .suggestedUrlPrefix(DISTRIBUTION_PREFIX) - .build(); - } - - // Repository ACL - public static Document aclRepository(String persistentUrl) { - final BasicBSONObject owner = new BasicBSONObject() - .append("name", USER_ALBERT.getUuid()) - .append("isPrincipal", true); - final Document acl = new Document(); - acl.append("className", "nl.dtls.fairdatapoint.entity.metadata.FDPMetadata"); - acl.append("instanceId", persistentUrl); - acl.append("owner", owner); - acl.append("inheritPermissions", true); - final BasicBSONList permissions = new BasicBSONList(); - permissions.add( - new Document() - .append(FIELD_SID, owner) - .append(FIELD_PERM, MASK_W) - .append(FIELD_GRANT, true) - .append(FIELD_AUDIT_FAILURE, false) - .append(FIELD_AUDIT_SUCCESS, false)); - permissions.add( - new Document() - .append(FIELD_SID, owner) - .append(FIELD_PERM, MASK_C) - .append(FIELD_GRANT, true) - .append(FIELD_AUDIT_FAILURE, false) - .append(FIELD_AUDIT_SUCCESS, false)); - permissions.add( - new Document() - .append(FIELD_SID, owner) - .append(FIELD_PERM, MASK_D) - .append(FIELD_GRANT, true) - .append(FIELD_AUDIT_FAILURE, false) - .append(FIELD_AUDIT_SUCCESS, false)); - permissions.add( - new Document() - .append(FIELD_SID, owner) - .append(FIELD_PERM, MASK_A) - .append(FIELD_GRANT, true) - .append(FIELD_AUDIT_FAILURE, false) - .append(FIELD_AUDIT_SUCCESS, false)); - acl.append("permissions", permissions); - acl.append("_class", "org.springframework.security.acls.domain.MongoAcl"); - return acl; - } - // Repository RDF statements public static List repositoryStatements(String persistentUrl, IRI license, diff --git a/src/main/java/nl/dtls/fairdatapoint/service/reset/ResetService.java b/src/main/java/nl/dtls/fairdatapoint/service/reset/ResetService.java index f5b3381db..5b3519196 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/reset/ResetService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/reset/ResetService.java @@ -22,17 +22,15 @@ */ package nl.dtls.fairdatapoint.service.reset; -import com.mongodb.client.MongoCollection; import lombok.extern.slf4j.Slf4j; import nl.dtls.fairdatapoint.api.dto.reset.ResetDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.*; +import nl.dtls.fairdatapoint.database.db.repository.*; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; import nl.dtls.fairdatapoint.service.metadata.exception.MetadataServiceException; import nl.dtls.fairdatapoint.service.metadata.generic.GenericMetadataService; import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionCache; import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionTargetClassesCache; import nl.dtls.fairdatapoint.service.settings.SettingsService; -import org.bson.Document; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.repository.Repository; @@ -41,9 +39,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.factory.annotation.Value; -import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.security.access.prepost.PreAuthorize; -import org.springframework.security.acls.dao.AclRepository; import org.springframework.security.acls.model.AclCache; import org.springframework.stereotype.Service; @@ -81,14 +77,11 @@ public class ResetService { @Autowired private MembershipRepository membershipRepository; - @Autowired - private AclRepository aclRepository; - @Autowired private AclCache aclCache; @Autowired - private UserRepository userRepository; + private UserAccountRepository userRepository; @Autowired private MetadataSchemaRepository metadataSchemaRepository; @@ -108,9 +101,6 @@ public class ResetService { @Autowired private SettingsService settingsService; - @Autowired - private MongoTemplate mongoTemplate; - @PreAuthorize("hasRole('ADMIN')") public void resetToFactoryDefaults(ResetDTO reqDto) throws Exception { log.info("Resetting to factory defaults"); @@ -149,7 +139,6 @@ private void clearMemberships() { log.debug("Clearing memberships"); membershipRepository.deleteAll(); log.debug("Clearing ACL cache"); - aclRepository.deleteAll(); aclCache.clearCache(); } @@ -169,7 +158,6 @@ private void clearResourceDefinitions() { } private void clearMetadata() throws MetadataServiceException { - // TODO REPO: clear DRAFTS repository log.debug("Clearing metadata"); final Optional resourceDefinition = resourceDefinitionRepository.findByUrlPrefix(""); @@ -180,18 +168,12 @@ private void clearMetadata() throws MetadataServiceException { private void restoreDefaultUsers() { log.debug("Creating default users"); - userRepository.save(FactoryDefaults.USER_ALBERT); - userRepository.save(FactoryDefaults.USER_NIKOLA); + // TODO: data seed from specs } private void restoreDefaultMemberships() { log.debug("Creating default memberships"); - membershipRepository.save(FactoryDefaults.MEMBERSHIP_OWNER); - membershipRepository.save(FactoryDefaults.MEMBERSHIP_DATA_PROVIDER); - - final MongoCollection aclCol = - mongoTemplate.getCollection("ACL"); - aclCol.insertOne(FactoryDefaults.aclRepository(persistentUrl)); + // TODO: data seed from specs } private void restoreDefaultMetadata() { @@ -212,20 +194,11 @@ private void restoreDefaultMetadata() { private void restoreDefaultMetadataSchemas() throws Exception { log.debug("Creating default metadata schemas"); - metadataSchemaRepository.save(FactoryDefaults.schemaResource()); - metadataSchemaRepository.save(FactoryDefaults.schemaDataService()); - metadataSchemaRepository.save(FactoryDefaults.schemaMetadataService()); - metadataSchemaRepository.save(FactoryDefaults.schemaFDP()); - metadataSchemaRepository.save(FactoryDefaults.schemaCatalog()); - metadataSchemaRepository.save(FactoryDefaults.schemaDataset()); - metadataSchemaRepository.save(FactoryDefaults.schemaDistribution()); + // TODO: data seed from specs } private void restoreDefaultResourceDefinitions() { log.debug("Creating default resource definitions"); - resourceDefinitionRepository.save(FactoryDefaults.RESOURCE_DEFINITION_FDP); - resourceDefinitionRepository.save(FactoryDefaults.RESOURCE_DEFINITION_CATALOG); - resourceDefinitionRepository.save(FactoryDefaults.RESOURCE_DEFINITION_DATASET); - resourceDefinitionRepository.save(FactoryDefaults.RESOURCE_DEFINITION_DISTRIBUTION); + // TODO: data seed from specs } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionCache.java b/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionCache.java index 7a5d5b691..54d620040 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionCache.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionCache.java @@ -24,29 +24,29 @@ import jakarta.annotation.PostConstruct; import lombok.Getter; -import nl.dtls.fairdatapoint.database.mongo.repository.ResourceDefinitionRepository; +import lombok.RequiredArgsConstructor; +import nl.dtls.fairdatapoint.database.db.repository.ResourceDefinitionChildRepository; +import nl.dtls.fairdatapoint.database.db.repository.ResourceDefinitionRepository; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.Cache; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.stereotype.Service; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; +import java.util.*; +import java.util.stream.Collectors; import static nl.dtls.fairdatapoint.config.CacheConfig.RESOURCE_DEFINITION_CACHE; import static nl.dtls.fairdatapoint.config.CacheConfig.RESOURCE_DEFINITION_PARENT_CACHE; @Service +@RequiredArgsConstructor public class ResourceDefinitionCache { - @Autowired - private ConcurrentMapCacheManager cacheManager; + private final ConcurrentMapCacheManager cacheManager; - @Autowired - private ResourceDefinitionRepository resourceDefinitionRepository; + private final ResourceDefinitionRepository resourceDefinitionRepository; + + private final ResourceDefinitionChildRepository resourceDefinitionChildRepository; @PostConstruct public void computeCache() { @@ -59,27 +59,25 @@ public void computeCache() { parentCache.clear(); // Add to cache - final List rds = resourceDefinitionRepository.findAll(); - rds.forEach(resourceDefinition -> { - parentCache.put(resourceDefinition.getUuid(), new ResourceDefinitionParents()); - }); - rds.forEach(resourceDefinition -> { - cache.put(resourceDefinition.getUuid(), resourceDefinition); - resourceDefinition.getChildren() - .forEach(child -> { - parentCache.get( - child.getResourceDefinitionUuid(), - ResourceDefinitionParents.class - ).add(resourceDefinition); - }); - }); + resourceDefinitionChildRepository.getAllMappings() + .forEach(mapping -> { + if (parentCache.get(mapping.getTargetUuid(), ResourceDefinitionParents.class) == null) { + parentCache.put(mapping.getTargetUuid(), new ResourceDefinitionParents()); + } + parentCache + .get(mapping.getTargetUuid(), ResourceDefinitionParents.class) + .add(mapping.getSourceUuid()); + }); + } - public ResourceDefinition getByUuid(String uuid) { - return cache().get(uuid, ResourceDefinition.class); + public ResourceDefinition getByUuid(UUID uuid) { + // TODO: not needed anymore? + return resourceDefinitionRepository.findByUuid(uuid).orElse(null); } - public Set getParentsByUuid(String uuid) { + public Set getParentsByUuid(UUID uuid) { + // TODO: not needed anymore? var parents = parentCache().get(uuid, ResourceDefinitionParents.class); if (parents == null) { computeCache(); @@ -88,7 +86,11 @@ public Set getParentsByUuid(String uuid) { return Collections.emptySet(); } } - return parents.getParents(); + return parents.getParents() + .stream() + .map(parentUuid -> resourceDefinitionRepository.findByUuid(parentUuid).orElse(null)) + .filter(Objects::nonNull) + .collect(Collectors.toSet()); } private Cache cache() { @@ -101,9 +103,9 @@ private Cache parentCache() { @Getter private static final class ResourceDefinitionParents { - private final Set parents = new HashSet<>(); + private final Set parents = new HashSet<>(); - public void add(ResourceDefinition rdParent) { + public void add(UUID rdParent) { parents.add(rdParent); } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionMapper.java b/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionMapper.java index 8f6f8b838..41da4e303 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionMapper.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionMapper.java @@ -22,49 +22,151 @@ */ package nl.dtls.fairdatapoint.service.resource; -import nl.dtls.fairdatapoint.api.dto.resource.ResourceDefinitionChangeDTO; -import nl.dtls.fairdatapoint.api.dto.resource.ResourceDefinitionDTO; -import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; +import nl.dtls.fairdatapoint.api.dto.resource.*; +import nl.dtls.fairdatapoint.entity.resource.*; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; import org.springframework.stereotype.Service; +import java.time.Instant; import java.util.List; +import java.util.UUID; @Service public class ResourceDefinitionMapper { - public ResourceDefinition fromChangeDTO(ResourceDefinitionChangeDTO dto, String uuid) { - return new ResourceDefinition( - uuid, - dto.getName(), - dto.getUrlPrefix(), - dto.getMetadataSchemaUuids(), - dto.getChildren(), - dto.getExternalLinks()); + public ResourceDefinition fromChangeDTO(ResourceDefinitionChangeDTO dto) { + return ResourceDefinition.builder() + .uuid(UUID.randomUUID()) + .name(dto.getName()) + .urlPrefix(dto.getUrlPrefix()) + .build(); + } + + public ResourceDefinition fromChangeDTO(ResourceDefinitionChangeDTO dto, ResourceDefinition resourceDefinition) { + return resourceDefinition.toBuilder() + .name(dto.getName()) + .urlPrefix(dto.getUrlPrefix()) + .updatedAt(Instant.now()) + .build(); } public ResourceDefinitionChangeDTO toChangeDTO( ResourceDefinition resourceDefinition ) { - return new ResourceDefinitionChangeDTO( - resourceDefinition.getName(), - resourceDefinition.getUrlPrefix(), - resourceDefinition.getMetadataSchemaUuids(), - resourceDefinition.getChildren(), - resourceDefinition.getExternalLinks()); + return ResourceDefinitionChangeDTO.builder() + .name(resourceDefinition.getName()) + .urlPrefix(resourceDefinition.getUrlPrefix()) + .metadataSchemaUuids( + resourceDefinition + .getMetadataSchemaUsages() + .stream() + .map(usage -> usage.getUsedMetadataSchema().getUuid()) + .toList() + ) + .children(resourceDefinition.getChildren().stream().map(this::toChildDTO).toList()) + .externalLinks(resourceDefinition.getExternalLinks().stream().map(this::toLinkDTO).toList()) + .build(); } public ResourceDefinitionDTO toDTO( ResourceDefinition resourceDefinition, List targetClassUris ) { - return new ResourceDefinitionDTO( - resourceDefinition.getUuid(), - resourceDefinition.getName(), - resourceDefinition.getUrlPrefix(), - resourceDefinition.getMetadataSchemaUuids(), - targetClassUris, - resourceDefinition.getChildren(), - resourceDefinition.getExternalLinks() - ); + return ResourceDefinitionDTO.builder() + .uuid(resourceDefinition.getUuid()) + .name(resourceDefinition.getName()) + .urlPrefix(resourceDefinition.getUrlPrefix()) + .targetClassUris(targetClassUris) + .metadataSchemaUuids( + resourceDefinition + .getMetadataSchemaUsages() + .stream() + .map(usage -> usage.getUsedMetadataSchema().getUuid()) + .toList() + ) + .children(resourceDefinition.getChildren().stream().map(this::toChildDTO).toList()) + .externalLinks(resourceDefinition.getExternalLinks().stream().map(this::toLinkDTO).toList()) + .build(); + } + + private ResourceDefinitionLinkDTO toLinkDTO(ResourceDefinitionLink link) { + return ResourceDefinitionLinkDTO.builder() + .title(link.getTitle()) + .propertyUri(link.getPropertyUri()) + .build(); + } + + private ResourceDefinitionChildDTO toChildDTO(ResourceDefinitionChild child) { + return ResourceDefinitionChildDTO.builder() + .resourceDefinitionUuid(child.getTarget().getUuid()) + .relationUri(child.getRelationUri()) + .listView( + ResourceDefinitionChildListViewDTO.builder() + .title(child.getTitle()) + .tagsUri(child.getTagsUri()) + .metadata(child.getMetadata().stream().map(this::toChildMetadataDTO).toList()) + .build() + ) + .build(); + } + + private ResourceDefinitionChildListViewMetadataDTO toChildMetadataDTO(ResourceDefinitionChildMetadata metadata) { + return ResourceDefinitionChildListViewMetadataDTO.builder() + .title(metadata.getTitle()) + .propertyUri(metadata.getPropertyUri()) + .build(); + } + + public MetadataSchemaUsage toUsage(MetadataSchema schema, ResourceDefinition definition, int orderPriority) { + return MetadataSchemaUsage.builder() + .uuid(UUID.randomUUID()) + .usedMetadataSchema(schema) + .resourceDefinition(definition) + .orderPriority(orderPriority) + .build(); + } + + public ResourceDefinitionLink toLink( + ResourceDefinitionLinkDTO dto, ResourceDefinition definition, int orderPriority + ) { + return ResourceDefinitionLink.builder() + .uuid(UUID.randomUUID()) + .title(dto.getTitle()) + .propertyUri(dto.getPropertyUri()) + .resourceDefinition(definition) + .orderPriority(orderPriority) + .createdAt(definition.getCreatedAt()) + .updatedAt(definition.getUpdatedAt()) + .build(); + } + + public ResourceDefinitionChild toChild( + ResourceDefinitionChildDTO dto, ResourceDefinition source, ResourceDefinition target, int orderPriority + ) { + return ResourceDefinitionChild.builder() + .uuid(UUID.randomUUID()) + .relationUri(dto.getRelationUri()) + .title(dto.getListView().getTitle()) + .tagsUri(dto.getListView().getTagsUri()) + .source(source) + .target(target) + .orderPriority(orderPriority) + .createdAt(source.getCreatedAt()) + .updatedAt(source.getUpdatedAt()) + .build(); + } + + public ResourceDefinitionChildMetadata toChildMetadata( + ResourceDefinitionChildListViewMetadataDTO dto, ResourceDefinitionChild child, int orderPriority + ) { + return ResourceDefinitionChildMetadata.builder() + .uuid(UUID.randomUUID()) + .title(dto.getTitle()) + .propertyUri(dto.getPropertyUri()) + .child(child) + .orderPriority(orderPriority) + .createdAt(child.getCreatedAt()) + .updatedAt(child.getUpdatedAt()) + .build(); } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionService.java b/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionService.java index dbdd1191d..092cb9f3e 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionService.java @@ -22,54 +22,66 @@ */ package nl.dtls.fairdatapoint.service.resource; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.resource.ResourceDefinitionChangeDTO; +import nl.dtls.fairdatapoint.api.dto.resource.ResourceDefinitionChildDTO; import nl.dtls.fairdatapoint.api.dto.resource.ResourceDefinitionDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.ResourceDefinitionRepository; +import nl.dtls.fairdatapoint.database.db.repository.*; import nl.dtls.fairdatapoint.entity.exception.ResourceNotFoundException; +import nl.dtls.fairdatapoint.entity.resource.MetadataSchemaUsage; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; +import nl.dtls.fairdatapoint.entity.resource.ResourceDefinitionChild; +import nl.dtls.fairdatapoint.entity.resource.ResourceDefinitionLink; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; import nl.dtls.fairdatapoint.service.membership.MembershipService; import nl.dtls.fairdatapoint.service.openapi.OpenApiService; -import org.springframework.beans.factory.annotation.Autowired; +import nl.dtls.fairdatapoint.service.schema.MetadataSchemaService; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; import org.springframework.validation.BindException; import java.util.*; -import java.util.stream.Collectors; import static java.lang.String.format; @Service +@RequiredArgsConstructor public class ResourceDefinitionService { - @Autowired @Qualifier("persistentUrl") - private String persistentUrl; + private final String persistentUrl; - @Autowired - private ResourceDefinitionRepository resourceDefinitionRepository; + private final ResourceDefinitionRepository resourceDefinitionRepository; - @Autowired - private ResourceDefinitionValidator resourceDefinitionValidator; + private final ResourceDefinitionChildRepository childRepository; - @Autowired - private ResourceDefinitionMapper resourceDefinitionMapper; + private final ResourceDefinitionChildMetadataRepository childMetadataRepository; - @Autowired - private ResourceDefinitionCache resourceDefinitionCache; + private final ResourceDefinitionLinkRepository linkRepository; - @Autowired - private ResourceDefinitionTargetClassesCache targetClassesCache; + private final MetadataSchemaUsageRepository usageRepository; - @Autowired - private MembershipService membershipService; + private final ResourceDefinitionValidator resourceDefinitionValidator; - @Autowired - private OpenApiService openApiService; + private final ResourceDefinitionMapper mapper; + + private final ResourceDefinitionCache resourceDefinitionCache; + + private final ResourceDefinitionTargetClassesCache targetClassesCache; + + private final MetadataSchemaService metadataSchemaService; + + private final MembershipService membershipService; + + private final OpenApiService openApiService; + + private final EntityManager entityManager; public ResourceDefinitionDTO toDTO(ResourceDefinition definition) { - return resourceDefinitionMapper.toDTO(definition, getTargetClassUris(definition)); + return mapper.toDTO(definition, getTargetClassUris(definition)); } public List getAll() { @@ -80,11 +92,17 @@ public List getAll() { .toList(); } - public Optional getByUuid(String uuid) { + public Optional getByUuid(UUID uuid) { return resourceDefinitionRepository.findByUuid(uuid); } - public Optional getDTOByUuid(String uuid) { + public ResourceDefinition getByUuidOrThrow(UUID uuid) { + return resourceDefinitionRepository + .findByUuid(uuid) + .orElseThrow(() -> new ResourceNotFoundException(format("Resource Definition ('%s') not found", uuid))); + } + + public Optional getDTOByUuid(UUID uuid) { return getByUuid(uuid).map(this::toDTO); } @@ -113,15 +131,15 @@ public ResourceDefinition getByUrlPrefix(String urlPrefix) { return definition.get(); } + @Transactional @PreAuthorize("hasRole('ADMIN')") public ResourceDefinitionDTO create(ResourceDefinitionChangeDTO reqDto) throws BindException { - final String uuid = UUID.randomUUID().toString(); - final ResourceDefinition definition = resourceDefinitionMapper.fromChangeDTO(reqDto, uuid); + resourceDefinitionValidator.validate(null, reqDto); - // TODO: check if schemas exist + final ResourceDefinition definition = resourceDefinitionRepository.saveAndFlush(mapper.fromChangeDTO(reqDto)); + entityManager.refresh(definition); + createDependents(definition, reqDto); - resourceDefinitionValidator.validate(definition); - resourceDefinitionRepository.save(definition); resourceDefinitionCache.computeCache(); targetClassesCache.computeCache(); @@ -130,30 +148,33 @@ public ResourceDefinitionDTO create(ResourceDefinitionChangeDTO reqDto) throws B return toDTO(definition); } + @Transactional @PreAuthorize("hasRole('ADMIN')") - public Optional update(String uuid, ResourceDefinitionChangeDTO reqDto) + public Optional update(UUID uuid, ResourceDefinitionChangeDTO reqDto) throws BindException { final Optional optionalDefinition = resourceDefinitionRepository.findByUuid(uuid); if (optionalDefinition.isEmpty()) { return Optional.empty(); } + resourceDefinitionValidator.validate(uuid, reqDto); final ResourceDefinition definition = optionalDefinition.get(); - final ResourceDefinition updatedDefinition = - resourceDefinitionMapper.fromChangeDTO(reqDto, definition.getUuid()); - updatedDefinition.setId(definition.getId()); + deleteDependents(definition); - // TODO: check if schemas exist + final ResourceDefinition updatedDefinition = resourceDefinitionRepository.saveAndFlush( + mapper.fromChangeDTO(reqDto, definition) + ); + entityManager.refresh(updatedDefinition); + createDependents(updatedDefinition, reqDto); - resourceDefinitionValidator.validate(updatedDefinition); - resourceDefinitionRepository.save(updatedDefinition); resourceDefinitionCache.computeCache(); targetClassesCache.computeCache(); openApiService.updateGenericPaths(updatedDefinition); return Optional.of(updatedDefinition).map(this::toDTO); } + @Transactional @PreAuthorize("hasRole('ADMIN')") - public boolean deleteByUuid(String uuid) { + public boolean deleteByUuid(UUID uuid) { // 1. Get resource definition final Optional oRd = resourceDefinitionRepository.findByUuid(uuid); if (oRd.isEmpty()) { @@ -162,23 +183,15 @@ public boolean deleteByUuid(String uuid) { final ResourceDefinition rd = oRd.get(); // 2. Delete from parent resource definitions - final Set rdParents = resourceDefinitionCache.getParentsByUuid(rd.getUuid()); - rdParents.forEach(definition -> { - final ResourceDefinition rdParent = resourceDefinitionRepository.findByUuid(definition.getUuid()).get(); - rdParent.setChildren( - rdParent.getChildren() - .stream() - .filter(child -> !child.getResourceDefinitionUuid().equals(rd.getUuid())) - .collect(Collectors.toList()) - ); - resourceDefinitionRepository.save(rdParent); - }); + rd.getParents().forEach(this::deleteChild); - // 3. Delete resource definition + // 3. Delete resource definition (incl. children and links) + deleteDependents(rd); resourceDefinitionRepository.delete(rd); // 4. Delete entity from membership membershipService.removeFromMembership(rd); + entityManager.flush(); // 5. Recompute cache resourceDefinitionCache.computeCache(); @@ -189,12 +202,71 @@ public boolean deleteByUuid(String uuid) { return true; } + @Transactional + @PreAuthorize("hasRole('ADMIN')") + protected void createDependents(ResourceDefinition definition, ResourceDefinitionChangeDTO reqDto) { + // Get metadata schemas + final List schemas = metadataSchemaService.getAll(reqDto.getMetadataSchemaUuids()); + if (reqDto.getMetadataSchemaUuids().size() > schemas.size()) { + throw new ResourceNotFoundException( + format("Some of the metadata schemas do not exist: %s", reqDto.getMetadataSchemaUuids()) + ); + } + // Create usages + final List usages = new ArrayList<>(); + for (int index = 0; index < schemas.size(); index++) { + usages.add(mapper.toUsage(schemas.get(index), definition, index)); + } + usageRepository.saveAllAndFlush(usages); + + // Create links + final List links = new ArrayList<>(); + for (int index = 0; index < reqDto.getExternalLinks().size(); index++) { + links.add(mapper.toLink(reqDto.getExternalLinks().get(index), definition, index)); + } + linkRepository.saveAllAndFlush(links); + + // Create children + metadata + for (int index = 0; index < reqDto.getChildren().size(); index++) { + final ResourceDefinitionChildDTO dto = reqDto.getChildren().get(index); + final ResourceDefinition target = getByUuidOrThrow(dto.getResourceDefinitionUuid()); + final ResourceDefinitionChild child = childRepository.saveAndFlush( + mapper.toChild(dto, definition, target, index) + ); + + child.setMetadata(new ArrayList<>()); + for (int index2 = 0; index2 < dto.getListView().getMetadata().size(); index2++) { + child.getMetadata() + .add(mapper.toChildMetadata(dto.getListView().getMetadata().get(index2), child, index2)); + } + childMetadataRepository.saveAllAndFlush(child.getMetadata()); + } + } + + @Transactional + @PreAuthorize("hasRole('ADMIN')") + protected void deleteDependents(ResourceDefinition resourceDefinition) { + resourceDefinition.getChildren().forEach(this::deleteChild); + linkRepository.deleteAll(resourceDefinition.getExternalLinks()); + usageRepository.deleteAll(resourceDefinition.getMetadataSchemaUsages()); + entityManager.flush(); + entityManager.refresh(resourceDefinition); + } + + @Transactional + @PreAuthorize("hasRole('ADMIN')") + protected void deleteChild(ResourceDefinitionChild child) { + childMetadataRepository.deleteAll(child.getMetadata()); + childRepository.delete(child); + } + public List getTargetClassUris(ResourceDefinition resourceDefinition) { - final List result = targetClassesCache.getByUuid(resourceDefinition.getUuid()); + final Set result = targetClassesCache + .getByUuid(resourceDefinition.getUuid().toString()); if (result == null) { targetClassesCache.computeCache(); - return targetClassesCache.getByUuid(resourceDefinition.getUuid()); + return targetClassesCache.getByUuid(resourceDefinition.getUuid().toString()).stream().toList(); } - return result; + return result.stream().toList(); } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionTargetClassesCache.java b/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionTargetClassesCache.java index 628c48785..c78506cf8 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionTargetClassesCache.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionTargetClassesCache.java @@ -23,11 +23,8 @@ package nl.dtls.fairdatapoint.service.resource; import jakarta.annotation.PostConstruct; -import nl.dtls.fairdatapoint.database.mongo.repository.ResourceDefinitionRepository; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaRepository; -import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; -import org.springframework.beans.factory.annotation.Autowired; +import lombok.RequiredArgsConstructor; +import nl.dtls.fairdatapoint.database.db.repository.*; import org.springframework.cache.Cache; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.stereotype.Service; @@ -37,16 +34,18 @@ import static nl.dtls.fairdatapoint.config.CacheConfig.RESOURCE_DEFINITION_TARGET_CLASSES_CACHE; @Service +@RequiredArgsConstructor public class ResourceDefinitionTargetClassesCache { - @Autowired - private ConcurrentMapCacheManager cacheManager; + private final ConcurrentMapCacheManager cacheManager; - @Autowired - private ResourceDefinitionRepository resourceDefinitionRepository; + private final ResourceDefinitionRepository resourceDefinitionRepository; - @Autowired - private MetadataSchemaRepository metadataSchemaRepository; + private final MetadataSchemaRepository metadataSchemaRepository; + + private final MetadataSchemaUsageRepository usageRepository; + + private final MetadataSchemaExtensionRepository extensionRepository; @PostConstruct public void computeCache() { @@ -57,45 +56,59 @@ public void computeCache() { cache.clear(); // Add to cache - final List rds = resourceDefinitionRepository.findAll(); - final Map metadataSchemaMap = new HashMap<>(); - metadataSchemaRepository.findAllByLatestIsTrue().forEach(schema -> { - final boolean isNewer = Optional.ofNullable(metadataSchemaMap.get(schema.getUuid())) - .map(otherSchema -> otherSchema.getVersion().compareTo(schema.getVersion()) < 0) - .orElse(false); - if (!metadataSchemaMap.containsKey(schema.getUuid()) || isNewer) { - metadataSchemaMap.put(schema.getUuid(), schema); - } + // - Get all latest metadata schemas and organize them by schema UUID + final Map metadataSchemas = new HashMap<>(); + metadataSchemaRepository.getBasicLatestMetadataSchemas().forEach(schema -> { + metadataSchemas.put(schema.getUuid(), schema); + }); + + // - Get all extensions + final Map> extensions = new HashMap<>(); + metadataSchemas.forEach((schemaUuid, schema) -> { + extensions.put(schemaUuid, new HashSet<>()); + }); + extensionRepository.getBasicExtensionsForLatest().forEach(extension -> { + extensions.get(extension.getSchemaUuid()).add(extension.getExtendedMetadataSchemaUuid()); + }); + + // - Resolve target classes + final Map> targetClasses = new HashMap<>(); + metadataSchemas.forEach((schemaUuid, schema) -> { + targetClasses.put(schemaUuid, new HashSet<>(schema.getTargetClasses())); }); - rds.forEach(resourceDefinition -> { - final Set targetClassUris = new HashSet<>(); - resourceDefinition.getMetadataSchemaUuids().forEach(schemaUuid -> { - if (metadataSchemaMap.containsKey(schemaUuid)) { - targetClassUris.addAll(metadataSchemaMap.get(schemaUuid).getTargetClasses()); - final Queue parentUuids = - new LinkedList<>(metadataSchemaMap.get(schemaUuid).getExtendSchemas()); - final Set visitedParents = new HashSet<>(); - String parentUuid = null; - while (!parentUuids.isEmpty()) { - parentUuid = parentUuids.poll(); - if (!visitedParents.contains(parentUuid)) { - visitedParents.add(parentUuid); - targetClassUris.addAll( - metadataSchemaMap.get(parentUuid).getTargetClasses() - ); - parentUuids.addAll( - metadataSchemaMap.get(parentUuid).getExtendSchemas() - ); - } - } + metadataSchemas.forEach((schemaUuid, schema) -> { + final Queue parentUuids = new LinkedList<>(extensions.get(schemaUuid)); + final Set visitedParents = new HashSet<>(); + UUID parentUuid = null; + while (!parentUuids.isEmpty()) { + parentUuid = parentUuids.poll(); + if (!visitedParents.contains(parentUuid)) { + visitedParents.add(parentUuid); + targetClasses.get(schemaUuid).addAll(metadataSchemas.get(parentUuid).getTargetClasses()); + parentUuids.addAll(extensions.get(parentUuid)); } - }); - cache.put(resourceDefinition.getUuid(), targetClassUris.stream().toList()); + } + }); + + // - Resolve for resource definitions + final Map> resourceDefinitionTargetClasses = new HashMap<>(); + resourceDefinitionRepository.findAll().forEach(resourceDefinition -> { + resourceDefinitionTargetClasses.put(resourceDefinition.getUuid(), new HashSet<>()); + }); + usageRepository.getBasicUsages().forEach(usage -> { + resourceDefinitionTargetClasses + .get(usage.getResourceDefinitionUuid()) + .addAll(targetClasses.get(usage.getSchemaUuid())); + }); + + // - Add to cache + resourceDefinitionTargetClasses.forEach((resourceDefinitionUuid, classes) -> { + cache.put(resourceDefinitionUuid.toString(), classes); }); } - public List getByUuid(String uuid) { - return cache().get(uuid, List.class); + public Set getByUuid(String uuid) { + return cache().get(uuid, Set.class); } private Cache cache() { diff --git a/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionValidator.java b/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionValidator.java index 2124e1fb5..625c4f284 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionValidator.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionValidator.java @@ -22,40 +22,44 @@ */ package nl.dtls.fairdatapoint.service.resource; -import nl.dtls.fairdatapoint.database.mongo.repository.ResourceDefinitionRepository; +import lombok.RequiredArgsConstructor; +import nl.dtls.fairdatapoint.api.dto.resource.ResourceDefinitionChangeDTO; +import nl.dtls.fairdatapoint.api.dto.resource.ResourceDefinitionChildDTO; +import nl.dtls.fairdatapoint.database.db.repository.ResourceDefinitionRepository; import nl.dtls.fairdatapoint.entity.exception.ValidationException; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinitionChild; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.validation.BindException; import java.util.List; import java.util.Optional; +import java.util.UUID; import static nl.dtls.fairdatapoint.util.ValidationUtil.uniquenessValidationFailed; @Service +@RequiredArgsConstructor public class ResourceDefinitionValidator { - @Autowired - private ResourceDefinitionRepository resourceDefinitionRepository; + private static final String ERR_DEP_CYCLE = "Detect dependency cycle through child"; - @Autowired - private ResourceDefinitionCache resourceDefinitionCache; + private final ResourceDefinitionRepository resourceDefinitionRepository; - public void validate(ResourceDefinition reqDto) throws BindException { + private final ResourceDefinitionCache resourceDefinitionCache; + + public void validate(UUID uuid, ResourceDefinitionChangeDTO reqDto) throws BindException { // Check uniqueness final Optional resourceDefinitionByName = resourceDefinitionRepository.findByName(reqDto.getName()); if (resourceDefinitionByName.isPresent() - && !resourceDefinitionByName.get().getUuid().equals(reqDto.getUuid())) { + && !resourceDefinitionByName.get().getUuid().equals(uuid)) { uniquenessValidationFailed("name", reqDto); } final Optional resourceDefinitionByPrefix = resourceDefinitionRepository.findByUrlPrefix(reqDto.getUrlPrefix()); if (resourceDefinitionByPrefix.isPresent() - && !resourceDefinitionByPrefix.get().getUuid().equals(reqDto.getUuid())) { + && !resourceDefinitionByPrefix.get().getUuid().equals(uuid)) { uniquenessValidationFailed("urlPrefix", reqDto); } @@ -65,30 +69,47 @@ public void validate(ResourceDefinition reqDto) throws BindException { } // Check existence of connected entities - for (ResourceDefinitionChild child : reqDto.getChildren()) { + for (ResourceDefinitionChildDTO child : reqDto.getChildren()) { if (resourceDefinitionCache.getByUuid(child.getResourceDefinitionUuid()) == null) { throw new ValidationException("Child doesn't exist"); } } // Check existence of dependency cycles - validateDependencyCycles(reqDto, reqDto.getChildren()); + validateDependencyCyclesChildDTO(uuid, reqDto.getChildren()); + } + + private void validateDependencyCyclesChildDTO( + UUID uuid, List children + ) { + for (ResourceDefinitionChildDTO child : children) { + final UUID childUuid = child.getResourceDefinitionUuid(); + if (childUuid.equals(uuid)) { + throw new ValidationException(ERR_DEP_CYCLE); + } + + final ResourceDefinition rdChild = resourceDefinitionCache.getByUuid(childUuid); + if (rdChild.getChildren().isEmpty()) { + return; + } + validateDependencyCyclesChild(uuid, rdChild.getChildren()); + } } - private void validateDependencyCycles( - ResourceDefinition reqDto, List children + private void validateDependencyCyclesChild( + UUID uuid, List children ) { for (ResourceDefinitionChild child : children) { - final String childUuid = child.getResourceDefinitionUuid(); - if (reqDto.getUuid().equals(childUuid)) { - throw new ValidationException("Detect dependency cycle through child"); + final UUID childUuid = child.getTarget().getUuid(); + if (childUuid.equals(uuid)) { + throw new ValidationException(ERR_DEP_CYCLE); } final ResourceDefinition rdChild = resourceDefinitionCache.getByUuid(childUuid); if (rdChild.getChildren().isEmpty()) { return; } - validateDependencyCycles(reqDto, rdChild.getChildren()); + validateDependencyCyclesChild(uuid, rdChild.getChildren()); } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/schema/MetadataSchemaMapper.java b/src/main/java/nl/dtls/fairdatapoint/service/schema/MetadataSchemaMapper.java index b0b0c9800..17b195b8c 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/schema/MetadataSchemaMapper.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/schema/MetadataSchemaMapper.java @@ -23,38 +23,38 @@ package nl.dtls.fairdatapoint.service.schema; import nl.dtls.fairdatapoint.api.dto.schema.*; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaDraft; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaType; -import nl.dtls.fairdatapoint.entity.schema.SemVer; +import nl.dtls.fairdatapoint.entity.schema.*; import org.springframework.stereotype.Service; import java.time.Instant; import java.util.Collections; import java.util.List; +import java.util.UUID; @Service public class MetadataSchemaMapper { - public MetadataSchemaDraft fromChangeDTO(MetadataSchemaChangeDTO dto, String uuid) { - final Instant now = Instant.now(); - return MetadataSchemaDraft.builder() - .uuid(uuid) + public MetadataSchemaVersion fromChangeDTO( + MetadataSchemaChangeDTO dto, MetadataSchema schema + ) { + return MetadataSchemaVersion.builder() + .uuid(UUID.randomUUID()) .name(dto.getName()) .description(dto.getDescription()) .abstractSchema(dto.isAbstractSchema()) + .type(MetadataSchemaType.CUSTOM) + .state(MetadataSchemaState.DRAFT) + .version("0.0.0") .definition(dto.getDefinition()) - .targetClasses(MetadataSchemaShaclUtils.extractTargetClasses(dto.getDefinition())) - .extendSchemas(dto.getExtendsSchemaUuids()) + .targetClasses(MetadataSchemaShaclUtils.extractTargetClasses(dto.getDefinition()).stream().toList()) .suggestedResourceName(dto.getSuggestedResourceName()) .suggestedUrlPrefix(dto.getSuggestedUrlPrefix()) - .createdAt(now) - .updatedAt(now) + .schema(schema) .build(); } - public MetadataSchemaDraft fromChangeDTO( - MetadataSchemaChangeDTO dto, MetadataSchemaDraft draft + public MetadataSchemaVersion fromChangeDTO( + MetadataSchemaChangeDTO dto, MetadataSchemaVersion draft ) { return draft @@ -63,18 +63,19 @@ public MetadataSchemaDraft fromChangeDTO( .abstractSchema(dto.isAbstractSchema()) .description(dto.getDescription()) .definition(dto.getDefinition()) - .extendSchemas(dto.getExtendsSchemaUuids()) .targetClasses( MetadataSchemaShaclUtils .extractTargetClasses(dto.getDefinition()) + .stream().toList() ) .suggestedResourceName(dto.getSuggestedResourceName()) .suggestedUrlPrefix(dto.getSuggestedUrlPrefix()) + .updatedAt(Instant.now()) .build(); } public MetadataSchemaDraftDTO toDraftDTO( - MetadataSchemaDraft draft, MetadataSchema lastVersion + MetadataSchemaVersion draft ) { return MetadataSchemaDraftDTO.builder() .uuid(draft.getUuid()) @@ -82,32 +83,42 @@ public MetadataSchemaDraftDTO toDraftDTO( .description(draft.getDescription()) .abstractSchema(draft.isAbstractSchema()) .definition(draft.getDefinition()) - .extendsSchemaUuids(draft.getExtendSchemas()) + .extendsSchemaUuids( + draft.getExtensions() + .stream() + .map(extension -> extension.getExtendedMetadataSchema().getUuid()) + .toList() + ) .suggestedResourceName(draft.getSuggestedResourceName()) .suggestedUrlPrefix(draft.getSuggestedUrlPrefix()) - .lastVersion(lastVersion == null ? null : lastVersion.getVersionString()) + .lastVersion(draft.getPreviousVersion() == null ? null : draft.getPreviousVersion().getVersion()) .build(); } - public MetadataSchemaDraftDTO toDraftDTO(MetadataSchema schema) { + public MetadataSchemaDraftDTO toNewDraftDTO(MetadataSchemaVersion schema) { return MetadataSchemaDraftDTO.builder() - .uuid(schema.getUuid()) + .uuid(schema.getSchema().getUuid()) .name(schema.getName()) .description(schema.getDescription()) .abstractSchema(schema.isAbstractSchema()) .definition(schema.getDefinition()) - .extendsSchemaUuids(schema.getExtendSchemas()) + .extendsSchemaUuids( + schema.getExtensions() + .stream() + .map(extension -> extension.getExtendedMetadataSchema().getUuid()) + .toList() + ) .suggestedResourceName(schema.getSuggestedResourceName()) .suggestedUrlPrefix(schema.getSuggestedUrlPrefix()) - .lastVersion(schema.getVersionString()) + .lastVersion(schema.getVersion()) .build(); } - public MetadataSchemaVersionDTO toVersionDTO(MetadataSchema schema) { + public MetadataSchemaVersionDTO toVersionDTO(MetadataSchemaVersion schema) { return MetadataSchemaVersionDTO.builder() - .uuid(schema.getUuid()) - .versionUuid(schema.getVersionUuid()) - .version(schema.getVersion().toString()) + .uuid(schema.getSchema().getUuid()) + .versionUuid(schema.getUuid()) + .version(schema.getVersion()) .name(schema.getName()) .description(schema.getDescription()) .published(schema.isPublished()) @@ -118,61 +129,64 @@ public MetadataSchemaVersionDTO toVersionDTO(MetadataSchema schema) { .importedFrom(schema.getImportedFrom()) .definition(schema.getDefinition()) .targetClasses(schema.getTargetClasses()) - .extendsSchemaUuids(schema.getExtendSchemas()) + .extendsSchemaUuids( + schema.getExtensions() == null + ? + List.of() + : + schema.getExtensions() + .stream() + .map(extension -> extension.getExtendedMetadataSchema().getUuid()) + .toList() + ) .suggestedResourceName(schema.getSuggestedResourceName()) .suggestedUrlPrefix(schema.getSuggestedUrlPrefix()) - .previousVersionUuid(schema.getPreviousVersionUuid()) + .previousVersionUuid(schema.getPreviousVersion() == null ? null : schema.getPreviousVersion().getUuid()) .build(); } - public MetadataSchema fromReleaseDTO( - MetadataSchemaReleaseDTO reqDto, MetadataSchemaDraft draft, String versionUuid + public MetadataSchemaVersion fromReleaseDTO( + MetadataSchemaReleaseDTO reqDto, MetadataSchemaVersion draft ) { - return MetadataSchema.builder() - .uuid(draft.getUuid()) - .versionUuid(versionUuid) - .version(new SemVer(reqDto.getVersion())) - .versionString(reqDto.getVersion()) + return draft.toBuilder() + .version(reqDto.getVersion()) + .state(MetadataSchemaState.LATEST) .type(MetadataSchemaType.CUSTOM) .origin(null) - .name(draft.getName()) .description(reqDto.getDescription()) - .definition(draft.getDefinition()) - .targetClasses(draft.getTargetClasses()) - .extendSchemas(draft.getExtendSchemas()) - .abstractSchema(draft.isAbstractSchema()) .published(reqDto.isPublished()) - .latest(true) - .previousVersionUuid(null) - .suggestedResourceName(draft.getSuggestedResourceName()) - .suggestedUrlPrefix(draft.getSuggestedUrlPrefix()) - .createdAt(Instant.now()) + .updatedAt(Instant.now()) .build(); } public MetadataSchemaDTO toDTO( - MetadataSchema latest, - MetadataSchemaDraft draft, - List schemaVersions, - List childSchemas + MetadataSchemaVersion latest, + MetadataSchemaVersion draft, + List schemaVersions, + List childSchemas ) { if (latest != null) { return MetadataSchemaDTO.builder() - .uuid(latest.getUuid()) + .uuid(latest.getSchema().getUuid()) .name(latest.getName()) .latest(toVersionDTO(latest)) - .draft(draft == null ? null : toDraftDTO(draft, latest)) + .draft(draft == null ? null : toDraftDTO(draft)) .versions(schemaVersions .stream() - .map(MetadataSchema::getVersion) + .map(MetadataSchemaVersion::getSemVer) .sorted() .map(SemVer::toString) .toList() ) - .extendSchemaUuids(latest.getExtendSchemas()) + .extendSchemaUuids(latest + .getExtensions() + .stream() + .map(extension -> extension.getExtendedMetadataSchema().getUuid()) + .toList() + ) .childSchemaUuids(childSchemas .stream() - .map(MetadataSchema::getUuid) + .map(child -> child.getSchema().getUuid()) .distinct() .toList() ) @@ -180,16 +194,16 @@ public MetadataSchemaDTO toDTO( } if (draft != null) { return MetadataSchemaDTO.builder() - .uuid(draft.getUuid()) + .uuid(draft.getSchema().getUuid()) .name(draft.getName()) .latest(null) - .draft(toDraftDTO(draft, latest)) + .draft(toDraftDTO(draft)) .versions(schemaVersions - .stream() - .map(MetadataSchema::getVersion) - .sorted() - .map(SemVer::toString) - .toList() + .stream() + .map(MetadataSchemaVersion::getSemVer) + .sorted() + .map(SemVer::toString) + .toList() ) .extendSchemaUuids(Collections.emptyList()) .childSchemaUuids(Collections.emptyList()) @@ -198,7 +212,7 @@ public MetadataSchemaDTO toDTO( return null; } - public MetadataSchema fromUpdateDTO(MetadataSchema schema, MetadataSchemaUpdateDTO reqDto) { + public MetadataSchemaVersion fromUpdateDTO(MetadataSchemaVersion schema, MetadataSchemaUpdateDTO reqDto) { return schema .toBuilder() @@ -208,22 +222,20 @@ public MetadataSchema fromUpdateDTO(MetadataSchema schema, MetadataSchemaUpdateD .build(); } - public MetadataSchemaDraft toDraft(MetadataSchema schema) { - return MetadataSchemaDraft.builder() + public MetadataSchemaVersion toDraft(MetadataSchemaVersion schema) { + return MetadataSchemaVersion.builder() .uuid(schema.getUuid()) .name(schema.getName()) - .name(schema.getName()) .description(schema.getDescription()) .abstractSchema(schema.isAbstractSchema()) .definition(schema.getDefinition()) - .extendSchemas(schema.getExtendSchemas()) .suggestedResourceName(schema.getSuggestedResourceName()) .suggestedUrlPrefix(schema.getSuggestedUrlPrefix()) .build(); } public MetadataSchemaVersionDTO toPublishedVersionDTO( - MetadataSchema schema, String persistentUrl + MetadataSchemaVersion schema, String persistentUrl ) { final MetadataSchemaVersionDTO dto = toVersionDTO(schema); if (dto.getOrigin() == null) { @@ -233,46 +245,64 @@ public MetadataSchemaVersionDTO toPublishedVersionDTO( return dto; } - public MetadataSchema fromRemoteVersion(MetadataSchemaVersionDTO remoteVersion) { - return MetadataSchema.builder() - .uuid(remoteVersion.getUuid()) - .versionUuid(remoteVersion.getVersionUuid()) + public MetadataSchemaVersion fromRemoteVersion(MetadataSchema schema, MetadataSchemaVersionDTO remoteVersion) { + return MetadataSchemaVersion.builder() + .uuid(remoteVersion.getVersionUuid()) .name(remoteVersion.getName()) .description(remoteVersion.getDescription()) .definition(remoteVersion.getDefinition()) - .versionString(remoteVersion.getVersion()) + .version(remoteVersion.getVersion()) .origin(remoteVersion.getOrigin()) .importedFrom(remoteVersion.getImportedFrom()) - .extendSchemas(remoteVersion.getExtendsSchemaUuids()) - .targetClasses(remoteVersion.getTargetClasses()) + .targetClasses(remoteVersion.getTargetClasses().stream().toList()) .abstractSchema(remoteVersion.isAbstractSchema()) .published(false) .suggestedResourceName(remoteVersion.getSuggestedResourceName()) .suggestedUrlPrefix(remoteVersion.getSuggestedUrlPrefix()) .type(MetadataSchemaType.REFERENCE) - .previousVersionUuid(remoteVersion.getPreviousVersionUuid()) - .createdAt(Instant.now()) + .schema(schema) .build(); } - public MetadataSchema fromRemoteVersion( - MetadataSchemaVersionDTO remoteVersion, MetadataSchema schema + public MetadataSchemaVersion fromRemoteVersion( + MetadataSchema schema, MetadataSchemaVersionDTO remoteVersion, MetadataSchemaVersion version ) { - return schema.toBuilder() + return version.toBuilder() .name(remoteVersion.getName()) .description(remoteVersion.getDescription()) .definition(remoteVersion.getDefinition()) - .extendSchemas(remoteVersion.getExtendsSchemaUuids()) .type(MetadataSchemaType.REFERENCE) - .targetClasses(remoteVersion.getTargetClasses()) + .targetClasses(remoteVersion.getTargetClasses().stream().toList()) .abstractSchema(remoteVersion.isAbstractSchema()) - .published(schema.isPublished()) + .published(version.isPublished()) .origin(remoteVersion.getOrigin()) .importedFrom(remoteVersion.getImportedFrom()) .suggestedUrlPrefix(remoteVersion.getSuggestedUrlPrefix()) .suggestedResourceName(remoteVersion.getSuggestedResourceName()) - .versionString(remoteVersion.getVersion()) - .createdAt(Instant.now()) + .version(remoteVersion.getVersion()) + .schema(schema) + .updatedAt(Instant.now()) + .build(); + } + + public MetadataSchema newSchema(UUID uuid) { + return MetadataSchema.builder() + .uuid(uuid) + .build(); + } + + public MetadataSchema newSchema() { + return newSchema(UUID.randomUUID()); + } + + public MetadataSchemaExtension newExtension( + MetadataSchemaVersion version, MetadataSchema metadataSchema, int orderPriority + ) { + return MetadataSchemaExtension.builder() + .uuid(UUID.randomUUID()) + .extendedMetadataSchema(metadataSchema) + .metadataSchemaVersion(version) + .orderPriority(orderPriority) .build(); } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/schema/MetadataSchemaService.java b/src/main/java/nl/dtls/fairdatapoint/service/schema/MetadataSchemaService.java index 63fc3b531..f0e904200 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/schema/MetadataSchemaService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/schema/MetadataSchemaService.java @@ -22,22 +22,23 @@ */ package nl.dtls.fairdatapoint.service.schema; -import jakarta.validation.Valid; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import nl.dtls.fairdatapoint.api.dto.schema.*; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaDraftRepository; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaRepository; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaExtensionRepository; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaRepository; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaUsageRepository; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaVersionRepository; import nl.dtls.fairdatapoint.entity.exception.ResourceNotFoundException; import nl.dtls.fairdatapoint.entity.exception.ValidationException; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaDraft; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaType; -import nl.dtls.fairdatapoint.entity.schema.SemVer; +import nl.dtls.fairdatapoint.entity.resource.MetadataSchemaUsage; +import nl.dtls.fairdatapoint.entity.schema.*; import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionTargetClassesCache; import nl.dtls.fairdatapoint.util.RdfIOUtil; import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.impl.LinkedHashModel; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.stereotype.Service; @@ -52,218 +53,258 @@ import static java.util.stream.Collectors.groupingBy; import static java.util.stream.Collectors.toMap; -@Service @Slf4j +@Service +@RequiredArgsConstructor public class MetadataSchemaService { private static final String MSG_ERROR_PARENTS_PUBLISH = "Cannot publish as not all parents (via extends) are published"; - @Autowired - private MetadataSchemaRepository metadataSchemaRepository; + private final MetadataSchemaRepository schemaRepository; + + private final MetadataSchemaVersionRepository versionRepository; - @Autowired - private MetadataSchemaDraftRepository metadataSchemaDraftRepository; + private final MetadataSchemaUsageRepository usageRepository; - @Autowired - private MetadataSchemaMapper metadataSchemaMapper; + private final MetadataSchemaExtensionRepository extensionRepository; - @Autowired - private MetadataSchemaValidator metadataSchemaValidator; + private final MetadataSchemaMapper metadataSchemaMapper; - @Autowired - private ResourceDefinitionTargetClassesCache targetClassesCache; + private final MetadataSchemaValidator metadataSchemaValidator; - @Autowired - private String persistentUrl; + private final ResourceDefinitionTargetClassesCache targetClassesCache; + + private final String persistentUrl; + + private final EntityManager entityManager; // =============================================================================================== // Schema drafts + @Transactional @PreAuthorize("hasRole('ADMIN')") public MetadataSchemaDraftDTO createSchemaDraft(MetadataSchemaChangeDTO reqDto) { - final String uuid = UUID.randomUUID().toString(); - // Validate metadataSchemaValidator.validateAllExist(reqDto.getExtendsSchemaUuids()); + final List extendedSchemas = getAll(reqDto.getExtendsSchemaUuids()); + + // create new MetadataSchema (bundle) + final MetadataSchema schema = schemaRepository.saveAndFlush(metadataSchemaMapper.newSchema()); + entityManager.refresh(schema); + // create new MetadataSchemaVersion (draft) + final MetadataSchemaVersion draft = versionRepository + .saveAndFlush(metadataSchemaMapper.fromChangeDTO(reqDto, schema)); + + // create Extensions + draft.setExtensions(new ArrayList<>()); + for (int index = 0; index < extendedSchemas.size(); index++) { + draft.getExtensions().add(metadataSchemaMapper.newExtension(draft, extendedSchemas.get(index), index)); + } + extensionRepository.saveAllAndFlush(draft.getExtensions()); - final MetadataSchemaDraft draft = metadataSchemaMapper.fromChangeDTO(reqDto, uuid); - metadataSchemaDraftRepository.save(draft); - return metadataSchemaMapper.toDraftDTO(draft, null); + return metadataSchemaMapper.toDraftDTO(draft); } @PreAuthorize("hasRole('ADMIN')") - public Optional getSchemaDraft(String uuid) { - final Optional oDraft = metadataSchemaDraftRepository.findByUuid(uuid); - final Optional oLatest = metadataSchemaRepository.findByUuidAndLatestIsTrue(uuid); + public Optional getSchemaDraft(UUID uuid) { + final Optional oDraft = versionRepository.getDraftBySchemaUuid(uuid); + final Optional oLatest = versionRepository.getLatestBySchemaUuid(uuid); if (oDraft.isPresent()) { - return oDraft.map(draft -> metadataSchemaMapper.toDraftDTO(draft, oLatest.orElse(null))); + return oDraft.map(metadataSchemaMapper::toDraftDTO); } - return oLatest.map(latest -> metadataSchemaMapper.toDraftDTO(latest)); + return oLatest.map(metadataSchemaMapper::toNewDraftDTO); } + @Transactional @PreAuthorize("hasRole('ADMIN')") - public Optional updateSchemaDraft(String uuid, MetadataSchemaChangeDTO reqDto) { - final Optional oDraft = metadataSchemaDraftRepository.findByUuid(uuid); - final Optional oSchema = metadataSchemaRepository.findByUuidAndLatestIsTrue(uuid); - final MetadataSchemaDraft baseDraft; + public Optional updateSchemaDraft(UUID uuid, MetadataSchemaChangeDTO reqDto) { + final Optional oDraft = versionRepository.getDraftBySchemaUuid(uuid); + final Optional oLatest = versionRepository.getLatestBySchemaUuid(uuid); + final MetadataSchemaVersion baseDraft; // Check if present if (oDraft.isPresent()) { baseDraft = oDraft.get(); } else { - if (oSchema.isEmpty()) { + if (oLatest.isEmpty()) { return empty(); } - baseDraft = metadataSchemaMapper.toDraft(oSchema.get()); + baseDraft = metadataSchemaMapper.toDraft(oLatest.get()); } // Validate metadataSchemaValidator.validateAllExist(reqDto.getExtendsSchemaUuids()); metadataSchemaValidator.validateNoExtendsCycle(uuid, reqDto.getExtendsSchemaUuids()); + final List extendedSchemas = getAll(reqDto.getExtendsSchemaUuids()); // Save - final MetadataSchemaDraft updatedDraft = metadataSchemaMapper.fromChangeDTO(reqDto, baseDraft); - metadataSchemaDraftRepository.save(updatedDraft); - return of(metadataSchemaMapper.toDraftDTO(updatedDraft, oSchema.orElse(null))); + final MetadataSchemaVersion updatedDraft = versionRepository.saveAndFlush( + metadataSchemaMapper.fromChangeDTO(reqDto, baseDraft) + ); + + // Update schema extensions + extensionRepository.deleteAll(updatedDraft.getExtensions()); + extensionRepository.saveAllAndFlush(extendedSchemas.stream().map(schema -> { + return metadataSchemaMapper.newExtension(updatedDraft, schema, 0); + }).toList()); + + entityManager.refresh(updatedDraft); + + return of(metadataSchemaMapper.toDraftDTO(updatedDraft)); } + @Transactional @PreAuthorize("hasRole('ADMIN')") - public boolean deleteSchemaDraft(String uuid) { - final Optional oDraft = metadataSchemaDraftRepository.findByUuid(uuid); + public boolean deleteSchemaDraft(UUID uuid) { + final Optional oDraft = versionRepository.getDraftBySchemaUuid(uuid); if (oDraft.isEmpty()) { return false; } - metadataSchemaDraftRepository.delete(oDraft.get()); + final MetadataSchemaVersion draft = oDraft.get(); + final boolean isOnlyVersion = draft.getSchema().getVersions().size() == 1; + extensionRepository.deleteAll(draft.getExtensions()); + versionRepository.delete(draft); + + if (isOnlyVersion) { + usageRepository.deleteAll(draft.getSchema().getUsages()); + extensionRepository.deleteAll(draft.getSchema().getExtensions()); + schemaRepository.delete(draft.getSchema()); + } return true; } @PreAuthorize("hasRole('ADMIN')") - public Optional releaseDraft(String uuid, MetadataSchemaReleaseDTO reqDto) { - final Optional oDraft = metadataSchemaDraftRepository.findByUuid(uuid); + public Optional releaseDraft(UUID uuid, MetadataSchemaReleaseDTO reqDto) { + final Optional oDraft = versionRepository.getDraftBySchemaUuid(uuid); // Check if present if (oDraft.isEmpty()) { return empty(); } // Update - final MetadataSchemaDraft draft = oDraft.get(); - final String versionUuid = UUID.randomUUID().toString(); - final MetadataSchema newLatest = metadataSchemaMapper.fromReleaseDTO(reqDto, draft, versionUuid); - final Optional oLatest = metadataSchemaRepository.findByUuidAndLatestIsTrue(uuid); - oLatest.map(MetadataSchema::getVersionUuid).ifPresent(newLatest::setPreviousVersionUuid); - // Validate & Save - metadataSchemaValidator.validateAllExist(newLatest.getExtendSchemas()); + final MetadataSchemaVersion newLatest = metadataSchemaMapper.fromReleaseDTO(reqDto, oDraft.get()); + final Optional oLatest = Optional.ofNullable(newLatest.getPreviousVersion()); // validate all parents are published if publishing if (reqDto.isPublished()) { - final List parents = resolveExtends(draft); - if (!parents.stream().allMatch(MetadataSchema::isPublished)) { + final List parents = resolveExtends(newLatest); + if (!parents.stream().allMatch(MetadataSchemaVersion::isPublished)) { throw new ValidationException(MSG_ERROR_PARENTS_PUBLISH); } } if (oLatest.isPresent()) { - final MetadataSchema oldLatest = oLatest.get(); - oldLatest.setLatest(false); + final MetadataSchemaVersion oldLatest = oLatest.get(); + oldLatest.setState(MetadataSchemaState.LEGACY); metadataSchemaValidator.validate(newLatest, oldLatest); - metadataSchemaRepository.save(oldLatest); + versionRepository.save(oldLatest); } else { metadataSchemaValidator.validate(newLatest); } - metadataSchemaRepository.save(newLatest); - metadataSchemaDraftRepository.delete(draft); + versionRepository.save(newLatest); // Update cache targetClassesCache.computeCache(); - final List versions = metadataSchemaRepository.findByUuid(uuid); - final List childs = metadataSchemaRepository.findAllByExtendSchemasContains(uuid); - return of(metadataSchemaMapper.toDTO(newLatest, draft, versions, childs)); + final List versions = versionRepository.getBySchemaUuid(uuid); + final List childs = extensionRepository + .findByExtendedMetadataSchema(newLatest.getSchema()) + .stream() + .map(MetadataSchemaExtension::getMetadataSchemaVersion) + .toList(); + return of(metadataSchemaMapper.toDTO(newLatest, null, versions, childs)); } // =============================================================================================== // Schema versions - private Optional getByUuidAndVersion(String uuid, String version) { + private Optional getByUuidAndVersion(UUID uuid, String version) { if (Objects.equals(version, "latest")) { - return metadataSchemaRepository.findByUuidAndLatestIsTrue(uuid); + return versionRepository.getLatestBySchemaUuid(uuid); } - return metadataSchemaRepository.findByUuidAndVersionString(uuid, version); + return versionRepository.getBySchemaUuidAndVersion(uuid, version); } - public Optional getVersion(String uuid, String version) { + public Optional getVersion(UUID uuid, String version) { return getByUuidAndVersion(uuid, version).map(metadataSchemaMapper::toVersionDTO); } @PreAuthorize("hasRole('ADMIN')") public Optional updateVersion( - String uuid, String version, MetadataSchemaUpdateDTO reqDto + UUID uuid, String version, MetadataSchemaUpdateDTO reqDto ) { - final Optional oSchema = getByUuidAndVersion(uuid, version); + final Optional oSchema = getByUuidAndVersion(uuid, version); if (oSchema.isEmpty()) { return empty(); } - final MetadataSchema schema = oSchema.get(); + final MetadataSchemaVersion schema = oSchema.get(); // validate all parents are published if publishing if (!schema.isPublished() && reqDto.isPublished()) { - final List parents = resolveExtends(schema); - if (!parents.stream().allMatch(MetadataSchema::isPublished)) { + final List parents = resolveExtends(schema); + if (!parents.stream().allMatch(MetadataSchemaVersion::isPublished)) { throw new ValidationException(MSG_ERROR_PARENTS_PUBLISH); } } // result - final MetadataSchema updatedSchema = - metadataSchemaRepository.save(metadataSchemaMapper.fromUpdateDTO(schema, reqDto)); + final MetadataSchemaVersion updatedSchema = + versionRepository.saveAndFlush(metadataSchemaMapper.fromUpdateDTO(schema, reqDto)); return of(metadataSchemaMapper.toVersionDTO(updatedSchema)); } + @Transactional @PreAuthorize("hasRole('ADMIN')") - public boolean deleteVersion(String uuid, String version) { - final Optional oSchema = getByUuidAndVersion(uuid, version); + public boolean deleteVersion(UUID uuid, String version) { + final Optional oSchema = getByUuidAndVersion(uuid, version); // Check if present if (oSchema.isEmpty()) { return false; } // Validate and fix links - final MetadataSchema schema = oSchema.get(); - MetadataSchema previous = null; - if (schema.getPreviousVersionUuid() != null) { - previous = metadataSchemaRepository.findByVersionUuid(schema.getPreviousVersionUuid()).orElse(null); - } - final Optional oNewer = - metadataSchemaRepository.findByPreviousVersionUuid(schema.getVersionUuid()); + final MetadataSchemaVersion schema = oSchema.get(); if (schema.isLatest()) { - if (previous == null) { - metadataSchemaValidator.validateNotUsed(uuid); + if (schema.getPreviousVersion() == null) { + metadataSchemaValidator.validateNotUsed(schema.getSchema()); } else { - previous.setLatest(true); - metadataSchemaValidator.validateNoExtendsCycle(uuid, previous.getExtendSchemas()); - metadataSchemaRepository.save(previous); + schema.getPreviousVersion().setState(MetadataSchemaState.LATEST); + metadataSchemaValidator.validateNoExtendsCycle(uuid, + schema.getExtensions() + .stream() + .map(extension -> extension.getExtendedMetadataSchema().getUuid()) + .toList()); + versionRepository.save(schema.getPreviousVersion()); } } - else if (oNewer.isPresent()) { - final MetadataSchema newer = oNewer.get(); - newer.setPreviousVersionUuid(previous == null ? null : previous.getVersionUuid()); - metadataSchemaRepository.save(newer); + if (schema.getNextVersion() != null) { + schema.getNextVersion().setPreviousVersion(schema.getPreviousVersion()); + versionRepository.save(schema.getNextVersion()); + } + + final boolean isOnlyVersion = schema.getSchema().getVersions().size() == 1; + versionRepository.delete(schema); + if (isOnlyVersion) { + usageRepository.deleteAll(schema.getSchema().getUsages()); + extensionRepository.deleteAll(schema.getSchema().getExtensions()); + schemaRepository.delete(schema.getSchema()); } - metadataSchemaRepository.delete(schema); return true; } + @Transactional @PreAuthorize("hasRole('ADMIN')") - public boolean deleteSchemaFull(String uuid) { - final List schemas = metadataSchemaRepository.findByUuid(uuid); - final Optional oDraft = metadataSchemaDraftRepository.findByUuid(uuid); + public boolean deleteSchemaFull(UUID uuid) { + final Optional oSchema = schemaRepository.findByUuid(uuid); // Check if present - if (schemas.isEmpty() && oDraft.isEmpty()) { + if (oSchema.isEmpty()) { return false; } + final MetadataSchema schema = oSchema.get(); // Validate - metadataSchemaValidator.validateNotUsed(uuid); - if (schemas.stream().anyMatch(schema -> schema.getType() == MetadataSchemaType.INTERNAL)) { + metadataSchemaValidator.validateNotUsed(schema); + if (schema.getVersions().stream().anyMatch(version -> version.getType() == MetadataSchemaType.INTERNAL)) { throw new ValidationException("You can't delete INTERNAL Shape"); } // Delete - if (!schemas.isEmpty()) { - metadataSchemaRepository.deleteAll(schemas); - } - oDraft.ifPresent(draft -> metadataSchemaDraftRepository.delete(draft)); + versionRepository.deleteAll(schema.getVersions()); + extensionRepository.deleteAll(schema.getExtensions()); + usageRepository.deleteAll(schema.getUsages()); + schemaRepository.delete(schema); + entityManager.flush(); // Update cache targetClassesCache.computeCache(); return true; @@ -273,41 +314,49 @@ public boolean deleteSchemaFull(String uuid) { // Reading schemas public List getSchemasWithoutDrafts(boolean includeAbstract) { - return metadataSchemaRepository - .findAllByLatestIsTrue() + return versionRepository + .findAllByState(MetadataSchemaState.LATEST) .stream() .filter(schema -> includeAbstract || !schema.isAbstractSchema()) .map(schema -> { - final List versions = - metadataSchemaRepository.findByUuid(schema.getUuid()); - final List children = - metadataSchemaRepository.findAllByExtendSchemasContains(schema.getUuid()); + final List versions = + schema.getSchema().getVersions(); + final List children = + extensionRepository + .findByExtendedMetadataSchema(schema.getSchema()) + .stream().map(MetadataSchemaExtension::getMetadataSchemaVersion) + .toList(); return metadataSchemaMapper.toDTO(schema, null, versions, children); }) .toList(); } public List getSchemasWithDrafts(boolean includeAbstract) { - final Set listedUuids = new HashSet<>(); - final Stream schemas = metadataSchemaRepository - .findAllByLatestIsTrue() + final Set listedUuids = new HashSet<>(); + final Stream schemas = versionRepository + .findAllByState(MetadataSchemaState.LATEST) .stream() .filter(schema -> includeAbstract || !schema.isAbstractSchema()) .map(schema -> { - final List versions = metadataSchemaRepository.findByUuid(schema.getUuid()); - final List children = - metadataSchemaRepository.findAllByExtendSchemasContains(schema.getUuid()); - final Optional oDraft = - metadataSchemaDraftRepository.findByUuid(schema.getUuid()); - listedUuids.add(schema.getUuid()); + final List versions = + schema.getSchema().getVersions(); + final List children = + extensionRepository + .findByExtendedMetadataSchema(schema.getSchema()) + .stream().map(MetadataSchemaExtension::getMetadataSchemaVersion) + .toList(); + final Optional oDraft = + versionRepository.getDraftBySchemaUuid(schema.getSchema().getUuid()); + listedUuids.add(schema.getSchema().getUuid()); return metadataSchemaMapper.toDTO(schema, oDraft.orElse(null), versions, children); }); - final Stream drafts = metadataSchemaDraftRepository - .findAll() + final Stream drafts = versionRepository + .findAllByState(MetadataSchemaState.DRAFT) .stream() .filter(draft -> { - return !listedUuids.contains(draft.getUuid()) && (includeAbstract || !draft.isAbstractSchema()); + return !listedUuids.contains(draft.getSchema().getUuid()) + && (includeAbstract || !draft.isAbstractSchema()); }) .map(draft -> { return metadataSchemaMapper.toDTO(null, draft, Collections.emptyList(), Collections.emptyList()); @@ -315,84 +364,92 @@ public List getSchemasWithDrafts(boolean includeAbstract) { return Stream.concat(schemas, drafts).toList(); } - public Optional getSchemaByUuid(String uuid) { - final Optional oSchema = metadataSchemaRepository.findByUuidAndLatestIsTrue(uuid); - final Optional oDraft = metadataSchemaDraftRepository.findByUuid(uuid); + public Optional getSchemaByUuid(UUID uuid) { + final Optional oSchema = versionRepository.getLatestBySchemaUuid(uuid); + final Optional oDraft = versionRepository.getDraftBySchemaUuid(uuid); return oSchema.map(schema -> { - final List versions = - metadataSchemaRepository.findByUuid(schema.getUuid()); - final List children = - metadataSchemaRepository.findAllByExtendSchemasContains(schema.getUuid()); + final List versions = + schema.getSchema().getVersions(); + final List children = + extensionRepository + .findByExtendedMetadataSchema(schema.getSchema()) + .stream().map(MetadataSchemaExtension::getMetadataSchemaVersion) + .toList(); return metadataSchemaMapper.toDTO(schema, oDraft.orElse(null), versions, children); }); } - public Optional getSchemaContentByUuid(String uuid) { + public Optional getSchemaContentByUuid(UUID uuid) { // TODO: cache (?) - final Optional oSchema = metadataSchemaRepository.findByUuidAndLatestIsTrue(uuid); + final Optional oSchema = versionRepository.getLatestBySchemaUuid(uuid); if (oSchema.isEmpty()) { return empty(); } - final MetadataSchema schema = oSchema.get(); - final List schemas = resolveExtends(schema); + final MetadataSchemaVersion schema = oSchema.get(); + final List schemas = resolveExtends(schema); return of(mergeSchemaDefinitions(schemas)); } public Model getShaclFromSchemas() { - return mergeSchemaDefinitions(metadataSchemaRepository.findAllByLatestIsTrue()); + return mergeSchemaDefinitions(versionRepository.findAllByState(MetadataSchemaState.LATEST)); } public Model getShaclFromSchemas(MetadataSchemaPreviewRequestDTO reqDto) { return getShaclFromSchemas(reqDto.getMetadataSchemaUuids()); } - public Model getShaclFromSchemas(List metadataSchemaUuids) { - final Set schemaUuids = new HashSet<>(metadataSchemaUuids); - final List schemas = schemaUuids + public Model getShaclFromSchemas(List metadataSchemaUuids) { + final Set schemaUuids = new HashSet<>(metadataSchemaUuids); + final List schemas = schemaUuids .stream() .map(schemaUuid -> { - return metadataSchemaRepository - .findByUuidAndLatestIsTrue(schemaUuid) + return versionRepository + .getLatestBySchemaUuid(schemaUuid) .orElseThrow(() -> raiseNotFound(schemaUuid)); }) .toList(); return mergeSchemaDefinitions(resolveExtends(schemas)); } - private static ResourceNotFoundException raiseNotFound(String schemaUuid) { + public Model getShaclFromSchemaUsages(List usages) { + return getShaclFromSchemas(usages.stream().map(usage -> usage.getUsedMetadataSchema().getUuid()).toList()); + } + + private static ResourceNotFoundException raiseNotFound(UUID schemaUuid) { return new ResourceNotFoundException(format("Metadata schema '%s' not found", schemaUuid)); } // =============================================================================================== // Extends and SHACL manipulation - private List resolveExtends(MetadataSchema schema) { - return resolveExtends(List.of(schema)); - } - - private List resolveExtends(MetadataSchemaDraft draft) { + private List resolveExtends(MetadataSchemaVersion draft) { return resolveExtends( draft - .getExtendSchemas() + .getExtensions() .stream() - .map(schemaUuid -> metadataSchemaRepository.findByUuidAndLatestIsTrue(schemaUuid).orElse(null)) + .map(extension -> { + return versionRepository + .getLatestBySchemaUuid(extension.getExtendedMetadataSchema().getUuid()) + .orElse(null); + }) .toList() ); } - private List resolveExtends(List schemas) { - final Map allSchemas = metadataSchemaRepository - .findAllByLatestIsTrue() + private List resolveExtends(List schemas) { + final Map allSchemas = versionRepository + .findAllByState(MetadataSchemaState.LATEST) .stream() - .collect(Collectors.toMap(MetadataSchema::getUuid, Function.identity())); - final Set addedSchemaUuids = new HashSet<>(); - final List result = new ArrayList<>(); + .collect(Collectors.toMap(MetadataSchemaVersion::getUuid, Function.identity())); + final Set addedSchemaUuids = new HashSet<>(); + final List result = new ArrayList<>(); schemas.forEach(schema -> { addedSchemaUuids.add(schema.getUuid()); result.add(schema); }); int index = 0; while (index < result.size()) { - result.get(index).getExtendSchemas().forEach(extendUuid -> { + result.get(index).getExtensions().forEach(extension -> { + final UUID extendUuid = extension.getExtendedMetadataSchema().getUuid(); if (!addedSchemaUuids.contains(extendUuid) && allSchemas.containsKey(extendUuid)) { result.add(allSchemas.get(extendUuid)); } @@ -402,7 +459,7 @@ private List resolveExtends(List schemas) { return result; } - private Model mergeSchemaDefinitions(List schemas) { + private Model mergeSchemaDefinitions(List schemas) { final Model model = new LinkedHashModel(); schemas.stream() .map(schema -> RdfIOUtil.read(schema.getDefinition(), "")) @@ -414,7 +471,7 @@ private Model mergeSchemaDefinitions(List schemas) { // Importing and sharing public List getPublishedSchemas() { - return metadataSchemaRepository + return versionRepository .findAllByPublishedIsTrue() .stream() .map(schema -> metadataSchemaMapper.toPublishedVersionDTO(schema, persistentUrl)) @@ -422,10 +479,10 @@ public List getPublishedSchemas() { } private MetadataSchemaRemoteDTO toRemoteSchema(MetadataSchemaVersionDTO remoteDto) { - final Optional localVersion = - metadataSchemaRepository.findByVersionUuid(remoteDto.getVersionUuid()); - final List localSchemas = - metadataSchemaRepository.findByUuid(remoteDto.getUuid()); + final Optional localVersion = + versionRepository.findByUuid(remoteDto.getVersionUuid()); + final List localSchemas = + versionRepository.getBySchemaUuid(remoteDto.getUuid()); boolean isDirty = false; MetadataSchemaRemoteState status = MetadataSchemaRemoteState.NOT_IMPORTED; if (localVersion.isPresent()) { @@ -460,12 +517,14 @@ public List getRemoteSchemas(String fdpUrl) { .toList(); } - public List importSchemas(String schemaUuid, List remoteVersions) { + public void importVersions(UUID schemaUuid, List remoteVersions) { // prepare and check local versions - final Map versions = metadataSchemaRepository - .findByUuid(schemaUuid) + final MetadataSchema schema = schemaRepository.findByUuid(schemaUuid) + .orElseThrow(() -> raiseNotFound(schemaUuid)); + final Map versions = versionRepository + .getBySchemaUuid(schemaUuid) .stream() - .collect(toMap(MetadataSchema::getVersionUuid, Function.identity())); + .collect(toMap(MetadataSchemaVersion::getUuid, Function.identity())); if (versions.values().stream().anyMatch(version -> version.getType() == MetadataSchemaType.CUSTOM)) { throw new ValidationException(format("Schema has CUSTOM version(s): %s", schemaUuid)); } @@ -473,52 +532,81 @@ public List importSchemas(String schemaUuid, List { if (versions.containsKey(remoteVersion.getVersionUuid())) { versions.put(remoteVersion.getVersionUuid(), - metadataSchemaMapper.fromRemoteVersion(remoteVersion, + metadataSchemaMapper.fromRemoteVersion(schema, remoteVersion, versions.get(remoteVersion.getVersionUuid()))); } else { - versions.put(remoteVersion.getVersionUuid(), metadataSchemaMapper.fromRemoteVersion(remoteVersion)); + versions.put(remoteVersion.getVersionUuid(), + metadataSchemaMapper.fromRemoteVersion(schema, remoteVersion)); } }); // fix versions chain - final Map versionMap = - versions.values().stream().collect(toMap(MetadataSchema::getVersionString, Function.identity())); + final Map versionMap = + versions.values().stream().collect(toMap(MetadataSchemaVersion::getVersion, Function.identity())); final List versionsSorted = versionMap.keySet().stream().map(SemVer::new).sorted().map(SemVer::toString).toList(); - String previousVersionUuid = null; + MetadataSchemaVersion previousVersion = null; + final List schemaVersions = new ArrayList<>(); for (String version : versionsSorted) { - versionMap.get(version).setPreviousVersionUuid(previousVersionUuid); - versionMap.get(version).setLatest(false); - previousVersionUuid = versionMap.get(version).getVersionUuid(); + versionMap.get(version).setPreviousVersion(previousVersion); + if (previousVersion != null) { + previousVersion.setNextVersion(versionMap.get(version)); + } + versionMap.get(version).setState(MetadataSchemaState.LEGACY); + previousVersion = versionMap.get(version); + schemaVersions.add(previousVersion); } - versionMap.get(versionsSorted.get(versionsSorted.size() - 1)).setLatest(true); - return versionMap.values().stream().toList(); + versionMap.get(versionsSorted.get(versionsSorted.size() - 1)).setState(MetadataSchemaState.LATEST); + schemaVersions.forEach(versionRepository::saveAndFlush); + + // extensions + remoteVersions.forEach(remoteVersion -> { + for (int i = 0; i < remoteVersion.getExtendsSchemaUuids().size(); i++) { + final MetadataSchemaVersion version = versionMap.get(remoteVersion.getVersion()); + final MetadataSchema extend = + schemaRepository.findByUuid(remoteVersion.getExtendsSchemaUuids().get(i)).get(); + extensionRepository.save(metadataSchemaMapper.newExtension(version, extend, i)); + } + }); + entityManager.flush(); + entityManager.clear(); } - public List importSchemas(@Valid List reqDtos) { + @Transactional + public List importSchemas(List reqDtos) { // Validate - reqDtos.forEach(dto -> metadataSchemaValidator.validate(dto)); - final List localLatestSchemas = metadataSchemaRepository.findAllByLatestIsTrue(); - final Map> schemas = + reqDtos.forEach(metadataSchemaValidator::validate); + final List localLatestSchemas = + versionRepository.findAllByState(MetadataSchemaState.LATEST); + final Map> schemas = reqDtos.stream().collect(groupingBy(MetadataSchemaVersionDTO::getUuid)); - final Set toBePresentUuids = localLatestSchemas + final Set toBePresentUuids = localLatestSchemas .stream() - .map(MetadataSchema::getUuid) + .map(MetadataSchemaVersion::extractSchemaUuid) .collect(Collectors.toSet()); + // Create new metadata schemas (root object with matching UUID) + final List newSchemas = schemaRepository.saveAllAndFlush( + reqDtos.stream() + .map(MetadataSchemaVersionDTO::getUuid) + .filter(uuid -> !toBePresentUuids.contains(uuid)) + .collect(Collectors.toSet()) + .stream() + .map(metadataSchemaMapper::newSchema) + .toList() + ); + entityManager.flush(); + // Check extends relations toBePresentUuids.addAll(schemas.keySet()); reqDtos.forEach(dto -> { if (dto.getExtendsSchemaUuids().stream().anyMatch(uuid -> !toBePresentUuids.contains(uuid))) { throw new ValidationException("Missing schema for extends relation"); } }); - final List toSave = new ArrayList<>(); - schemas.forEach((schemaUuid, versions) -> { - toSave.addAll(importSchemas(schemaUuid, versions)); - }); - metadataSchemaRepository.saveAll(toSave); + schemas.forEach(this::importVersions); + entityManager.flush(); return reqDtos - .parallelStream() - .map(version -> metadataSchemaRepository.findByVersionUuid(version.getVersionUuid()).orElse(null)) + .stream() + .map(schema -> versionRepository.findByUuid(schema.getVersionUuid()).orElse(null)) .filter(Objects::nonNull) .map(metadataSchemaMapper::toVersionDTO) .toList(); @@ -526,13 +614,13 @@ public List importSchemas(@Valid List checkForUpdates(String fdpUrl) { try { - final Map> remoteSchemas = MetadataSchemaRetrievalUtils + final Map> remoteSchemas = MetadataSchemaRetrievalUtils .retrievePublishedMetadataSchemas(fdpUrl) .stream() .collect(groupingBy(MetadataSchemaVersionDTO::getUuid)); final List updates = new ArrayList<>(); remoteSchemas.forEach((schemaUuid, remoteVersions) -> { - final List localVersions = metadataSchemaRepository.findByUuid(schemaUuid); + final List localVersions = versionRepository.getBySchemaUuid(schemaUuid); final boolean hasCustom = localVersions .stream() .anyMatch(schema -> schema.getType() == MetadataSchemaType.CUSTOM); @@ -540,9 +628,10 @@ private List checkForUpdates(String fdpUrl) { .stream() .allMatch(schema -> schema.getImportedFrom().equals(fdpUrl)); if (!hasCustom && allImportedFromThis && !localVersions.isEmpty()) { - final Set localVersionUuids = localVersions + final Set localVersionUuids = localVersions .stream() - .map(MetadataSchema::getVersionUuid).collect(Collectors.toSet()); + .map(MetadataSchemaVersion::getUuid) + .collect(Collectors.toSet()); updates.addAll( remoteVersions .stream() @@ -569,15 +658,19 @@ private List checkForUpdates(String fdpUrl) { } public List checkForUpdates() { - final Set importSources = metadataSchemaRepository + final Set importSources = versionRepository .findAllByImportedFromIsNotNull() .stream() - .map(MetadataSchema::getImportedFrom) + .map(MetadataSchemaVersion::getImportedFrom) .collect(Collectors.toSet()); return importSources .stream() .map(this::checkForUpdates) .flatMap(Collection::stream) - .collect(Collectors.toList()); + .toList(); + } + + public List getAll(List metadataSchemaUuids) { + return schemaRepository.findAllById(metadataSchemaUuids); } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/schema/MetadataSchemaValidator.java b/src/main/java/nl/dtls/fairdatapoint/service/schema/MetadataSchemaValidator.java index f7bbb14e2..f513191d0 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/schema/MetadataSchemaValidator.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/schema/MetadataSchemaValidator.java @@ -22,36 +22,34 @@ */ package nl.dtls.fairdatapoint.service.schema; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaChangeDTO; import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaVersionDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaDraftRepository; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaRepository; -import nl.dtls.fairdatapoint.database.mongo.repository.ResourceDefinitionRepository; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaExtensionRepository; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaVersionRepository; import nl.dtls.fairdatapoint.entity.exception.ValidationException; -import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaExtension; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaState; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaVersion; import nl.dtls.fairdatapoint.util.RdfIOUtil; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.List; import java.util.Optional; import java.util.Set; +import java.util.UUID; import java.util.stream.Collectors; import static java.lang.String.format; @Component +@RequiredArgsConstructor public class MetadataSchemaValidator { - @Autowired - private MetadataSchemaDraftRepository metadataSchemaDraftRepository; + private final MetadataSchemaVersionRepository versionRepository; - @Autowired - private MetadataSchemaRepository metadataSchemaRepository; - - @Autowired - private ResourceDefinitionRepository resourceDefinitionRepository; + private final MetadataSchemaExtensionRepository extensionRepository; private void validateShacl(String shaclDefinition) { try { @@ -62,36 +60,41 @@ private void validateShacl(String shaclDefinition) { } } - public void validateNotUsed(String uuid) { - final List resourceDefinitions = - resourceDefinitionRepository.findByMetadataSchemaUuidsIsContaining(uuid); - if (!resourceDefinitions.isEmpty()) { + public void validateNotUsed(MetadataSchema schema) { + if (!schema.getUsages().isEmpty()) { throw new ValidationException( format("Schema is used in %d resource definitions", - resourceDefinitions.size()) + schema.getUsages().size()) ); } - final List children = - metadataSchemaRepository.findAllByExtendSchemasContains(uuid); - if (!children.isEmpty()) { + final List extensions = + extensionRepository.findByExtendedMetadataSchema(schema); + if (!extensions.isEmpty()) { throw new ValidationException( - format("Schema is used in %d other schemas", children.size()) + format("Schema is used in %d other schemas", extensions.size()) ); } } - public void validateNoExtendsCycle(String uuid, List extendSchemaUuids) { + public void validateNoExtendsCycle(UUID uuid, List extendSchemaUuids) { if (extendSchemaUuids.contains(uuid)) { throw new ValidationException("Extends-cycle detected for the metadata schema"); } extendSchemaUuids.forEach(schemaUuid -> { - final Optional oSchema = - metadataSchemaRepository.findByUuidAndLatestIsTrue(schemaUuid); - oSchema.ifPresent(schema -> validateNoExtendsCycle(uuid, schema.getExtendSchemas())); + final Optional oSchema = + versionRepository.getLatestBySchemaUuid(schemaUuid); + oSchema.ifPresent(schema -> { + validateNoExtendsCycle(uuid, + schema.getExtensions() + .stream() + .map(extension -> extension.getExtendedMetadataSchema().getUuid()) + .toList() + ); + }); }); } - public void validate(MetadataSchema newVersion, MetadataSchema previousVersion) { + public void validate(MetadataSchemaVersion newVersion, MetadataSchemaVersion previousVersion) { // Check previous if (previousVersion != null) { if (previousVersion.getVersion().compareTo(newVersion.getVersion()) >= 0) { @@ -105,8 +108,8 @@ public void validate(MetadataSchema newVersion, MetadataSchema previousVersion) validateShacl(newVersion.getDefinition()); } - public void validate(MetadataSchema metadataSchema) { - validate(metadataSchema, null); + public void validate(MetadataSchemaVersion schemaVersion) { + validate(schemaVersion, null); } public void validate(MetadataSchemaVersionDTO reqDto) { @@ -119,11 +122,11 @@ public void validate(MetadataSchemaChangeDTO reqDto) { validateShacl(reqDto.getDefinition()); } - private List getMissingSchemaUuids(List schemasUuids) { - final Set existingUuids = metadataSchemaRepository - .findAllByLatestIsTrue() + private List getMissingSchemaUuids(List schemasUuids) { + final Set existingUuids = versionRepository + .findAllByState(MetadataSchemaState.LATEST) .stream() - .map(MetadataSchema::getUuid) + .map(ver -> ver.getSchema().getUuid()) .collect(Collectors.toSet()); return schemasUuids .stream() @@ -131,8 +134,8 @@ private List getMissingSchemaUuids(List schemasUuids) { .toList(); } - public void validateAllExist(List schemasUuids) { - final List missing = getMissingSchemaUuids(schemasUuids); + public void validateAllExist(List schemasUuids) { + final List missing = getMissingSchemaUuids(schemasUuids); if (!missing.isEmpty()) { throw new ValidationException(format("Metadata schemas not found: %s", missing)); } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/search/SearchFilterCache.java b/src/main/java/nl/dtls/fairdatapoint/service/search/SearchFilterCache.java index 16fb03802..ed59628c8 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/search/SearchFilterCache.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/search/SearchFilterCache.java @@ -23,11 +23,12 @@ package nl.dtls.fairdatapoint.service.search; import jakarta.annotation.PostConstruct; +import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import nl.dtls.fairdatapoint.database.db.repository.SettingsSearchFilterRepository; import nl.dtls.fairdatapoint.entity.search.SearchFilterCacheContainer; import nl.dtls.fairdatapoint.service.label.LabelService; import nl.dtls.fairdatapoint.service.settings.SettingsCache; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.Cache; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.stereotype.Component; @@ -37,24 +38,23 @@ @Component @Slf4j +@RequiredArgsConstructor public class SearchFilterCache { - @Autowired - private ConcurrentMapCacheManager cacheManager; + private final ConcurrentMapCacheManager cacheManager; - @Autowired - private SettingsCache settingsCache; + private final SettingsCache settingsCache; - @Autowired - private LabelService labelService; + private final LabelService labelService; + + private final SettingsSearchFilterRepository settingsSearchFilterRepository; @PostConstruct public void clearCache() { cache().clear(); - settingsCache - .getOrDefaults() - .getSearchFilters() + settingsSearchFilterRepository + .findAll() .forEach(filter -> cache().put(filter.getPredicate(), null)); } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/search/SearchMapper.java b/src/main/java/nl/dtls/fairdatapoint/service/search/SearchMapper.java index 5171bf221..9df94ef49 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/search/SearchMapper.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/search/SearchMapper.java @@ -65,11 +65,11 @@ public SearchFilterDTO toFilterDTO(SettingsSearchFilter filter) { return SearchFilterDTO .builder() .type(filter.getType()) - .queryFromRecords(filter.isQueryFromRecords()) + .queryFromRecords(filter.getQueryRecords()) .predicate(filter.getPredicate()) .label(filter.getLabel()) .values(filter - .getPresetValues() + .getItems() .stream() .map(this::toFilterItemDTO) .toList() diff --git a/src/main/java/nl/dtls/fairdatapoint/service/search/SearchService.java b/src/main/java/nl/dtls/fairdatapoint/service/search/SearchService.java index daa094fe1..ca652abec 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/search/SearchService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/search/SearchService.java @@ -23,6 +23,7 @@ package nl.dtls.fairdatapoint.service.search; import com.google.common.io.Resources; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.search.*; import nl.dtls.fairdatapoint.database.rdf.repository.RepositoryMode; import nl.dtls.fairdatapoint.database.rdf.repository.exception.MetadataRepositoryException; @@ -37,7 +38,6 @@ import org.apache.commons.lang.text.StrSubstitutor; import org.eclipse.rdf4j.query.MalformedQueryException; import org.eclipse.rdf4j.query.parser.sparql.SPARQLParser; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Service; @@ -54,30 +54,25 @@ import static nl.dtls.fairdatapoint.util.ValueFactoryHelper.l; @Service +@RequiredArgsConstructor public class SearchService { private static final String QUERY_TEMPLATE_NAME = "queryTemplate.sparql"; private static final String QUERY_TEMPLATE = loadSparqlQueryTemplate(); - @Autowired - private GenericMetadataRepository metadataRepository; + private final GenericMetadataRepository metadataRepository; - @Autowired - private MetadataStateService metadataStateService; + private final MetadataStateService metadataStateService; - @Autowired - private SearchMapper searchMapper; + private final SearchMapper searchMapper; - @Autowired - private SettingsService settingsService; + private final SettingsService settingsService; - @Autowired - private SearchFilterCache searchFilterCache; + private final SearchFilterCache searchFilterCache; - @Autowired @Qualifier("persistentUrl") - private String persistentUrl; + private final String persistentUrl; public List search( SearchSavedQueryDTO searchSavedQueryDTO @@ -129,7 +124,7 @@ private SearchFilterDTO enrichItems(SettingsSearchFilter filter) { .stream() .map(SearchFilterItemDTO::getValue) .collect(Collectors.toSet()); - if (filter.isQueryFromRecords()) { + if (filter.getQueryRecords()) { final List xvalues = new ArrayList<>(); xvalues.addAll(result.getValues()); xvalues.addAll( diff --git a/src/main/java/nl/dtls/fairdatapoint/service/search/query/SearchSavedQueryMapper.java b/src/main/java/nl/dtls/fairdatapoint/service/search/query/SearchSavedQueryMapper.java index 60eb1607c..19e04157a 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/search/query/SearchSavedQueryMapper.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/search/query/SearchSavedQueryMapper.java @@ -22,26 +22,38 @@ */ package nl.dtls.fairdatapoint.service.search.query; +import lombok.RequiredArgsConstructor; +import nl.dtls.fairdatapoint.api.dto.search.SearchQueryVariablesDTO; import nl.dtls.fairdatapoint.api.dto.search.SearchSavedQueryChangeDTO; import nl.dtls.fairdatapoint.api.dto.search.SearchSavedQueryDTO; -import nl.dtls.fairdatapoint.api.dto.user.UserDTO; import nl.dtls.fairdatapoint.entity.search.SearchSavedQuery; +import nl.dtls.fairdatapoint.entity.user.UserAccount; +import nl.dtls.fairdatapoint.service.user.UserMapper; import org.springframework.stereotype.Component; import java.time.Instant; +import java.util.Optional; import java.util.UUID; @Component +@RequiredArgsConstructor public class SearchSavedQueryMapper { + + private final UserMapper userMapper; + public SearchSavedQueryDTO toDTO( - SearchSavedQuery query, UserDTO userDTO + SearchSavedQuery query ) { return SearchSavedQueryDTO.builder() .uuid(query.getUuid()) .name(query.getName()) .description(query.getDescription()) - .variables(query.getVariables()) - .user(userDTO) + .variables(toVariablesDTO(query)) + .user( + Optional.ofNullable(query.getUserAccount()) + .map(userMapper::toDTO) + .orElse(null) + ) .type(query.getType()) .createdAt(query.getCreatedAt()) .updatedAt(query.getUpdatedAt()) @@ -49,30 +61,45 @@ public SearchSavedQueryDTO toDTO( } public SearchSavedQuery fromChangeDTO( - SearchSavedQueryChangeDTO reqDto, UserDTO userDto + SearchSavedQueryChangeDTO reqDto, UserAccount userAccount ) { return SearchSavedQuery.builder() - .uuid(UUID.randomUUID().toString()) + .uuid(UUID.randomUUID()) .name(reqDto.getName()) .description(reqDto.getDescription()) .type(reqDto.getType()) - .variables(reqDto.getVariables()) - .userUuid(userDto == null ? null : userDto.getUuid()) + .varPrefixes(reqDto.getVariables().getPrefixes()) + .varGraphPattern(reqDto.getVariables().getGraphPattern()) + .varOrdering(reqDto.getVariables().getOrdering()) + .userAccount(userAccount) .createdAt(Instant.now()) .updatedAt(Instant.now()) .build(); } public SearchSavedQuery fromChangeDTO( - SearchSavedQuery query, SearchSavedQueryChangeDTO reqDto + SearchSavedQuery query, SearchSavedQueryChangeDTO reqDto, + UserAccount userAccount ) { return query.toBuilder() .name(reqDto.getName()) .description(reqDto.getDescription()) - .variables(reqDto.getVariables()) - .userUuid(query.getUserUuid()) + .varPrefixes(reqDto.getVariables().getPrefixes()) + .varGraphPattern(reqDto.getVariables().getGraphPattern()) + .varOrdering(reqDto.getVariables().getOrdering()) + .userAccount(userAccount) .type(reqDto.getType()) .updatedAt(Instant.now()) .build(); } + + public SearchQueryVariablesDTO toVariablesDTO( + SearchSavedQuery query + ) { + return SearchQueryVariablesDTO.builder() + .prefixes(query.getVarPrefixes()) + .graphPattern(query.getVarGraphPattern()) + .ordering(query.getVarOrdering()) + .build(); + } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/search/query/SearchSavedQueryService.java b/src/main/java/nl/dtls/fairdatapoint/service/search/query/SearchSavedQueryService.java index 3046fcb35..7ca6bebdf 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/search/query/SearchSavedQueryService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/search/query/SearchSavedQueryService.java @@ -22,77 +22,59 @@ */ package nl.dtls.fairdatapoint.service.search.query; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.search.SearchSavedQueryChangeDTO; import nl.dtls.fairdatapoint.api.dto.search.SearchSavedQueryDTO; -import nl.dtls.fairdatapoint.api.dto.user.UserDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.SearchSavedQueryRepository; +import nl.dtls.fairdatapoint.database.db.repository.SearchSavedQueryRepository; import nl.dtls.fairdatapoint.entity.exception.ForbiddenException; import nl.dtls.fairdatapoint.entity.search.SearchSavedQuery; import nl.dtls.fairdatapoint.entity.search.SearchSavedQueryType; -import nl.dtls.fairdatapoint.entity.user.User; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import nl.dtls.fairdatapoint.entity.user.UserRole; import nl.dtls.fairdatapoint.service.user.CurrentUserService; import nl.dtls.fairdatapoint.service.user.UserService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.function.Function; -import java.util.stream.Collectors; +import java.util.*; @Service +@RequiredArgsConstructor public class SearchSavedQueryService { private static final String MSG_CANNOT_UPDATE = "User is not allowed to update the query"; - @Autowired - private SearchSavedQueryRepository repository; + private final SearchSavedQueryRepository repository; - @Autowired - private SearchSavedQueryMapper mapper; + private final SearchSavedQueryMapper mapper; - @Autowired - private CurrentUserService currentUserService; + private final CurrentUserService currentUserService; - @Autowired - private UserService userService; + private final UserService userService; public List getAll() { - final Optional optionalUser = currentUserService.getCurrentUser(); - final Map userMap = - userService - .getUsers() - .stream() - .collect(Collectors.toMap(UserDTO::getUuid, Function.identity())); + final Optional optionalUser = currentUserService.getCurrentUser(); return repository .findAll() .parallelStream() .filter(query -> canSeeQuery(optionalUser, query)) - .map(query -> mapper.toDTO(query, userMap.get(query.getUserUuid()))) + .map(mapper::toDTO) .toList(); } - public Optional getSingle(String uuid) { - final Optional optionalUser = currentUserService.getCurrentUser(); + public Optional getSingle(UUID uuid) { + final Optional optionalUser = currentUserService.getCurrentUser(); return repository.findByUuid(uuid) .filter(searchSavedQuery -> canSeeQuery(optionalUser, searchSavedQuery)) - .map(searchSavedQuery -> { - final UserDTO userDto = - userService.getUserByUuid(searchSavedQuery.getUserUuid()).orElse(null); - return mapper.toDTO(searchSavedQuery, userDto); - }); + .map(mapper::toDTO); } - public boolean delete(String uuid) { + public boolean delete(UUID uuid) { final Optional optionalSearchQuery = repository.findByUuid(uuid); if (optionalSearchQuery.isEmpty()) { return false; } final SearchSavedQuery searchSavedQuery = optionalSearchQuery.get(); - final Optional optionalUser = currentUserService.getCurrentUser(); + final Optional optionalUser = currentUserService.getCurrentUser(); if (!canManageQuery(optionalUser, searchSavedQuery)) { throw new ForbiddenException(MSG_CANNOT_UPDATE); } @@ -101,38 +83,30 @@ public boolean delete(String uuid) { } public SearchSavedQueryDTO create(SearchSavedQueryChangeDTO reqDto) { - final UserDTO userDto = userService.getCurrentUser().orElse(null); + final UserAccount userAccount = userService.getCurrentUserAccount().orElse(null); final SearchSavedQuery searchSavedQuery = repository.save( - mapper.fromChangeDTO(reqDto, userDto) + mapper.fromChangeDTO(reqDto, userAccount) ); - return mapper.toDTO(searchSavedQuery, userDto); + return mapper.toDTO(searchSavedQuery); } - public Optional update(String uuid, SearchSavedQueryChangeDTO reqDto) { + public Optional update(UUID uuid, SearchSavedQueryChangeDTO reqDto) { final Optional optionalSearchQuery = repository.findByUuid(uuid); if (optionalSearchQuery.isEmpty()) { return Optional.empty(); } - final Optional optionalUser = currentUserService.getCurrentUser(); + final Optional optionalUser = currentUserService.getCurrentUser(); final SearchSavedQuery searchSavedQuery = optionalSearchQuery.get(); if (!canManageQuery(optionalUser, searchSavedQuery)) { throw new ForbiddenException(MSG_CANNOT_UPDATE); } final SearchSavedQuery updatedQuery = repository.save( - mapper.fromChangeDTO(searchSavedQuery, reqDto) - ); - if (updatedQuery.getUserUuid() == null) { - return Optional.of(mapper.toDTO(updatedQuery, null)); - } - return Optional.of(mapper.toDTO( - updatedQuery, - userService - .getUserByUuid(updatedQuery.getUserUuid()) - .orElse(null)) + mapper.fromChangeDTO(searchSavedQuery, reqDto, searchSavedQuery.getUserAccount()) ); + return Optional.of(mapper.toDTO(updatedQuery)); } - private boolean canSeeQuery(Optional optionalUser, SearchSavedQuery query) { + private boolean canSeeQuery(Optional optionalUser, SearchSavedQuery query) { return query.getType().equals(SearchSavedQueryType.PUBLIC) || optionalUser .filter(user -> user.getRole().equals(UserRole.ADMIN)) @@ -142,12 +116,12 @@ private boolean canSeeQuery(Optional optionalUser, SearchSavedQuery query) .isPresent(); } - private boolean isOwnOrInternal(User user, SearchSavedQuery query) { + private boolean isOwnOrInternal(UserAccount user, SearchSavedQuery query) { return query.getType().equals(SearchSavedQueryType.INTERNAL) - || Objects.equals(query.getUserUuid(), user.getUuid()); + || Objects.equals(query.getUserAccount().getUuid(), user.getUuid()); } - private boolean canManageQuery(Optional optionalUser, SearchSavedQuery query) { + private boolean canManageQuery(Optional optionalUser, SearchSavedQuery query) { if (optionalUser.isEmpty()) { return false; } @@ -156,8 +130,8 @@ private boolean canManageQuery(Optional optionalUser, SearchSavedQuery que .isPresent(); } - private boolean isOwner(User user, SearchSavedQuery query) { + private boolean isOwner(UserAccount user, SearchSavedQuery query) { return user.getRole().equals(UserRole.ADMIN) - || Objects.equals(query.getUserUuid(), user.getUuid()); + || Objects.equals(query.getUserAccount().getUuid(), user.getUuid()); } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/security/MongoAuthenticationService.java b/src/main/java/nl/dtls/fairdatapoint/service/security/AuthenticationService.java similarity index 91% rename from src/main/java/nl/dtls/fairdatapoint/service/security/MongoAuthenticationService.java rename to src/main/java/nl/dtls/fairdatapoint/service/security/AuthenticationService.java index 132f118a5..43404f1c9 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/security/MongoAuthenticationService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/security/AuthenticationService.java @@ -22,7 +22,7 @@ */ package nl.dtls.fairdatapoint.service.security; -import org.springframework.beans.factory.annotation.Autowired; +import lombok.RequiredArgsConstructor; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; import org.springframework.security.core.userdetails.UserDetails; @@ -30,12 +30,12 @@ import org.springframework.stereotype.Service; @Service -public class MongoAuthenticationService { +@RequiredArgsConstructor +public class AuthenticationService { private static final String DEFAULT_CREDENTIALS = ""; - @Autowired - private UserDetailsService userDetailsService; + private final UserDetailsService userDetailsService; public Authentication getAuthentication(String userUuid) { final UserDetails userDetails = userDetailsService.loadUserByUsername(userUuid); diff --git a/src/main/java/nl/dtls/fairdatapoint/service/security/MongoUserDetailsService.java b/src/main/java/nl/dtls/fairdatapoint/service/security/UserDetailsServiceImpl.java similarity index 78% rename from src/main/java/nl/dtls/fairdatapoint/service/security/MongoUserDetailsService.java rename to src/main/java/nl/dtls/fairdatapoint/service/security/UserDetailsServiceImpl.java index 92c07ed2e..c8736e864 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/security/MongoUserDetailsService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/security/UserDetailsServiceImpl.java @@ -22,10 +22,10 @@ */ package nl.dtls.fairdatapoint.service.security; -import nl.dtls.fairdatapoint.database.mongo.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; import nl.dtls.fairdatapoint.entity.exception.UnauthorizedException; -import nl.dtls.fairdatapoint.entity.user.User; -import org.springframework.beans.factory.annotation.Autowired; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import org.springframework.security.core.authority.SimpleGrantedAuthority; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; @@ -33,27 +33,28 @@ import java.util.List; import java.util.Optional; +import java.util.UUID; import static java.lang.String.format; @Service -public class MongoUserDetailsService implements UserDetailsService { +@RequiredArgsConstructor +public class UserDetailsServiceImpl implements UserDetailsService { - @Autowired - private UserRepository repository; + private final UserAccountRepository repository; @Override public UserDetails loadUserByUsername(String uuid) { - final Optional oUser = repository.findByUuid(uuid); + final Optional oUser = repository.findByUuid(UUID.fromString(uuid)); if (oUser.isEmpty()) { throw new UnauthorizedException("User not found"); } - final User user = oUser.get(); + final UserAccount user = oUser.get(); final List authorities = List.of( new SimpleGrantedAuthority(format("ROLE_%s", user.getRole().name())) ); return new org.springframework.security.core.userdetails.User( - user.getUuid(), user.getPasswordHash(), authorities + user.getUuid().toString(), user.getPasswordHash(), authorities ); } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/settings/SettingsCache.java b/src/main/java/nl/dtls/fairdatapoint/service/settings/SettingsCache.java index ca1a7cb57..64664db99 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/settings/SettingsCache.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/settings/SettingsCache.java @@ -23,29 +23,38 @@ package nl.dtls.fairdatapoint.service.settings; import jakarta.annotation.PostConstruct; -import nl.dtls.fairdatapoint.database.mongo.repository.SettingsRepository; +import lombok.RequiredArgsConstructor; +import nl.dtls.fairdatapoint.api.controller.settings.SettingsDefaults; +import nl.dtls.fairdatapoint.database.db.repository.SettingsRepository; import nl.dtls.fairdatapoint.entity.settings.Settings; -import org.springframework.beans.factory.annotation.Autowired; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.springframework.cache.Cache; import org.springframework.cache.concurrent.ConcurrentMapCacheManager; import org.springframework.stereotype.Service; +import java.util.Optional; + import static nl.dtls.fairdatapoint.config.CacheConfig.SETTINGS_CACHE; @Service +@RequiredArgsConstructor public class SettingsCache { private static final String SETTINGS_KEY = "settings"; - @Autowired - private ConcurrentMapCacheManager cacheManager; + private final ConcurrentMapCacheManager cacheManager; + + private final SettingsRepository settingsRepository; - @Autowired - private SettingsRepository settingsRepository; + private final SettingsDefaults settingsDefaults; @PostConstruct public void updateCachedSettings() { - updateCachedSettings(settingsRepository.findFirstBy().orElse(Settings.getDefault())); + updateCachedSettings( + settingsRepository + .findByUuid(KnownUUIDs.SETTINGS_UUID) + .orElse(settingsDefaults.getDefaults()) + ); } public void updateCachedSettings(Settings settings) { @@ -60,7 +69,9 @@ public void updateCachedSettings(Settings settings) { } public Settings getOrDefaults() { - return cache().get(SETTINGS_KEY, Settings.class); + return Optional + .ofNullable(cache().get(SETTINGS_KEY, Settings.class)) + .orElse(settingsDefaults.getDefaults()); } private Cache cache() { diff --git a/src/main/java/nl/dtls/fairdatapoint/service/settings/SettingsMapper.java b/src/main/java/nl/dtls/fairdatapoint/service/settings/SettingsMapper.java index 2e4ea7777..9ea5cf3f3 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/settings/SettingsMapper.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/settings/SettingsMapper.java @@ -22,242 +22,184 @@ */ package nl.dtls.fairdatapoint.service.settings; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.search.SearchFilterDTO; import nl.dtls.fairdatapoint.api.dto.search.SearchFilterItemDTO; import nl.dtls.fairdatapoint.api.dto.settings.*; import nl.dtls.fairdatapoint.config.properties.InstanceProperties; import nl.dtls.fairdatapoint.config.properties.PingProperties; +import nl.dtls.fairdatapoint.config.properties.RepositoryConnectionProperties; import nl.dtls.fairdatapoint.config.properties.RepositoryProperties; import nl.dtls.fairdatapoint.entity.settings.*; import nl.dtls.fairdatapoint.service.search.SearchMapper; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; +import java.time.Instant; +import java.util.ArrayList; +import java.util.List; + @Component +@RequiredArgsConstructor public class SettingsMapper { - @Autowired - private InstanceProperties instanceProperties; + private final InstanceProperties instanceProperties; - @Autowired - private PingProperties pingProperties; + private final PingProperties pingProperties; - @Autowired - private RepositoryProperties repositoryProperties; + private final RepositoryProperties repositoryProperties; - @Autowired - private SearchMapper searchMapper; + private final SearchMapper searchMapper; public SettingsDTO toDTO(Settings settings) { - return SettingsDTO - .builder() + return SettingsDTO.builder() + .clientUrl(instanceProperties.getClientUrl()) + .persistentUrl(instanceProperties.getPersistentUrl()) .appTitle(settings.getAppTitle()) .appSubtitle(settings.getAppSubtitle()) .appTitleFromConfig(instanceProperties.getTitle()) .appSubtitleFromConfig(instanceProperties.getSubtitle()) - .clientUrl(instanceProperties.getClientUrl()) - .persistentUrl(instanceProperties.getPersistentUrl()) - .metadataMetrics(settings.getMetadataMetrics()) - .ping(toDTO(settings.getPing())) - .mainRepository(getMainRepositoryDTO()) - .draftsRepository(getDraftsRepositoryDTO()) - .search( - SettingsSearchDTO - .builder() - .filters(settings - .getSearchFilters() - .stream() - .map(this::toDTO) - .toList() - ) + .metadataMetrics(settings.getMetrics().stream().map(this::toMetricDTO).toList()) + .ping(toPingDTO(settings)) + .mainRepository(toRepositoryDTO(repositoryProperties.getMain())) + .draftsRepository(toRepositoryDTO(repositoryProperties.getDrafts())) + .search(toSearchDTO(settings)) + .forms(toFormsDTO(settings)) + .build(); + } + + private SettingsFormsDTO toFormsDTO(Settings settings) { + return SettingsFormsDTO.builder() + .autocomplete( + SettingsFormsAutocompleteDTO.builder() + .searchNamespace(settings.getAutocompleteSearchNamespace()) + .sources(settings.getAutocompleteSources().stream().map(this::toSourceDTO).toList()) .build() ) - .forms(toDTO(settings.getForms())) .build(); } - public SettingsFormsDTO toDTO(SettingsForms forms) { - return SettingsFormsDTO - .builder() - .autocomplete(toDTO(forms.getAutocomplete())) + private SettingsAutocompleteSourceDTO toSourceDTO(SettingsAutocompleteSource source) { + return SettingsAutocompleteSourceDTO.builder() + .rdfType(source.getRdfType()) + .sparqlEndpoint(source.getSparqlEndpoint()) + .sparqlQuery(source.getSparqlQuery()) .build(); } - public SettingsFormsAutocompleteDTO toDTO(SettingsFormsAutocomplete autocomplete) { - return SettingsFormsAutocompleteDTO - .builder() - .searchNamespace(autocomplete.getSearchNamespace()) - .sources(autocomplete.getSources().stream().map(this::toDTO).toList()) + private SettingsSearchDTO toSearchDTO(Settings settings) { + return SettingsSearchDTO.builder() + .filters(settings.getSearchFilters().stream().map(this::toSearchFilterDTO).toList()) .build(); } - public SettingsAutocompleteSourceDTO toDTO(SettingsAutocompleteSource autocomplete) { - return SettingsAutocompleteSourceDTO - .builder() - .rdfType(autocomplete.getRdfType()) - .sparqlEndpoint(autocomplete.getSparqlEndpoint()) - .sparqlQuery(autocomplete.getSparqlQuery()) + private SearchFilterDTO toSearchFilterDTO(SettingsSearchFilter settingsSearchFilter) { + return SearchFilterDTO.builder() + .type(settingsSearchFilter.getType()) + .label(settingsSearchFilter.getLabel()) + .predicate(settingsSearchFilter.getPredicate()) + .queryFromRecords(settingsSearchFilter.getQueryRecords()) + .values(settingsSearchFilter.getItems().stream().map(this::toSearchFilterItemDTO).toList()) .build(); } - public SearchFilterDTO toDTO(SettingsSearchFilter filter) { - return SearchFilterDTO - .builder() - .type(filter.getType()) - .label(filter.getLabel()) - .predicate(filter.getPredicate()) - .values(filter.getPresetValues().stream().map(this::toDTO).toList()) - .queryFromRecords(filter.isQueryFromRecords()) + private SearchFilterItemDTO toSearchFilterItemDTO(SettingsSearchFilterItem settingsSearchFilterItem) { + return SearchFilterItemDTO.builder() + .label(settingsSearchFilterItem.getLabel()) + .value(settingsSearchFilterItem.getValue()) + .preset(true) .build(); } - public SearchFilterItemDTO toDTO(SettingsSearchFilterItem filterItem) { - return SearchFilterItemDTO - .builder() - .label(filterItem.getLabel()) - .value(filterItem.getValue()) - .preset(true) + private SettingsRepositoryDTO toRepositoryDTO(RepositoryConnectionProperties repo) { + return SettingsRepositoryDTO.builder() + .type(repo.getStringType()) + .repository(repo.getRepository()) + .dir(repo.getDir()) + .url(repo.getUrl()) + .username(repo.getUsername()) + .password(redact(repo.getPassword())) .build(); } - public SettingsPingDTO toDTO(SettingsPing settingsPing) { - return SettingsPingDTO - .builder() - .enabled(settingsPing.isEnabled()) - .endpoints(settingsPing.getEndpoints()) + private SettingsPingDTO toPingDTO(Settings settings) { + return SettingsPingDTO.builder() + .enabled(settings.getPingEnabled()) + .endpoints(settings.getPingEndpoints()) .endpointsFromConfig(pingProperties.getEndpoints()) .interval(pingProperties.getInterval().toString()) .build(); } - public SettingsRepositoryDTO getMainRepositoryDTO() { - return SettingsRepositoryDTO - .builder() - .type(repositoryProperties.getMain().getStringType()) - .dir(repositoryProperties.getMain().getDir()) - .url(repositoryProperties.getMain().getUrl()) - .repository(repositoryProperties.getMain().getRepository()) - .username(repositoryProperties.getMain().getUsername()) - .password(redact(repositoryProperties.getMain().getPassword())) + public SettingsMetricDTO toMetricDTO(SettingsMetric metric) { + return SettingsMetricDTO.builder() + .metricUri(metric.getMetricUri()) + .resourceUri(metric.getResourceUri()) .build(); } - public SettingsRepositoryDTO getDraftsRepositoryDTO() { - return SettingsRepositoryDTO - .builder() - .type(repositoryProperties.getDrafts().getStringType()) - .dir(repositoryProperties.getDrafts().getDir()) - .url(repositoryProperties.getDrafts().getUrl()) - .repository(repositoryProperties.getDrafts().getRepository()) - .username(repositoryProperties.getDrafts().getUsername()) - .password(redact(repositoryProperties.getDrafts().getPassword())) - .build(); + private String redact(String secret) { + return secret != null ? "" : null; } public Settings fromUpdateDTO(SettingsUpdateDTO dto, Settings settings) { - return settings - .toBuilder() + return settings.toBuilder() .appTitle(dto.getAppTitle()) .appSubtitle(dto.getAppSubtitle()) - .metadataMetrics(dto.getMetadataMetrics()) - .ping(fromUpdateDTO(dto.getPing(), settings.getPing())) - .searchFilters(dto - .getSearch() - .getFilters() - .stream() - .map(this::fromUpdateDTO) - .toList() - ) - .forms(fromUpdateDTO(dto.getForms(), settings.getForms())) - .build(); - } - - public SettingsSearchFilter fromUpdateDTO(SearchFilterDTO dto) { - return SettingsSearchFilter - .builder() - .type(dto.getType()) - .label(dto.getLabel()) - .predicate(dto.getPredicate()) - .queryFromRecords(dto.isQueryFromRecords()) - .presetValues(dto - .getValues() - .stream() - .map(this::fromUpdateDTO) - .toList() - ) - .build(); - } - - public SettingsSearchFilterItem fromUpdateDTO(SearchFilterItemDTO dto) { - return SettingsSearchFilterItem - .builder() - .label(dto.getLabel()) - .value(dto.getValue()) + .pingEnabled(dto.getPing().isEnabled()) + .pingEndpoints(dto.getPing().getEndpoints()) + .autocompleteSearchNamespace(dto.getForms().getAutocomplete().getSearchNamespace()) + .updatedAt(Instant.now()) .build(); } - public SettingsForms fromUpdateDTO(SettingsFormsDTO dto, SettingsForms forms) { - return forms - .toBuilder() - .autocomplete(fromUpdateDTO(dto.getAutocomplete(), forms.getAutocomplete())) + public SettingsMetric fromMetricDTO(SettingsMetricDTO dto, int orderPriority, Settings settings) { + return SettingsMetric.builder() + .metricUri(dto.getMetricUri()) + .resourceUri(dto.getResourceUri()) + .orderPriority(orderPriority) + .settings(settings) .build(); } - public SettingsFormsAutocomplete fromUpdateDTO( - SettingsFormsAutocompleteDTO dto, SettingsFormsAutocomplete autocomplete + public SettingsAutocompleteSource fromAutocompleteSourceDTO( + SettingsAutocompleteSourceDTO dto, int orderPriority, Settings settings ) { - return autocomplete - .toBuilder() - .searchNamespace(dto.getSearchNamespace()) - .sources(dto.getSources().stream().map(this::fromUpdateDTO).toList()) - .build(); - } - - public SettingsAutocompleteSource fromUpdateDTO(SettingsAutocompleteSourceDTO dto) { - return SettingsAutocompleteSource - .builder() + return SettingsAutocompleteSource.builder() .rdfType(dto.getRdfType()) .sparqlEndpoint(dto.getSparqlEndpoint()) .sparqlQuery(dto.getSparqlQuery()) + .orderPriority(orderPriority) + .settings(settings) .build(); } - public SettingsPing fromUpdateDTO(SettingsPingUpdateDTO dto, SettingsPing settingsPing) { - return settingsPing - .toBuilder() - .enabled(dto.isEnabled()) - .endpoints(dto.getEndpoints()) - .build(); - } - - public SettingsUpdateDTO toUpdateDTO(Settings settings) { - return SettingsUpdateDTO - .builder() - .metadataMetrics(settings.getMetadataMetrics()) - .ping(toUpdateDTO(settings.getPing())) - .search(SettingsSearchDTO - .builder() - .filters(settings - .getSearchFilters() - .stream() - .map(searchMapper::toFilterDTO) - .toList() - ) - .build() - ) - .forms(toDTO(settings.getForms())) + public SettingsSearchFilter fromSearchFilterDTO( + SearchFilterDTO dto, int orderPriority, Settings settings + ) { + final List items = new ArrayList<>(); + final SettingsSearchFilter filter = SettingsSearchFilter.builder() + .queryRecords(dto.isQueryFromRecords()) + .label(dto.getLabel()) + .predicate(dto.getPredicate()) + .type(dto.getType()) + .orderPriority(orderPriority) + .settings(settings) .build(); + for (int index = 0; index < dto.getValues().size(); index++) { + items.add(fromSearchFilterItemDTO(dto.getValues().get(index), index, filter)); + } + filter.setItems(items); + return filter; } - public SettingsPingUpdateDTO toUpdateDTO(SettingsPing settingsPing) { - return SettingsPingUpdateDTO - .builder() - .enabled(settingsPing.isEnabled()) - .endpoints(settingsPing.getEndpoints()) + private SettingsSearchFilterItem fromSearchFilterItemDTO( + SearchFilterItemDTO dto, int orderPriority, SettingsSearchFilter filter + ) { + return SettingsSearchFilterItem.builder() + .label(dto.getLabel()) + .value(dto.getValue()) + .orderPriority(orderPriority) + .filter(filter) .build(); } - - private String redact(String secret) { - return secret != null ? "" : null; - } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/settings/SettingsService.java b/src/main/java/nl/dtls/fairdatapoint/service/settings/SettingsService.java index bd6b959f5..70651b6c8 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/settings/SettingsService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/settings/SettingsService.java @@ -22,32 +22,48 @@ */ package nl.dtls.fairdatapoint.service.settings; +import jakarta.persistence.EntityManager; +import jakarta.transaction.Transactional; +import lombok.RequiredArgsConstructor; +import nl.dtls.fairdatapoint.api.controller.settings.SettingsDefaults; +import nl.dtls.fairdatapoint.api.dto.search.SearchFilterDTO; +import nl.dtls.fairdatapoint.api.dto.settings.SettingsAutocompleteSourceDTO; import nl.dtls.fairdatapoint.api.dto.settings.SettingsDTO; +import nl.dtls.fairdatapoint.api.dto.settings.SettingsMetricDTO; import nl.dtls.fairdatapoint.api.dto.settings.SettingsUpdateDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.SettingsRepository; +import nl.dtls.fairdatapoint.database.db.repository.*; import nl.dtls.fairdatapoint.entity.settings.Settings; +import nl.dtls.fairdatapoint.entity.settings.SettingsAutocompleteSource; +import nl.dtls.fairdatapoint.entity.settings.SettingsMetric; import nl.dtls.fairdatapoint.entity.settings.SettingsSearchFilter; -import nl.dtls.fairdatapoint.service.search.SearchFilterCache; -import org.springframework.beans.factory.annotation.Autowired; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.springframework.stereotype.Service; -import java.util.Set; -import java.util.stream.Collectors; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; @Service +@RequiredArgsConstructor public class SettingsService { - @Autowired - private SettingsRepository repository; + private final SettingsRepository settingsRepository; - @Autowired - private SettingsMapper mapper; + private final SettingsMetricRepository metricRepository; - @Autowired - private SettingsCache settingsCache; + private final SettingsAutocompleteSourceRepository autocompleteSourceRepository; - @Autowired - private SearchFilterCache searchFilterCache; + private final SettingsSearchFilterRepository searchFilterRepository; + + private final SettingsSearchFilterItemRepository searchFilterItemRepository; + + private final SettingsMapper mapper; + + private final SettingsCache settingsCache; + + private final EntityManager entityManager; + + private final SettingsDefaults settingsDefaults; public Settings getOrDefaults() { return settingsCache.getOrDefaults(); @@ -57,39 +73,90 @@ public SettingsDTO getCurrentSettings() { return mapper.toDTO(getOrDefaults()); } + @Transactional public SettingsDTO updateSettings(SettingsUpdateDTO dto) { final Settings oldSettings = getOrDefaults(); - final Settings newSettings = repository.save(mapper.fromUpdateDTO(dto, getOrDefaults())); - handleSearchFiltersChange(oldSettings, newSettings); + + // update Settings + final Settings newSettings = mapper.fromUpdateDTO(dto, oldSettings); + settingsRepository.saveAndFlush(newSettings); + + // update Metrics + final List metrics = updateMetrics(dto, newSettings); + newSettings.setMetrics(metrics); + + // update Autocomplete Sources + final List sources = updateSources(dto, newSettings); + newSettings.setAutocompleteSources(sources); + + // update SearchFilters + final List searchFilters = updateSearchFilters(dto, newSettings); + newSettings.setSearchFilters(searchFilters); + settingsCache.updateCachedSettings(newSettings); return mapper.toDTO(newSettings); } - private void handleSearchFiltersChange(Settings oldSettings, Settings newSettings) { - final Set oldPredicateUris = - oldSettings - .getSearchFilters() - .stream() - .map(SettingsSearchFilter::getPredicate) - .collect(Collectors.toSet()); - final Set newPredicateUris = - newSettings - .getSearchFilters() - .stream() - .map(SettingsSearchFilter::getPredicate) - .collect(Collectors.toSet()); - oldPredicateUris - .stream() - .filter(predicate -> !newPredicateUris.contains(predicate)) - .forEach(searchFilterCache::clearFilter); - newPredicateUris - .stream() - .filter(predicate -> !oldPredicateUris.contains(predicate)) - .forEach(searchFilterCache::clearFilter); + private List updateMetrics(SettingsUpdateDTO dto, Settings settings) { + // Delete old + metricRepository.deleteAll(settings.getMetrics()); + // Add new + final List metrics = new ArrayList<>(); + final List dtos = dto.getMetadataMetrics(); + for (int index = 0; index < dtos.size(); index++) { + metrics.add(mapper.fromMetricDTO(dtos.get(index), index, settings)); + } + return metricRepository.saveAll(metrics); } + private List updateSources(SettingsUpdateDTO dto, Settings settings) { + // Delete old + metricRepository.deleteAll(settings.getMetrics()); + // Add new + final List metrics = new ArrayList<>(); + final List dtos = dto.getForms().getAutocomplete().getSources(); + for (int index = 0; index < dtos.size(); index++) { + metrics.add(mapper.fromAutocompleteSourceDTO(dtos.get(index), index, settings)); + } + return autocompleteSourceRepository.saveAll(metrics); + } + + private List updateSearchFilters(SettingsUpdateDTO dto, Settings settings) { + // Delete old + settings + .getSearchFilters() + .forEach(searchFilter -> searchFilterItemRepository.deleteAll(searchFilter.getItems())); + searchFilterRepository.deleteAll(settings.getSearchFilters()); + // Add new + final List searchFilters = new ArrayList<>(); + final List dtos = dto.getSearch().getFilters(); + for (int index = 0; index < dtos.size(); index++) { + searchFilters.add(mapper.fromSearchFilterDTO(dtos.get(index), index, settings)); + } + searchFilterRepository.saveAllAndFlush(searchFilters); + for (SettingsSearchFilter searchFilter : searchFilters) { + entityManager.refresh(searchFilter); + searchFilterItemRepository.saveAllAndFlush(searchFilter.getItems()); + } + return searchFilters; + } + + @Transactional public SettingsDTO resetSettings() { - return updateSettings(mapper.toUpdateDTO(Settings.getDefault())); + final Optional oldSettings = settingsRepository.findByUuid(KnownUUIDs.SETTINGS_UUID); + + if (oldSettings.isPresent()) { + settingsRepository.delete(oldSettings.get()); + entityManager.flush(); + } + + final Settings newSettings = settingsRepository.saveAndFlush(settingsDefaults.defaultSettings()); + metricRepository.saveAll(settingsDefaults.defaultMetrics(newSettings)); + entityManager.flush(); + entityManager.refresh(newSettings); + + settingsCache.updateCachedSettings(newSettings); + return mapper.toDTO(newSettings); } } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/user/CurrentUserService.java b/src/main/java/nl/dtls/fairdatapoint/service/user/CurrentUserService.java index 27c74227f..5842f22ed 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/user/CurrentUserService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/user/CurrentUserService.java @@ -22,32 +22,33 @@ */ package nl.dtls.fairdatapoint.service.user; -import nl.dtls.fairdatapoint.database.mongo.repository.UserRepository; -import nl.dtls.fairdatapoint.entity.user.User; -import org.springframework.beans.factory.annotation.Autowired; +import lombok.RequiredArgsConstructor; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; import java.util.Optional; +import java.util.UUID; import static java.util.Optional.empty; import static java.util.Optional.of; @Service +@RequiredArgsConstructor public class CurrentUserService { - @Autowired - private UserRepository userRepository; + private final UserAccountRepository userAccountRepository; - public Optional getCurrentUserUuid() { + public Optional getCurrentUserUuid() { final Authentication auth = SecurityContextHolder.getContext().getAuthentication(); if (auth != null) { final Object principal = auth.getPrincipal(); if (principal instanceof org.springframework.security.core.userdetails.User) { return of(((org.springframework.security.core.userdetails.User) principal) - .getUsername()); + .getUsername()).map(UUID::fromString); } } return empty(); @@ -62,8 +63,7 @@ private boolean isAuthorityAdmin(GrantedAuthority authority) { return authority.getAuthority().equals("ROLE_ADMIN"); } - public Optional getCurrentUser() { - return getCurrentUserUuid().flatMap(userRepository::findByUuid); + public Optional getCurrentUser() { + return getCurrentUserUuid().flatMap(userAccountRepository::findByUuid); } - } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/user/UserMapper.java b/src/main/java/nl/dtls/fairdatapoint/service/user/UserMapper.java index 94107ce2f..6fbc3676c 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/user/UserMapper.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/user/UserMapper.java @@ -22,19 +22,21 @@ */ package nl.dtls.fairdatapoint.service.user; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.user.*; -import nl.dtls.fairdatapoint.entity.user.User; -import org.springframework.beans.factory.annotation.Autowired; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import org.springframework.security.crypto.password.PasswordEncoder; -import org.springframework.stereotype.Service; +import org.springframework.stereotype.Component; -@Service +import java.util.UUID; + +@Component +@RequiredArgsConstructor public class UserMapper { - @Autowired - private PasswordEncoder passwordEncoder; + private final PasswordEncoder passwordEncoder; - public UserDTO toDTO(User user) { + public UserDTO toDTO(UserAccount user) { return new UserDTO( user.getUuid(), @@ -44,7 +46,7 @@ public UserDTO toDTO(User user) { user.getRole()); } - public UserSimpleDTO toSimpleDTO(User user) { + public UserSimpleDTO toSimpleDTO(UserAccount user) { return new UserSimpleDTO( user.getUuid(), @@ -53,10 +55,10 @@ public UserSimpleDTO toSimpleDTO(User user) { user.getEmail()); } - public User fromCreateDTO(UserCreateDTO dto, String uuid) { + public UserAccount fromCreateDTO(UserCreateDTO dto) { return - new User( - uuid, + new UserAccount( + UUID.randomUUID(), dto.getFirstName(), dto.getLastName(), dto.getEmail(), @@ -64,7 +66,7 @@ public User fromCreateDTO(UserCreateDTO dto, String uuid) { dto.getRole()); } - public User fromChangeDTO(UserChangeDTO dto, User user) { + public UserAccount fromChangeDTO(UserChangeDTO dto, UserAccount user) { return user .toBuilder() @@ -75,7 +77,7 @@ public User fromChangeDTO(UserChangeDTO dto, User user) { .build(); } - public User fromProfileChangeDTO(UserProfileChangeDTO dto, User user) { + public UserAccount fromProfileChangeDTO(UserProfileChangeDTO dto, UserAccount user) { return user .toBuilder() @@ -85,7 +87,7 @@ public User fromProfileChangeDTO(UserProfileChangeDTO dto, User user) { .build(); } - public User fromPasswordDTO(UserPasswordDTO reqDto, User user) { + public UserAccount fromPasswordDTO(UserPasswordDTO reqDto, UserAccount user) { return user .toBuilder() diff --git a/src/main/java/nl/dtls/fairdatapoint/service/user/UserService.java b/src/main/java/nl/dtls/fairdatapoint/service/user/UserService.java index e5c50d1d1..a88571ef9 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/user/UserService.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/user/UserService.java @@ -22,11 +22,11 @@ */ package nl.dtls.fairdatapoint.service.user; +import lombok.RequiredArgsConstructor; import nl.dtls.fairdatapoint.api.dto.user.*; -import nl.dtls.fairdatapoint.database.mongo.repository.UserRepository; -import nl.dtls.fairdatapoint.entity.user.User; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import nl.dtls.fairdatapoint.service.member.MemberService; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; @@ -39,112 +39,113 @@ import static java.util.Optional.of; @Service +@RequiredArgsConstructor public class UserService { - @Autowired - private UserRepository userRepository; + private final UserAccountRepository userAccountRepository; - @Autowired - private UserMapper userMapper; + private final UserMapper userMapper; - @Autowired - private UserValidator userValidator; + private final UserValidator userValidator; - @Autowired - private MemberService memberService; + private final MemberService memberService; public List getUsers() { return - userRepository + userAccountRepository .findAll() .stream() .map(userMapper::toDTO) .toList(); } - public Optional getUserByUuid(String uuid) { - return - userRepository - .findByUuid(uuid) - .map(userMapper::toDTO); + public Optional getUserAccountByUuid(UUID uuid) { + return userAccountRepository.findByUuid(uuid); + } + + public Optional getUserDtoByUuid(UUID uuid) { + return getUserAccountByUuid(uuid).map(userMapper::toDTO); } - public Optional getCurrentUserUuid() { + public Optional getCurrentUserUuid() { final Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if (principal instanceof org.springframework.security.core.userdetails.User) { return of(((org.springframework.security.core.userdetails.User) principal) - .getUsername()); + .getUsername()).map(UUID::fromString); } return empty(); } - public Optional getCurrentUser() { - return getCurrentUserUuid().flatMap(this::getUserByUuid); + public Optional getCurrentUserAccount() { + return getCurrentUserUuid().flatMap(this::getUserAccountByUuid); + } + + public Optional getCurrentUserDto() { + return getCurrentUserUuid().flatMap(this::getUserDtoByUuid); } @PreAuthorize("hasRole('ADMIN')") public UserDTO createUser(UserCreateDTO reqDto) { userValidator.validateEmail(null, reqDto.getEmail()); - final String uuid = UUID.randomUUID().toString(); - final User user = userMapper.fromCreateDTO(reqDto, uuid); - userRepository.save(user); + final UserAccount user = userMapper.fromCreateDTO(reqDto); + userAccountRepository.save(user); return userMapper.toDTO(user); } @PreAuthorize("hasRole('ADMIN')") - public Optional updateUser(String uuid, UserChangeDTO reqDto) { - final Optional user = userRepository.findByUuid(uuid); + public Optional updateUser(UUID uuid, UserChangeDTO reqDto) { + final Optional user = userAccountRepository.findByUuid(uuid); if (user.isEmpty()) { return empty(); } userValidator.validateEmail(uuid, reqDto.getEmail()); - final User updatedUser = userMapper.fromChangeDTO(reqDto, user.get()); - userRepository.save(updatedUser); + final UserAccount updatedUser = userMapper.fromChangeDTO(reqDto, user.get()); + userAccountRepository.save(updatedUser); return of(userMapper.toDTO(updatedUser)); } public Optional updateCurrentUser(UserProfileChangeDTO reqDto) { - final Optional user = - getCurrentUserUuid().flatMap(uuid -> userRepository.findByUuid(uuid)); + final Optional user = + getCurrentUserUuid().flatMap(userAccountRepository::findByUuid); if (user.isEmpty()) { return empty(); } userValidator.validateEmail(user.get().getUuid(), reqDto.getEmail()); - final User updatedUser = userMapper.fromProfileChangeDTO(reqDto, user.get()); - userRepository.save(updatedUser); + final UserAccount updatedUser = userMapper.fromProfileChangeDTO(reqDto, user.get()); + userAccountRepository.save(updatedUser); return of(userMapper.toDTO(updatedUser)); } @PreAuthorize("hasRole('ADMIN')") - public Optional updatePassword(String uuid, UserPasswordDTO reqDto) { - final Optional user = userRepository.findByUuid(uuid); + public Optional updatePassword(UUID uuid, UserPasswordDTO reqDto) { + final Optional user = userAccountRepository.findByUuid(uuid); if (user.isEmpty()) { return empty(); } - final User updatedUser = userMapper.fromPasswordDTO(reqDto, user.get()); - userRepository.save(updatedUser); + final UserAccount updatedUser = userMapper.fromPasswordDTO(reqDto, user.get()); + userAccountRepository.save(updatedUser); return of(userMapper.toDTO(updatedUser)); } public Optional updatePasswordForCurrentUser(UserPasswordDTO reqDto) { - final Optional user = - getCurrentUserUuid().flatMap(uuid -> userRepository.findByUuid(uuid)); + final Optional user = + getCurrentUserUuid().flatMap(userAccountRepository::findByUuid); if (user.isEmpty()) { return empty(); } - final User updatedUser = userMapper.fromPasswordDTO(reqDto, user.get()); - userRepository.save(updatedUser); + final UserAccount updatedUser = userMapper.fromPasswordDTO(reqDto, user.get()); + userAccountRepository.save(updatedUser); return of(userMapper.toDTO(updatedUser)); } @PreAuthorize("hasRole('ADMIN')") - public boolean deleteUser(String uuid) { - final Optional user = userRepository.findByUuid(uuid); + public boolean deleteUser(UUID uuid) { + final Optional user = userAccountRepository.findByUuid(uuid); if (user.isEmpty()) { return false; } - userRepository.delete(user.get()); + userAccountRepository.delete(user.get()); memberService.deleteMembers(user.get()); return true; } diff --git a/src/main/java/nl/dtls/fairdatapoint/service/user/UserValidator.java b/src/main/java/nl/dtls/fairdatapoint/service/user/UserValidator.java index 986ee0e9d..e17ed4274 100644 --- a/src/main/java/nl/dtls/fairdatapoint/service/user/UserValidator.java +++ b/src/main/java/nl/dtls/fairdatapoint/service/user/UserValidator.java @@ -22,29 +22,29 @@ */ package nl.dtls.fairdatapoint.service.user; -import nl.dtls.fairdatapoint.database.mongo.repository.UserRepository; +import lombok.RequiredArgsConstructor; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; import nl.dtls.fairdatapoint.entity.exception.ValidationException; -import nl.dtls.fairdatapoint.entity.user.User; -import org.springframework.beans.factory.annotation.Autowired; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import org.springframework.stereotype.Service; import java.util.Optional; +import java.util.UUID; import static java.lang.String.format; @Service +@RequiredArgsConstructor public class UserValidator { - @Autowired - private UserRepository userRepository; + private final UserAccountRepository userAccountRepository; - public void validateEmail(String uuid, String email) { - final Optional userEmail = userRepository.findByEmail(email); + public void validateEmail(UUID uuid, String email) { + final Optional userEmail = userAccountRepository.findByEmail(email); if (userEmail.isPresent() && !userEmail.get().getUuid().equals(uuid)) { throw new ValidationException( format("Email '%s' is already taken", email) ); } } - } diff --git a/src/main/java/nl/dtls/fairdatapoint/util/KnownUUIDs.java b/src/main/java/nl/dtls/fairdatapoint/util/KnownUUIDs.java index 9824653e7..dedb08a16 100644 --- a/src/main/java/nl/dtls/fairdatapoint/util/KnownUUIDs.java +++ b/src/main/java/nl/dtls/fairdatapoint/util/KnownUUIDs.java @@ -22,86 +22,141 @@ */ package nl.dtls.fairdatapoint.util; +import java.util.UUID; + public class KnownUUIDs { - public static final String USER_ALBERT_UUID = - "7e64818d-6276-46fb-8bb1-732e6e09f7e9"; + public static final UUID NULL_UUID = + UUID.fromString("00000000-0000-0000-0000-000000000000"); + + public static final UUID USER_ALBERT_UUID = + UUID.fromString("7e64818d-6276-46fb-8bb1-732e6e09f7e9"); + + public static final UUID USER_NIKOLA_UUID = + UUID.fromString("b5b92c69-5ed9-4054-954d-0121c29b6800"); - public static final String USER_NIKOLA_UUID = - "b5b92c69-5ed9-4054-954d-0121c29b6800"; + public static final UUID USER_ISAAC_UUID = + UUID.fromString("8d1a4c06-bb0e-4d03-a01f-14fa49bbc152"); - public static final String USER_ISAAC_UUID = - "8d1a4c06-bb0e-4d03-a01f-14fa49bbc152"; + public static final UUID USER_ADMIN_UUID = + UUID.fromString("95589e50-d261-492b-8852-9324e9a66a42"); - public static final String USER_ADMIN_UUID = - "95589e50-d261-492b-8852-9324e9a66a42"; + public static final UUID API_KEY_ALBERT_UUID = + UUID.fromString("a1c00673-24c5-4e0a-bdbe-22e961ee7548"); - public static final String MEMBERSHIP_OWNER_UUID = - "49f2bcfd-ef0a-4a3a-a1a3-0fc72a6892a8"; + public static final UUID API_KEY_NIKOLA_UUID = + UUID.fromString("62657760-21fe-488c-a0ea-f612a70493da"); - public static final String MEMBERSHIP_DATAPROVIDER_UUID = - "87a2d984-7db2-43f6-805c-6b0040afead5"; + public static final UUID MEMBERSHIP_OWNER_UUID = + UUID.fromString("49f2bcfd-ef0a-4a3a-a1a3-0fc72a6892a8"); - public static final String SCHEMA_RESOURCE_UUID = - "6a668323-3936-4b53-8380-a4fd2ed082ee"; + public static final UUID MEMBERSHIP_DATAPROVIDER_UUID = + UUID.fromString("87a2d984-7db2-43f6-805c-6b0040afead5"); - public static final String SCHEMA_REPOSITORY_UUID = - "a92958ab-a414-47e6-8e17-68ba96ba3a2b"; + public static final UUID SCHEMA_RESOURCE_UUID = + UUID.fromString("6a668323-3936-4b53-8380-a4fd2ed082ee"); - public static final String SCHEMA_FDP_UUID = + public static final UUID SCHEMA_REPOSITORY_UUID = + UUID.fromString("a92958ab-a414-47e6-8e17-68ba96ba3a2b"); + + public static final UUID SCHEMA_FDP_UUID = SCHEMA_REPOSITORY_UUID; - public static final String SCHEMA_DATASERVICE_UUID = - "89d94c1b-f6ff-4545-ba9b-120b2d1921d0"; + public static final UUID SCHEMA_DATASERVICE_UUID = + UUID.fromString("89d94c1b-f6ff-4545-ba9b-120b2d1921d0"); - public static final String SCHEMA_METADATASERVICE_UUID = - "6f7a5a76-6185-4bd0-9fe9-62ecc90c9bad"; + public static final UUID SCHEMA_METADATASERVICE_UUID = + UUID.fromString("6f7a5a76-6185-4bd0-9fe9-62ecc90c9bad"); - public static final String SCHEMA_CATALOG_UUID = - "2aa7ba63-d27a-4c0e-bfa6-3a4e250f4660"; + public static final UUID SCHEMA_CATALOG_UUID = + UUID.fromString("2aa7ba63-d27a-4c0e-bfa6-3a4e250f4660"); - public static final String SCHEMA_DATASET_UUID = - "866d7fb8-5982-4215-9c7c-18d0ed1bd5f3"; + public static final UUID SCHEMA_DATASET_UUID = + UUID.fromString("866d7fb8-5982-4215-9c7c-18d0ed1bd5f3"); - public static final String SCHEMA_DISTRIBUTION_UUID = - "ebacbf83-cd4f-4113-8738-d73c0735b0ab"; + public static final UUID SCHEMA_DISTRIBUTION_UUID = + UUID.fromString("ebacbf83-cd4f-4113-8738-d73c0735b0ab"); - public static final String SCHEMA_V1_RESOURCE_UUID = - "71d77460-f919-4f72-b265-ed26567fe361"; + public static final UUID SCHEMA_V1_RESOURCE_UUID = + UUID.fromString("71d77460-f919-4f72-b265-ed26567fe361"); - public static final String SCHEMA_V2_RESOURCE_UUID = - "4c65bdf7-bb56-4bca-ae22-74977b148b16"; + public static final UUID SCHEMA_V2_RESOURCE_UUID = + UUID.fromString("4c65bdf7-bb56-4bca-ae22-74977b148b16"); - public static final String SCHEMA_V1_FDP_UUID = - "4e64208d-f102-45a0-96e3-17b002e6213e"; + public static final UUID SCHEMA_V1_FDP_UUID = + UUID.fromString("4e64208d-f102-45a0-96e3-17b002e6213e"); - public static final String SCHEMA_V1_DATASERVICE_UUID = - "9111d436-fe58-4bd5-97ae-e6f86bc2997a"; + public static final UUID SCHEMA_V1_DATASERVICE_UUID = + UUID.fromString("9111d436-fe58-4bd5-97ae-e6f86bc2997a"); - public static final String SCHEMA_V1_METADATASERVICE_UUID = - "36b22b70-6203-4dd2-9fb6-b39a776bf467"; + public static final UUID SCHEMA_V1_METADATASERVICE_UUID = + UUID.fromString("36b22b70-6203-4dd2-9fb6-b39a776bf467"); - public static final String SCHEMA_V1_CATALOG_UUID = - "c9640671-945d-4114-88fb-e81314cb7ab2"; + public static final UUID SCHEMA_V1_CATALOG_UUID = + UUID.fromString("c9640671-945d-4114-88fb-e81314cb7ab2"); - public static final String SCHEMA_V1_DATASET_UUID = - "9cc3c89a-76cf-4639-a71f-652627af51db"; + public static final UUID SCHEMA_V1_DATASET_UUID = + UUID.fromString("9cc3c89a-76cf-4639-a71f-652627af51db"); - public static final String SCHEMA_V1_DISTRIBUTION_UUID = - "3cda8cd3-b08b-4797-822d-d3f3e83c466a"; + public static final UUID SCHEMA_V1_DISTRIBUTION_UUID = + UUID.fromString("3cda8cd3-b08b-4797-822d-d3f3e83c466a"); - public static final String RD_REPOSITORY_UUID = - "77aaad6a-0136-4c6e-88b9-07ffccd0ee4c"; + public static final UUID RD_REPOSITORY_UUID = + UUID.fromString("77aaad6a-0136-4c6e-88b9-07ffccd0ee4c"); - public static final String RD_FDP_UUID = + public static final UUID RD_FDP_UUID = RD_REPOSITORY_UUID; - public static final String RD_CATALOG_UUID = - "a0949e72-4466-4d53-8900-9436d1049a4b"; + public static final UUID RD_CATALOG_UUID = + UUID.fromString("a0949e72-4466-4d53-8900-9436d1049a4b"); + + public static final UUID RD_DATASET_UUID = + UUID.fromString("2f08228e-1789-40f8-84cd-28e3288c3604"); + + public static final UUID RD_DISTRIBUTION_UUID = + UUID.fromString("02c649de-c579-43bb-b470-306abdc808c7"); + + public static final UUID SETTINGS_UUID = NULL_UUID; + + public static final UUID SAVED_QUERY_PUBLIC_UUID = + UUID.fromString("d31e3da1-2cfa-4b55-a8cb-71d1acf01aef"); + + public static final UUID SAVED_QUERY_PRIVATE_UUID = + UUID.fromString("97da9119-834e-4687-8321-3df157547178"); + + public static final UUID SAVED_QUERY_INTERNAL_UUID = + UUID.fromString("c7d0b6a0-5b0a-4b0e-9b0a-9b0a9b0a9b0a"); + + public static final UUID RD_CHILD_FDP_CATALOG_UUID = + UUID.fromString("b8648597-8fbd-4b89-9e30-5eab82675e42"); + + public static final UUID RD_DATASERVICE_UUID = + UUID.fromString("4bc19f45-845d-48d6-ade7-ac2664563f60"); + + public static final UUID RD_CHILD_CATALOG_DATASET_UUID = + UUID.fromString("e9f0f5d3-2a93-4aa3-9dd0-acb1d76f54fc"); + + public static final UUID RD_CHILD_DATASET_DISTRIBUTION_UUID = + UUID.fromString("9f138a13-9d45-4371-b763-0a3b9e0ec912"); + + public static final UUID RD_CHILD_DATASET_DISTRIBUTION_MEDIA_TYPE_UUID = + UUID.fromString("723e95d3-1696-45e2-9429-f6e98e3fb893"); + + public static final UUID RD_LINK_DISTRIBUTION_ACCESS_UUID = + UUID.fromString("660a1821-a5d2-48d0-a26b-0c6d5bac3de4"); + + public static final UUID RD_LINK_DISTRIBUTION_DOWNLOAD_UUID = + UUID.fromString("c2eaebb8-4d8d-469d-8736-269adeded996"); + + public static final UUID SCHEMA_V1_DATASERVICE_EXTENSION_UUID = + UUID.fromString("5f0dbdf7-ff73-4574-a918-cdcda12ecfd4"); + + public static final UUID SCHEMA_V1_METADATASERVICE_EXTENSION_UUID = + UUID.fromString("a843138f-b6f8-43a9-8020-550d2d4b644e"); - public static final String RD_DATASET_UUID = - "2f08228e-1789-40f8-84cd-28e3288c3604"; + public static final UUID SCHEMA_V1_FDP_EXTENSION_UUID = + UUID.fromString("42a76a7a-ba04-43ae-a3d5-1bba62971261"); - public static final String RD_DISTRIBUTION_UUID = - "02c649de-c579-43bb-b470-306abdc808c7"; + public static final UUID RD_FDP_USAGE_UUID = + UUID.fromString("d8a67021-0f4c-4b0a-ab3d-7bc8621fbee7"); } diff --git a/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsForms.java b/src/main/java/nl/dtls/fairdatapoint/util/TimeUtils.java similarity index 82% rename from src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsForms.java rename to src/main/java/nl/dtls/fairdatapoint/util/TimeUtils.java index 0c97f82b4..e787e16fa 100644 --- a/src/main/java/nl/dtls/fairdatapoint/entity/settings/SettingsForms.java +++ b/src/main/java/nl/dtls/fairdatapoint/util/TimeUtils.java @@ -20,17 +20,14 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.entity.settings; +package nl.dtls.fairdatapoint.util; -import lombok.*; +import java.sql.Timestamp; +import java.time.Instant; -@NoArgsConstructor -@AllArgsConstructor -@Getter -@Setter -@EqualsAndHashCode -@Builder(toBuilder = true) -public class SettingsForms { +public class TimeUtils { - private SettingsFormsAutocomplete autocomplete; + public static Timestamp now() { + return Timestamp.from(Instant.now()); + } } diff --git a/src/main/resources/application-development.yml b/src/main/resources/application-development.yml index d392068c9..359635210 100644 --- a/src/main/resources/application-development.yml +++ b/src/main/resources/application-development.yml @@ -7,6 +7,11 @@ security: expiration: 999 spring: - data: - mongodb: - uri: mongodb://localhost:27017/fdp-dev + datasource: + url: jdbc:postgresql://localhost:54321/fdp + username: fdp + password: fdp + flyway: + locations: classpath:dev/db/migration,classpath:db/migration + fail-on-missing-locations: true + clean-disabled: false diff --git a/src/main/resources/application-production.yml b/src/main/resources/application-production.yml index 05f30753f..b26bfeab4 100644 --- a/src/main/resources/application-production.yml +++ b/src/main/resources/application-production.yml @@ -3,3 +3,7 @@ instance: server: port: 80 + +spring: + flyway: + locations: classpath:db/migration diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 7aa149cbd..d6d0885c5 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -8,9 +8,23 @@ instance: subtitle: ${FDP_SUBTITLE:Metadata for machines} spring: + application: + name: fair-data-point + main: + banner-mode: off + datasource: + url: jdbc:postgresql://${FDP_POSTGRES_HOST:postgres}:${FDP_POSTGRES_PORT:5432}/${FDP_POSTGRES_DB:fdp} + username: ${FDP_POSTGRES_USERNAME:postgres} + password: ${FDP_POSTGRES_PASSWORD:password} + jpa: + properties: + hibernate: + ddl-auto: none + dialect: org.hibernate.dialect.PostgreSQLDialect + enable_lazy_load_no_trans: true + jdbc: + time_zone: UTC data: - mongodb: - uri: mongodb://${FDP_MONGO_HOST:mongo}:${FDP_MONGO_PORT:27017}/${FDP_MONGO_DB:fdp} web: pageable: default-page-size: 50 diff --git a/src/main/resources/db/migration/V0001.0__init-fdp-db.sql b/src/main/resources/db/migration/V0001.0__init-fdp-db.sql new file mode 100644 index 000000000..e3dda3e29 --- /dev/null +++ b/src/main/resources/db/migration/V0001.0__init-fdp-db.sql @@ -0,0 +1,438 @@ +-- +-- The MIT License +-- Copyright © 2017 DTL +-- +-- Permission is hereby granted, free of charge, to any person obtaining a copy +-- of this software and associated documentation files (the "Software"), to deal +-- in the Software without restriction, including without limitation the rights +-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +-- copies of the Software, and to permit persons to whom the Software is +-- furnished to do so, subject to the following conditions: +-- +-- The above copyright notice and this permission notice shall be included in +-- all copies or substantial portions of the Software. +-- +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +-- THE SOFTWARE. +-- + +CREATE TYPE USER_ROLE AS ENUM ('USER', 'ADMIN'); +CREATE CAST (character varying AS USER_ROLE) WITH INOUT AS ASSIGNMENT; + +CREATE TYPE SAVED_QUERY_TYPE AS ENUM ('PUBLIC', 'PRIVATE', 'INTERNAL'); +CREATE CAST (character varying AS SAVED_QUERY_TYPE) WITH INOUT AS ASSIGNMENT; + +CREATE TYPE METADATA_SCHEMA_TYPE AS ENUM ('INTERNAL', 'CUSTOM', 'REFERENCE'); +CREATE CAST (character varying AS METADATA_SCHEMA_TYPE) WITH INOUT AS ASSIGNMENT; + +CREATE TYPE METADATA_SCHEMA_STATE AS ENUM ('DRAFT', 'LATEST', 'LEGACY'); +CREATE CAST (character varying AS METADATA_SCHEMA_STATE) WITH INOUT AS ASSIGNMENT; + +CREATE TYPE INDEX_WEBHOOK_EVENT_TYPE AS ENUM ('NEW_ENTRY', 'INCOMING_PING', 'ENTRY_VALID', 'ENTRY_INVALID', 'ENTRY_UNREACHABLE', 'ADMIN_TRIGGER', 'WEBHOOK_PING'); +CREATE CAST (character varying AS INDEX_WEBHOOK_EVENT_TYPE) WITH INOUT AS ASSIGNMENT; + +CREATE TYPE INDEX_EVENT_TYPE AS ENUM ('INCOMING_PING', 'METADATA_RETRIEVAL', 'ADMIN_TRIGGER', 'WEBHOOK_PING', 'WEBHOOK_TRIGGER'); +CREATE CAST (character varying AS INDEX_EVENT_TYPE) WITH INOUT AS ASSIGNMENT; + +CREATE TYPE INDEX_ENTRY_STATE AS ENUM ('UNKNOWN', 'VALID', 'INVALID', 'UNREACHABLE'); +CREATE CAST (character varying AS INDEX_ENTRY_STATE) WITH INOUT AS ASSIGNMENT; + +CREATE TYPE INDEX_ENTRY_PERMIT AS ENUM ('PENDING', 'ACCEPTED', 'REJECTED'); +CREATE CAST (character varying AS INDEX_ENTRY_PERMIT) WITH INOUT AS ASSIGNMENT; + +CREATE TYPE SEARCH_FILTER_TYPE AS ENUM ('IRI', 'LITERAL'); +CREATE CAST (character varying AS SEARCH_FILTER_TYPE) WITH INOUT AS ASSIGNMENT; + + +CREATE TABLE IF NOT EXISTS user_account +( + uuid UUID NOT NULL, + first_name TEXT NOT NULL, + last_name TEXT NOT NULL, + email TEXT NOT NULL, + password_hash TEXT NOT NULL, + user_role USER_ROLE NOT NULL DEFAULT 'USER', + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + + +CREATE TABLE IF NOT EXISTS api_key +( + uuid UUID NOT NULL, + user_account_id UUID NOT NULL, + token TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + +ALTER TABLE api_key + ADD CONSTRAINT fk__api_key_user FOREIGN KEY (user_account_id) REFERENCES user_account (uuid); + + +CREATE TABLE IF NOT EXISTS search_saved_query +( + uuid UUID NOT NULL, + user_account_id UUID NOT NULL, + name TEXT NOT NULL, + description TEXT NOT NULL, + type SAVED_QUERY_TYPE NOT NULL, + var_prefixes TEXT NOT NULL, + var_graph_pattern TEXT NOT NULL, + var_ordering TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + +ALTER TABLE search_saved_query + ADD CONSTRAINT fk__search_saved_query_user FOREIGN KEY (user_account_id) REFERENCES user_account (uuid); + +CREATE TABLE IF NOT EXISTS membership +( + uuid UUID NOT NULL, + name TEXT NOT NULL, + allowed_entities TEXT[] NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + +CREATE TABLE IF NOT EXISTS membership_permission +( + uuid UUID NOT NULL, + membership_id UUID NOT NULL, + mask INTEGER NOT NULL, + code CHAR NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + +ALTER TABLE membership_permission + ADD CONSTRAINT fk__membership_permission_membership FOREIGN KEY (membership_id) REFERENCES membership (uuid); + +CREATE TABLE IF NOT EXISTS metadata_schema +( + uuid UUID NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + +CREATE TABLE IF NOT EXISTS metadata_schema_version +( + uuid UUID NOT NULL, + metadata_schema_id UUID NOT NULL, + previous_version_id UUID, + version TEXT, + name TEXT NOT NULL, + description TEXT NOT NULL, + definition TEXT NOT NULL, + target_classes TEXT[] NOT NULL, + type METADATA_SCHEMA_TYPE NOT NULL, + origin TEXT, + imported_from TEXT, + state METADATA_SCHEMA_STATE NOT NULL, + published BOOLEAN NOT NULL, + abstract BOOLEAN NOT NULL, + suggested_resource_name TEXT, + suggested_url_prefix TEXT, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + +ALTER TABLE metadata_schema_version + ADD CONSTRAINT fk__metadata_schema_version_schema FOREIGN KEY (metadata_schema_id) REFERENCES metadata_schema (uuid); + +ALTER TABLE metadata_schema_version + ADD CONSTRAINT fk__metadata_schema_version_previous FOREIGN KEY (previous_version_id) REFERENCES metadata_schema_version (uuid); + +CREATE TABLE IF NOT EXISTS metadata_schema_extension +( + uuid UUID NOT NULL, + metadata_schema_version_id UUID NOT NULL, + extended_metadata_schema_id UUID NOT NULL, + order_priority INTEGER NOT NULL, + PRIMARY KEY (uuid) +); + +ALTER TABLE metadata_schema_extension + ADD CONSTRAINT fk__metadata_schema_extension_version FOREIGN KEY (metadata_schema_version_id) REFERENCES metadata_schema_version (uuid); + +ALTER TABLE metadata_schema_extension + ADD CONSTRAINT fk__metadata_schema_extension_extended FOREIGN KEY (extended_metadata_schema_id) REFERENCES metadata_schema (uuid); + +CREATE TABLE IF NOT EXISTS resource_definition +( + uuid UUID NOT NULL, + name TEXT NOT NULL, + url_prefix TEXT NOT NULL UNIQUE, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + +CREATE TABLE IF NOT EXISTS resource_definition_child +( + uuid UUID NOT NULL, + source_resource_definition_id UUID NOT NULL, + target_resource_definition_id UUID NOT NULL, + relation_uri TEXT NOT NULL, + title TEXT NOT NULL, + tags_uri TEXT, + order_priority INTEGER NOT NULL DEFAULT (0), + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + +ALTER TABLE resource_definition_child + ADD CONSTRAINT fk__resource_definition_child_source FOREIGN KEY (source_resource_definition_id) REFERENCES resource_definition (uuid); + +ALTER TABLE resource_definition_child + ADD CONSTRAINT fk__resource_definition_child_target FOREIGN KEY (target_resource_definition_id) REFERENCES resource_definition (uuid); + +CREATE TABLE IF NOT EXISTS resource_definition_child_metadata +( + uuid UUID NOT NULL, + resource_definition_child_id UUID NOT NULL, + title TEXT NOT NULL, + property_uri TEXT NOT NULL, + order_priority INTEGER NOT NULL DEFAULT (0), + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + +ALTER TABLE resource_definition_child_metadata + ADD CONSTRAINT fk__resource_definition_child_metadata_child FOREIGN KEY (resource_definition_child_id) REFERENCES resource_definition_child (uuid); + +CREATE TABLE IF NOT EXISTS resource_definition_link +( + uuid UUID NOT NULL, + resource_definition_id UUID NOT NULL, + title TEXT NOT NULL, + property_uri TEXT NOT NULL, + order_priority INTEGER NOT NULL DEFAULT (0), + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + +ALTER TABLE resource_definition_link + ADD CONSTRAINT fk__resource_definition_link_source FOREIGN KEY (resource_definition_id) REFERENCES resource_definition (uuid); + +CREATE TABLE IF NOT EXISTS metadata_schema_usage +( + uuid UUID NOT NULL, + resource_definition_id UUID NOT NULL, + metadata_schema_id UUID NOT NULL, + order_priority INTEGER NOT NULL, + PRIMARY KEY (uuid) +); + +ALTER TABLE metadata_schema_usage + ADD CONSTRAINT fk__metadata_schema_usage_rd FOREIGN KEY (resource_definition_id) REFERENCES resource_definition (uuid); + +ALTER TABLE metadata_schema_usage + ADD CONSTRAINT fk__metadata_schema_usage_schema FOREIGN KEY (metadata_schema_id) REFERENCES metadata_schema (uuid); + +CREATE TABLE IF NOT EXISTS settings +( + uuid UUID NOT NULL, + app_title TEXT, + app_subtitle TEXT, + ping_enabled BOOLEAN NOT NULL, + ping_endpoints TEXT[] NOT NULL, + autocomplete_search_ns BOOLEAN NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + +CREATE TABLE IF NOT EXISTS settings_autocomplete_source +( + uuid UUID NOT NULL, + settings_id UUID NOT NULL, + rdf_type TEXT NOT NULL, + sparql_endpoint TEXT NOT NULL, + sparql_query TEXT NOT NULL, + order_priority INTEGER NOT NULL DEFAULT (0), + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + +ALTER TABLE settings_autocomplete_source + ADD CONSTRAINT fk__settings_autocomplete_source_settings FOREIGN KEY (settings_id) REFERENCES settings (uuid); + +CREATE TABLE IF NOT EXISTS settings_metric +( + uuid UUID NOT NULL, + settings_id UUID NOT NULL, + metric_uri TEXT NOT NULL, + resource_uri TEXT NOT NULL, + order_priority INTEGER NOT NULL DEFAULT (0), + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + +ALTER TABLE settings_metric + ADD CONSTRAINT fk__settings_metric_settings FOREIGN KEY (settings_id) REFERENCES settings (uuid); + +CREATE TABLE IF NOT EXISTS settings_search_filter +( + uuid UUID NOT NULL, + settings_id UUID NOT NULL, + type SEARCH_FILTER_TYPE NOT NULL, + label TEXT NOT NULL, + predicate TEXT NOT NULL, + query_records BOOLEAN NOT NULL, + order_priority INTEGER NOT NULL DEFAULT (0), + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + +ALTER TABLE settings_search_filter + ADD CONSTRAINT fk__settings_search_filter_settings FOREIGN KEY (settings_id) REFERENCES settings (uuid); + +CREATE TABLE IF NOT EXISTS settings_search_filter_item +( + uuid UUID NOT NULL, + filter_id UUID NOT NULL, + label TEXT NOT NULL, + value TEXT NOT NULL, + order_priority INTEGER NOT NULL DEFAULT (0), + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + +ALTER TABLE settings_search_filter_item + ADD CONSTRAINT fk__settings_search_filter_item_filter FOREIGN KEY (filter_id) REFERENCES settings_search_filter (uuid); + +CREATE TABLE IF NOT EXISTS index_settings +( + uuid UUID NOT NULL, + auto_permit BOOLEAN, + retrieval_rate_limit_wait TEXT, + retrieval_timeout TEXT, + ping_valid_duration TEXT, + ping_rate_limit_duration TEXT, + ping_rate_limit_hits INTEGER, + ping_deny_list TEXT[], + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + +CREATE TABLE IF NOT EXISTS index_webhook +( + uuid UUID NOT NULL, + payload_url TEXT NOT NULL, + secret TEXT NOT NULL, + all_events BOOLEAN NOT NULL, + all_entries BOOLEAN NOT NULL, + enabled BOOLEAN NOT NULL, + entries TEXT[] NOT NULL, + events INDEX_WEBHOOK_EVENT_TYPE[] NOT NULL, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + + +CREATE TABLE IF NOT EXISTS index_entry +( + uuid UUID NOT NULL, + client_url TEXT NOT NULL, + state INDEX_ENTRY_STATE NOT NULL, + permit INDEX_ENTRY_PERMIT NOT NULL, + metadata_version INTEGER NOT NULL, + repository_uri TEXT, + metadata JSONB NOT NULL, + last_retrieval_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + + +CREATE TABLE IF NOT EXISTS index_event +( + uuid UUID NOT NULL, + type INDEX_EVENT_TYPE NOT NULL, + version INTEGER NOT NULL, + payload JSONB NOT NULL, + remote_addr TEXT, + triggered_by UUID, + related_to UUID, + executed_at TIMESTAMPTZ, + finished_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL, + updated_at TIMESTAMPTZ NOT NULL, + PRIMARY KEY (uuid) +); + +ALTER TABLE index_event + ADD CONSTRAINT fk__index_event_triggered_by FOREIGN KEY (triggered_by) REFERENCES index_event (uuid); + +ALTER TABLE index_event + ADD CONSTRAINT fk__index_event_related_to FOREIGN KEY (related_to) REFERENCES index_entry (uuid); + + +-- --------------------------------------------------------------------------------------------------- +-- Spring Security ACL +-- @see https://docs.spring.io/spring-security/reference/servlet/appendix/database-schema.html#_postgresql +-- --------------------------------------------------------------------------------------------------- +create table acl_sid( + id bigserial not null primary key, + principal boolean not null, + sid varchar(100) not null, + constraint unique_uk_1 unique(sid,principal) +); + +create table acl_class( + id bigserial not null primary key, + class varchar(100) not null, + class_id_type varchar(100), + constraint unique_uk_2 unique(class) +); + +create table acl_object_identity( + id bigserial primary key, + object_id_class bigint not null, + object_id_identity varchar not null, + parent_object bigint, + owner_sid bigint, + entries_inheriting boolean not null, + constraint unique_uk_3 unique(object_id_class,object_id_identity), + constraint foreign_fk_1 foreign key(parent_object)references acl_object_identity(id), + constraint foreign_fk_2 foreign key(object_id_class)references acl_class(id), + constraint foreign_fk_3 foreign key(owner_sid)references acl_sid(id) +); + +create table acl_entry( + id bigserial primary key, + acl_object_identity bigint not null, + ace_order int not null, + sid bigint not null, + mask integer not null, + granting boolean not null, + audit_success boolean not null, + audit_failure boolean not null, + constraint unique_uk_4 unique(acl_object_identity,ace_order), + constraint foreign_fk_4 foreign key(acl_object_identity) references acl_object_identity(id), + constraint foreign_fk_5 foreign key(sid) references acl_sid(id) +); diff --git a/src/main/resources/dev/db/migration/V0001.1__dev-data-users.sql b/src/main/resources/dev/db/migration/V0001.1__dev-data-users.sql new file mode 100644 index 000000000..f36291a59 --- /dev/null +++ b/src/main/resources/dev/db/migration/V0001.1__dev-data-users.sql @@ -0,0 +1,61 @@ +-- +-- The MIT License +-- Copyright © 2017 DTL +-- +-- Permission is hereby granted, free of charge, to any person obtaining a copy +-- of this software and associated documentation files (the "Software"), to deal +-- in the Software without restriction, including without limitation the rights +-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +-- copies of the Software, and to permit persons to whom the Software is +-- furnished to do so, subject to the following conditions: +-- +-- The above copyright notice and this permission notice shall be included in +-- all copies or substantial portions of the Software. +-- +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +-- THE SOFTWARE. +-- + +-- User Accounts +INSERT INTO public.user_account (uuid, first_name, last_name, email, password_hash, user_role, created_at, updated_at) +VALUES ('95589e50-d261-492b-8852-9324e9a66a42', 'Admin', 'von Universe', 'admin@example.com', '$2a$10$L.0OZ8QjV3yLhoCDvU04gu.WP1wGQih41MsBdvtQOshJJntaugBxe', 'ADMIN', NOW(), NOW()); + +INSERT INTO public.user_account (uuid, first_name, last_name, email, password_hash, user_role, created_at, updated_at) +VALUES ('7e64818d-6276-46fb-8bb1-732e6e09f7e9', 'Albert', 'Einstein', 'albert.einstein@example.com', '$2a$10$hZF1abbZ48Tf.3RndC9W6OlDt6gnBoD/2HbzJayTs6be7d.5DbpnW', 'USER', NOW(), NOW()); + +INSERT INTO public.user_account (uuid, first_name, last_name, email, password_hash, user_role, created_at, updated_at) +VALUES ('b5b92c69-5ed9-4054-954d-0121c29b6800', 'Nikola', 'Tesla', 'nikola.tesla@example.com', '$2a$10$tMbZUZg9AbYL514R.hZ0tuzvfZJR5NQhSVeJPTQhNwPf6gv/cvrna', 'USER', NOW(), NOW()); + +INSERT INTO public.user_account (uuid, first_name, last_name, email, password_hash, user_role, created_at, updated_at) +VALUES ('8d1a4c06-bb0e-4d03-a01f-14fa49bbc152', 'Isaac', 'Newton', 'isaac.newton@example.com', '$2a$10$DLkI7NAZDzWVaKG1lVtloeoPNLPoAgDDBqQKQiSAYDZXrf2QKkuHC', 'USER', NOW(), NOW()); + +-- API Keys +INSERT INTO public.api_key (uuid, token, user_account_id, created_at, updated_at) +VALUES ('a1c00673-24c5-4e0a-bdbe-22e961ee7548', 'a274793046e34a219fd0ea6362fcca61a001500b71724f4c973a017031653c20', '7e64818d-6276-46fb-8bb1-732e6e09f7e9', NOW(), NOW()); + +INSERT INTO public.api_key (uuid, token, user_account_id, created_at, updated_at) +VALUES ('62657760-21fe-488c-a0ea-f612a70493da', 'dd5dc3b53b6145cfa9f6c58b72ebad21cd2f860ace62451ba4e3c74a0e63540a', 'b5b92c69-5ed9-4054-954d-0121c29b6800', NOW(), NOW()); + +-- Saved Search Queries +INSERT INTO public.search_saved_query (uuid, name, description, type, var_prefixes, var_graph_pattern, var_ordering, user_account_id, created_at, updated_at) +VALUES ('d31e3da1-2cfa-4b55-a8cb-71d1acf01aef', 'All datasets', 'Quickly query all datasets (DCAT)', 'PUBLIC', + 'PREFIX dcat: ', '?entity rdf:type dcat:Dataset .', 'ASC(?title)', '7e64818d-6276-46fb-8bb1-732e6e09f7e9', + NOW(), NOW()); + +INSERT INTO public.search_saved_query (uuid, name, description, type, var_prefixes, var_graph_pattern, var_ordering, user_account_id, created_at, updated_at) +VALUES ('c7d0b6a0-5b0a-4b0e-9b0a-9b0a9b0a9b0a', 'All distributions', 'Quickly query all distributions (DCAT)', 'INTERNAL', + 'PREFIX dcat: ', '?entity rdf:type dcat:Distribution .', 'ASC(?title)', '7e64818d-6276-46fb-8bb1-732e6e09f7e9', + NOW(), NOW()); + +INSERT INTO public.search_saved_query (uuid, name, description, type, var_prefixes, var_graph_pattern, var_ordering, user_account_id, created_at, updated_at) +VALUES ('97da9119-834e-4687-8321-3df157547178', 'Things with data', 'This is private query of Nikola Tesla!', 'PRIVATE', + 'PREFIX dcat: ', + '?entity ?relationPredicate ?relationObject . + FILTER isLiteral(?relationObject) + FILTER CONTAINS(LCASE(str(?relationObject)), LCASE("data"))', + 'ASC(?title)', '7e64818d-6276-46fb-8bb1-732e6e09f7e9', NOW(), NOW()); diff --git a/src/main/resources/dev/db/migration/V0001.2__dev-data-schemas.sql b/src/main/resources/dev/db/migration/V0001.2__dev-data-schemas.sql new file mode 100644 index 000000000..b89fb1452 --- /dev/null +++ b/src/main/resources/dev/db/migration/V0001.2__dev-data-schemas.sql @@ -0,0 +1,473 @@ +-- +-- The MIT License +-- Copyright © 2017 DTL +-- +-- Permission is hereby granted, free of charge, to any person obtaining a copy +-- of this software and associated documentation files (the "Software"), to deal +-- in the Software without restriction, including without limitation the rights +-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +-- copies of the Software, and to permit persons to whom the Software is +-- furnished to do so, subject to the following conditions: +-- +-- The above copyright notice and this permission notice shall be included in +-- all copies or substantial portions of the Software. +-- +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +-- THE SOFTWARE. +-- + +-- Resource +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('6a668323-3936-4b53-8380-a4fd2ed082ee', NOW(), NOW()); +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('71d77460-f919-4f72-b265-ed26567fe361', + '6a668323-3936-4b53-8380-a4fd2ed082ee', + NULL, + '1.0.0', + 'Resource', + '', + '@prefix : . + @prefix dash: . + @prefix dcat: . + @prefix dct: . + @prefix foaf: . + @prefix sh: . + @prefix xsd: . + + :ResourceShape a sh:NodeShape ; + sh:targetClass dcat:Resource ; + sh:property [ + sh:path dct:title ; + sh:nodeKind sh:Literal ; + sh:minCount 1 ; + sh:maxCount 1 ; + dash:editor dash:TextFieldEditor ; + ], [ + sh:path dct:description ; + sh:nodeKind sh:Literal ; + sh:maxCount 1 ; + dash:editor dash:TextAreaEditor ; + ], [ + sh:path dct:publisher ; + sh:node :AgentShape ; + sh:minCount 1 ; + sh:maxCount 1 ; + dash:editor dash:BlankNodeEditor ; + ], [ + sh:path dcat:version ; + sh:name "version" ; + sh:nodeKind sh:Literal ; + sh:minCount 1 ; + sh:maxCount 1 ; + dash:editor dash:TextFieldEditor ; + dash:viewer dash:LiteralViewer ; + ], [ + sh:path dct:language ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + dash:editor dash:URIEditor ; + dash:viewer dash:LabelViewer ; + ], [ + sh:path dct:license ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + dash:editor dash:URIEditor ; + dash:viewer dash:LabelViewer ; + ], [ + sh:path dct:rights ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + dash:editor dash:URIEditor ; + dash:viewer dash:LabelViewer ; + ] . + + :AgentShape a sh:NodeShape ; + sh:targetClass foaf:Agent ; + sh:property [ + sh:path foaf:name; + sh:nodeKind sh:Literal ; + sh:minCount 1 ; + sh:maxCount 1 ; + dash:editor dash:TextFieldEditor ; + ] . + ', + ARRAY ['http://www.w3.org/ns/dcat#Resource'], + 'INTERNAL', + NULL, + NULL, + 'LATEST', + FALSE, + TRUE, + NULL, + NULL, + NOW(), + NOW()); + +-- Data Service +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('89d94c1b-f6ff-4545-ba9b-120b2d1921d0', NOW(), NOW()); +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('9111d436-fe58-4bd5-97ae-e6f86bc2997a', + '89d94c1b-f6ff-4545-ba9b-120b2d1921d0', + NULL, + '1.0.0', + 'Data Service', + '', + '@prefix : . +@prefix dash: . +@prefix dcat: . +@prefix dct: . +@prefix sh: . +@prefix xsd: . + +:DataServiceShape a sh:NodeShape ; + sh:targetClass dcat:DataService ; + sh:property [ + sh:path dcat:endpointURL ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + ] , [ + sh:path dcat:endpointDescription ; + sh:nodeKind sh:Literal ; + sh:maxCount 1 ; + dash:editor dash:TextAreaEditor ; + dash:viewer dash:LiteralViewer ; +] . +', + ARRAY ['http://www.w3.org/ns/dcat#Resource', 'http://www.w3.org/ns/dcat#DataService'], + 'INTERNAL', + NULL, + NULL, + 'LATEST', + FALSE, + FALSE, + NULL, + NULL, + NOW(), + NOW()); +INSERT INTO metadata_schema_extension (uuid, metadata_schema_version_id, extended_metadata_schema_id, order_priority) +VALUES ('2efc8366-541d-493f-8661-69ad8f72dfa1', '9111d436-fe58-4bd5-97ae-e6f86bc2997a', '6a668323-3936-4b53-8380-a4fd2ed082ee', 0); + +-- Metadata Service +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('6f7a5a76-6185-4bd0-9fe9-62ecc90c9bad', NOW(), NOW()); +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('36b22b70-6203-4dd2-9fb6-b39a776bf467', + '6f7a5a76-6185-4bd0-9fe9-62ecc90c9bad', + NULL, + '1.0.0', + 'Metadata Service', + '', + '@prefix : . +@prefix fdp: . +@prefix sh: . + +:MetadataServiceShape a sh:NodeShape ; + sh:targetClass fdp:MetadataService . +', + ARRAY ['http://www.w3.org/ns/dcat#Resource', 'http://www.w3.org/ns/dcat#DataService', 'https://w3id.org/fdp/fdp-o#MetadataService'], + 'INTERNAL', + NULL, + NULL, + 'LATEST', + FALSE, + FALSE, + NULL, + NULL, + NOW(), + NOW()); +INSERT INTO metadata_schema_extension (uuid, metadata_schema_version_id, extended_metadata_schema_id, order_priority) +VALUES ('8742361b-cd00-4167-b859-e45fa36d0cb7', '36b22b70-6203-4dd2-9fb6-b39a776bf467', '89d94c1b-f6ff-4545-ba9b-120b2d1921d0', 0); + +-- FAIR Data Point +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('a92958ab-a414-47e6-8e17-68ba96ba3a2b', NOW(), NOW()); +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('4e64208d-f102-45a0-96e3-17b002e6213e', + 'a92958ab-a414-47e6-8e17-68ba96ba3a2b', + NULL, + '1.0.0', + 'FAIR Data Point', + '', + '@prefix : . +@prefix dash: . +@prefix dct: . +@prefix fdp: . +@prefix sh: . +@prefix xsd: . + +:FDPShape a sh:NodeShape ; + sh:targetClass fdp:FAIRDataPoint ; + sh:property [ + sh:path fdp:startDate ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:editor dash:DatePickerEditor ; + dash:viewer dash:LiteralViewer ; + ] , [ + sh:path fdp:endDate ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:editor dash:DatePickerEditor ; + dash:viewer dash:LiteralViewer ; + ] , [ + sh:path fdp:uiLanguage ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + sh:defaultValue ; + dash:editor dash:URIEditor ; + dash:viewer dash:LabelViewer ; + ] , [ + sh:path fdp:metadataIdentifier ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + dash:editor dash:URIEditor ; + dash:viewer dash:LabelViewer ; + ] , [ + sh:path fdp:metadataIssued ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:editor dash:DatePickerEditor ; + dash:viewer dash:LiteralViewer ; + ] , [ + sh:path fdp:metadataModified ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:editor dash:DatePickerEditor ; + dash:viewer dash:LiteralViewer ; + ] . + ', + ARRAY ['http://www.w3.org/ns/dcat#Resource', 'http://www.w3.org/ns/dcat#DataService', 'https://w3id.org/fdp/fdp-o#MetadataService', 'https://w3id.org/fdp/fdp-o#FAIRDataPoint'], + 'INTERNAL', + NULL, + NULL, + 'LATEST', + FALSE, + FALSE, + NULL, + NULL, + NOW(), + NOW()); +INSERT INTO metadata_schema_extension (uuid, metadata_schema_version_id, extended_metadata_schema_id, order_priority) +VALUES ('afebd441-8aa5-464d-bc3c-033f175449b4', '4e64208d-f102-45a0-96e3-17b002e6213e', '6f7a5a76-6185-4bd0-9fe9-62ecc90c9bad', 0); + +-- Catalog +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('2aa7ba63-d27a-4c0e-bfa6-3a4e250f4660', NOW(), NOW()); +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('c9640671-945d-4114-88fb-e81314cb7ab2', + '2aa7ba63-d27a-4c0e-bfa6-3a4e250f4660', + NULL, + '1.0.0', + 'Catalog', + '', + '@prefix : . +@prefix dash: . +@prefix dcat: . +@prefix dct: . +@prefix foaf: . +@prefix sh: . +@prefix xsd: . + +:CatalogShape a sh:NodeShape ; + sh:targetClass dcat:Catalog ; + sh:property [ + sh:path dct:issued ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:viewer dash:LiteralViewer ; + ], [ + sh:path dct:modified ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:viewer dash:LiteralViewer ; + ], [ + sh:path foaf:homePage ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + dash:editor dash:URIEditor ; + dash:viewer dash:LabelViewer ; + ], [ + sh:path dcat:themeTaxonomy ; + sh:nodeKind sh:IRI ; + dash:viewer dash:LabelViewer ; + ] . +', + ARRAY ['http://www.w3.org/ns/dcat#Resource', 'http://www.w3.org/ns/dcat#Catalog'], + 'INTERNAL', + NULL, + NULL, + 'LATEST', + FALSE, + FALSE, + NULL, + NULL, + NOW(), + NOW()); +INSERT INTO metadata_schema_extension (uuid, metadata_schema_version_id, extended_metadata_schema_id, order_priority) +VALUES ('e75cb601-318d-41ea-9a8b-32e0749c80a7', 'c9640671-945d-4114-88fb-e81314cb7ab2', '6a668323-3936-4b53-8380-a4fd2ed082ee', 0); + +-- Dataset +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('866d7fb8-5982-4215-9c7c-18d0ed1bd5f3', NOW(), NOW()); +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('9cc3c89a-76cf-4639-a71f-652627af51db', + '866d7fb8-5982-4215-9c7c-18d0ed1bd5f3', + NULL, + '1.0.0', + 'Dataset', + '', + '@prefix : . +@prefix dash: . +@prefix dcat: . +@prefix dct: . +@prefix sh: . +@prefix xsd: . + +:DatasetShape a sh:NodeShape ; + sh:targetClass dcat:Dataset ; + sh:property [ + sh:path dct:issued ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:editor dash:DatePickerEditor ; + dash:viewer dash:LiteralViewer ; + ], [ + sh:path dct:modified ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:editor dash:DatePickerEditor ; + dash:viewer dash:LiteralViewer ; + ], [ + sh:path dcat:theme ; + sh:nodeKind sh:IRI ; + sh:minCount 1 ; + dash:editor dash:URIEditor ; + dash:viewer dash:LabelViewer ; + ], [ + sh:path dcat:contactPoint ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + dash:editor dash:URIEditor ; + dash:viewer dash:LabelViewer ; + ], [ + sh:path dcat:keyword ; + sh:nodeKind sh:Literal ; + dash:editor dash:TextFieldEditor ; + dash:viewer dash:LiteralViewer ; + ], [ + sh:path dcat:landingPage ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + dash:editor dash:URIEditor ; + dash:viewer dash:LabelViewer ; + ] . +', + ARRAY ['http://www.w3.org/ns/dcat#Resource', 'http://www.w3.org/ns/dcat#Dataset'], + 'INTERNAL', + NULL, + NULL, + 'LATEST', + FALSE, + FALSE, + NULL, + NULL, + NOW(), + NOW()); +INSERT INTO metadata_schema_extension (uuid, metadata_schema_version_id, extended_metadata_schema_id, order_priority) +VALUES ('da13ba37-09f8-4937-9055-e3ee3aefc57c', '9cc3c89a-76cf-4639-a71f-652627af51db', '6a668323-3936-4b53-8380-a4fd2ed082ee', 0); + +-- Distribution +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('ebacbf83-cd4f-4113-8738-d73c0735b0ab', NOW(), NOW()); +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('3cda8cd3-b08b-4797-822d-d3f3e83c466a', + 'ebacbf83-cd4f-4113-8738-d73c0735b0ab', + NULL, + '1.0.0', + 'Distribution', + '', + '@prefix : . +@prefix dash: . +@prefix dcat: . +@prefix dct: . +@prefix sh: . +@prefix xsd: . + +:DistributionShape a sh:NodeShape ; + sh:targetClass dcat:Distribution ; + sh:property [ + sh:path dct:issued ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:editor dash:DatePickerEditor ; + dash:viewer dash:LiteralViewer ; + ] , [ + sh:path dct:modified ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:editor dash:DatePickerEditor ; + dash:viewer dash:LiteralViewer ; + ] , [ + sh:path dcat:accessURL ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + dash:editor dash:URIEditor ; + ] , [ + sh:path dcat:downloadURL ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + dash:editor dash:URIEditor ; + ] , [ + sh:path dcat:mediaType ; + sh:nodeKind sh:Literal ; + sh:minCount 1 ; + sh:maxCount 1 ; + dash:editor dash:TextFieldEditor ; + dash:viewer dash:LiteralViewer ; + ] , [ + sh:path dcat:format ; + sh:nodeKind sh:Literal ; + sh:maxCount 1 ; + dash:editor dash:TextFieldEditor ; + dash:viewer dash:LiteralViewer ; + ] , [ + sh:path dcat:byteSize ; + sh:nodeKind sh:Literal ; + sh:maxCount 1 ; + dash:editor dash:TextFieldEditor ; + dash:viewer dash:LiteralViewer ; + ] . +', + ARRAY ['http://www.w3.org/ns/dcat#Resource', 'http://www.w3.org/ns/dcat#Distribution'], + 'INTERNAL', + NULL, + NULL, + 'LATEST', + FALSE, + FALSE, + NULL, + NULL, + NOW(), + NOW()); +INSERT INTO metadata_schema_extension (uuid, metadata_schema_version_id, extended_metadata_schema_id, order_priority) +VALUES ('a3b16a4e-cac7-4b71-a3de-94bb86714b5b', '3cda8cd3-b08b-4797-822d-d3f3e83c466a', '6a668323-3936-4b53-8380-a4fd2ed082ee', 0); diff --git a/src/main/resources/dev/db/migration/V0001.3__dev-data-rds.sql b/src/main/resources/dev/db/migration/V0001.3__dev-data-rds.sql new file mode 100644 index 000000000..29eb20aeb --- /dev/null +++ b/src/main/resources/dev/db/migration/V0001.3__dev-data-rds.sql @@ -0,0 +1,68 @@ +-- +-- The MIT License +-- Copyright © 2017 DTL +-- +-- Permission is hereby granted, free of charge, to any person obtaining a copy +-- of this software and associated documentation files (the "Software"), to deal +-- in the Software without restriction, including without limitation the rights +-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +-- copies of the Software, and to permit persons to whom the Software is +-- furnished to do so, subject to the following conditions: +-- +-- The above copyright notice and this permission notice shall be included in +-- all copies or substantial portions of the Software. +-- +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +-- THE SOFTWARE. +-- + +-- Distribution +INSERT INTO resource_definition (uuid, name, url_prefix, created_at, updated_at) +VALUES ('02c649de-c579-43bb-b470-306abdc808c7', 'Distribution', 'distribution', now(), now()); + +INSERT INTO resource_definition_link (uuid, resource_definition_id, title, property_uri, order_priority, created_at, updated_at) +VALUES ('660a1821-a5d2-48d0-a26b-0c6d5bac3de4', '02c649de-c579-43bb-b470-306abdc808c7', 'Access online', 'http://www.w3.org/ns/dcat#accessURL', 1, now(), now()); + +INSERT INTO resource_definition_link (uuid, resource_definition_id, title, property_uri, order_priority, created_at, updated_at) +VALUES ('c2eaebb8-4d8d-469d-8736-269adeded996', '02c649de-c579-43bb-b470-306abdc808c7', 'Download', 'http://www.w3.org/ns/dcat#downloadURL', 2, now(), now()); + +INSERT INTO metadata_schema_usage (uuid, resource_definition_id, metadata_schema_id, order_priority) +VALUES ('bbf4ecb3-c529-4c02-955c-7160755debf5', '02c649de-c579-43bb-b470-306abdc808c7', 'ebacbf83-cd4f-4113-8738-d73c0735b0ab', 1); + +-- Dataset +INSERT INTO resource_definition (uuid, name, url_prefix, created_at, updated_at) +VALUES ('2f08228e-1789-40f8-84cd-28e3288c3604', 'Dataset', 'dataset', now(), now()); + +INSERT INTO resource_definition_child (uuid, source_resource_definition_id, target_resource_definition_id, relation_uri, title, tags_uri, order_priority, created_at, updated_at) +VALUES ('9f138a13-9d45-4371-b763-0a3b9e0ec912', '2f08228e-1789-40f8-84cd-28e3288c3604', '02c649de-c579-43bb-b470-306abdc808c7', 'http://www.w3.org/ns/dcat#distribution', 'Distributions', NULL, 1, now(), now()); + +INSERT INTO resource_definition_child_metadata (uuid, resource_definition_child_id, title, property_uri, order_priority, created_at, updated_at) +VALUES ('723e95d3-1696-45e2-9429-f6e98e3fb893', '9f138a13-9d45-4371-b763-0a3b9e0ec912', 'Media Type', 'http://www.w3.org/ns/dcat#mediaType', 1, now(), now()); + +INSERT INTO metadata_schema_usage (uuid, resource_definition_id, metadata_schema_id, order_priority) +VALUES ('b8a0ed37-42a1-487e-8842-09fe082c4cc6', '2f08228e-1789-40f8-84cd-28e3288c3604', '866d7fb8-5982-4215-9c7c-18d0ed1bd5f3', 1); + +-- Catalog +INSERT INTO resource_definition (uuid, name, url_prefix, created_at, updated_at) +VALUES ('a0949e72-4466-4d53-8900-9436d1049a4b', 'Catalog', 'catalog', now(), now()); + +INSERT INTO resource_definition_child (uuid, source_resource_definition_id, target_resource_definition_id, relation_uri, title, tags_uri, order_priority, created_at, updated_at) +VALUES ('e9f0f5d3-2a93-4aa3-9dd0-acb1d76f54fc', 'a0949e72-4466-4d53-8900-9436d1049a4b', '2f08228e-1789-40f8-84cd-28e3288c3604', 'http://www.w3.org/ns/dcat#dataset', 'Datasets', 'http://www.w3.org/ns/dcat#theme', 1, now(), now()); + +INSERT INTO metadata_schema_usage (uuid, resource_definition_id, metadata_schema_id, order_priority) +VALUES ('e4df9510-a3ad-4e3b-a1a9-5fc330d8b1f0', 'a0949e72-4466-4d53-8900-9436d1049a4b', '2aa7ba63-d27a-4c0e-bfa6-3a4e250f4660', 1); + +-- FAIR Data Point +INSERT INTO resource_definition (uuid, name, url_prefix, created_at, updated_at) +VALUES ('77aaad6a-0136-4c6e-88b9-07ffccd0ee4c', 'FAIR Data Point', '', now(), now()); + +INSERT INTO resource_definition_child (uuid, source_resource_definition_id, target_resource_definition_id, relation_uri, title, tags_uri, order_priority, created_at, updated_at) +VALUES ('b8648597-8fbd-4b89-9e30-5eab82675e42', '77aaad6a-0136-4c6e-88b9-07ffccd0ee4c', 'a0949e72-4466-4d53-8900-9436d1049a4b', 'https://w3id.org/fdp/fdp-o#metadataCatalog', 'Catalogs', 'http://www.w3.org/ns/dcat#themeTaxonomy', 1, now(), now()); + +INSERT INTO metadata_schema_usage (uuid, resource_definition_id, metadata_schema_id, order_priority) +VALUES ('9b3a32a8-a14c-4eb0-ba02-3aa8e13a8f11', '77aaad6a-0136-4c6e-88b9-07ffccd0ee4c', 'a92958ab-a414-47e6-8e17-68ba96ba3a2b', 1); diff --git a/src/main/resources/dev/db/migration/V0001.4__dev-data-membership.sql b/src/main/resources/dev/db/migration/V0001.4__dev-data-membership.sql new file mode 100644 index 000000000..9e699a971 --- /dev/null +++ b/src/main/resources/dev/db/migration/V0001.4__dev-data-membership.sql @@ -0,0 +1,43 @@ +-- +-- The MIT License +-- Copyright © 2017 DTL +-- +-- Permission is hereby granted, free of charge, to any person obtaining a copy +-- of this software and associated documentation files (the "Software"), to deal +-- in the Software without restriction, including without limitation the rights +-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +-- copies of the Software, and to permit persons to whom the Software is +-- furnished to do so, subject to the following conditions: +-- +-- The above copyright notice and this permission notice shall be included in +-- all copies or substantial portions of the Software. +-- +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +-- THE SOFTWARE. +-- + +INSERT INTO membership (uuid, name, allowed_entities, created_at, updated_at) +VALUES ('49f2bcfd-ef0a-4a3a-a1a3-0fc72a6892a8', 'Owner', ARRAY ['a0949e72-4466-4d53-8900-9436d1049a4b', '2f08228e-1789-40f8-84cd-28e3288c3604', '02c649de-c579-43bb-b470-306abdc808c7'], NOW(), NOW()); + +INSERT INTO membership (uuid, name, allowed_entities, created_at, updated_at) +VALUES ('87a2d984-7db2-43f6-805c-6b0040afead5', 'Data Provider', ARRAY ['a0949e72-4466-4d53-8900-9436d1049a4b'], NOW(), NOW()); + +INSERT INTO membership_permission (uuid, membership_id, mask, code, created_at, updated_at) +VALUES ('e0d9f853-637b-4c50-9ad9-07b6349bf76f', '49f2bcfd-ef0a-4a3a-a1a3-0fc72a6892a8', 2, 'W', NOW(), NOW()); + +INSERT INTO membership_permission (uuid, membership_id, mask, code, created_at, updated_at) +VALUES ('de4e4f85-f11d-475b-b6f0-33bdfe5f923a', '49f2bcfd-ef0a-4a3a-a1a3-0fc72a6892a8', 4, 'C', NOW(), NOW()); + +INSERT INTO membership_permission (uuid, membership_id, mask, code, created_at, updated_at) +VALUES ('60bebbf0-210d-4b05-af85-ca1b58546261', '49f2bcfd-ef0a-4a3a-a1a3-0fc72a6892a8', 8, 'D', NOW(), NOW()); + +INSERT INTO membership_permission (uuid, membership_id, mask, code, created_at, updated_at) +VALUES ('36c3b6e9-f2e3-48b7-bae1-4dc3196a3657', '49f2bcfd-ef0a-4a3a-a1a3-0fc72a6892a8', 16, 'A', NOW(), NOW()); + +INSERT INTO membership_permission (uuid, membership_id, mask, code, created_at, updated_at) +VALUES ('589d09d3-1c29-4c6f-97fc-6ea4e007fb85', '87a2d984-7db2-43f6-805c-6b0040afead5', 4, 'C', NOW(), NOW()); diff --git a/src/main/resources/dev/db/migration/V0001.5__dev-settings.sql b/src/main/resources/dev/db/migration/V0001.5__dev-settings.sql new file mode 100644 index 000000000..f6df63825 --- /dev/null +++ b/src/main/resources/dev/db/migration/V0001.5__dev-settings.sql @@ -0,0 +1,73 @@ +-- +-- The MIT License +-- Copyright © 2017 DTL +-- +-- Permission is hereby granted, free of charge, to any person obtaining a copy +-- of this software and associated documentation files (the "Software"), to deal +-- in the Software without restriction, including without limitation the rights +-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +-- copies of the Software, and to permit persons to whom the Software is +-- furnished to do so, subject to the following conditions: +-- +-- The above copyright notice and this permission notice shall be included in +-- all copies or substantial portions of the Software. +-- +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +-- THE SOFTWARE. +-- + +-- Settings +INSERT INTO settings (uuid, app_title, app_subtitle, ping_enabled, ping_endpoints, autocomplete_search_ns, created_at, updated_at) +VALUES ('00000000-0000-0000-0000-000000000000', 'FAIR Data Point', 'FDP Development Instance', False, ARRAY ['https://home.fairdatapoint.org'], True, now(), now()); + +-- Autocomplete Sources +INSERT INTO settings_autocomplete_source (uuid, settings_id, rdf_type, sparql_endpoint, sparql_query, order_priority, created_at, updated_at) +VALUES ('d4045a98-dd25-493e-a0b1-d704921c0930', '00000000-0000-0000-0000-000000000000', 'http://www.w3.org/2000/01/rdf-schema#Class', 'http://localhost:3030/ds/query', +'SELECT DISTINCT ?uri ?label +WHERE { ?uri a . +?uri ?label . +FILTER regex(?label, ".*%s.*", "i") } +ORDER BY ?label', + 1, now(), now()); + +-- Search Filters: Type +INSERT INTO settings_search_filter (uuid, settings_id, type, label, predicate, query_records, order_priority, created_at, updated_at) +VALUES ('57a98728-ce8c-4e7f-b0f8-94e2668b44d3', '00000000-0000-0000-0000-000000000000', 'IRI', 'Type', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', False, 1, now(), now()); + +INSERT INTO settings_search_filter_item (uuid, filter_id, label, value, order_priority, created_at, updated_at) +VALUES ('b48c2c7f-d7fb-47ae-a72c-b1b360e16f6e', '57a98728-ce8c-4e7f-b0f8-94e2668b44d3', 'Catalog', 'http://www.w3.org/ns/dcat#Catalog', 1, now(), now()); + +INSERT INTO settings_search_filter_item (uuid, filter_id, label, value, order_priority, created_at, updated_at) +VALUES ('3e1598ac-9d29-47f0-8e7b-3c26ca0134a0', '57a98728-ce8c-4e7f-b0f8-94e2668b44d3', 'Dataset', 'http://www.w3.org/ns/dcat#Dataset', 2, now(), now()); + +INSERT INTO settings_search_filter_item (uuid, filter_id, label, value, order_priority, created_at, updated_at) +VALUES ('5697d8d9-f09d-4ebe-b834-b37eb0624c3f', '57a98728-ce8c-4e7f-b0f8-94e2668b44d3', 'Distribution', 'http://www.w3.org/ns/dcat#Distribution', 3, now(), now()); + +INSERT INTO settings_search_filter_item (uuid, filter_id, label, value, order_priority, created_at, updated_at) +VALUES ('022c3bc6-0598-408c-8d2e-b486dafb73dd', '57a98728-ce8c-4e7f-b0f8-94e2668b44d3', 'Data Service', 'http://www.w3.org/ns/dcat#DataService', 4, now(), now()); + +INSERT INTO settings_search_filter_item (uuid, filter_id, label, value, order_priority, created_at, updated_at) +VALUES ('7cee5591-8620-4fea-b883-a94285012b8d', '57a98728-ce8c-4e7f-b0f8-94e2668b44d3', 'Metadata Service', 'https://w3id.org/fdp/fdp-o#MetadataService', 5, now(), now()); + +INSERT INTO settings_search_filter_item (uuid, filter_id, label, value, order_priority, created_at, updated_at) +VALUES ('9d661dca-8017-4dba-b930-cd2834ea59e8', '57a98728-ce8c-4e7f-b0f8-94e2668b44d3', 'FAIR Data Point', 'https://w3id.org/fdp/fdp-o#FAIRDataPoint', 6, now(), now()); + +-- Search Filters: License +INSERT INTO settings_search_filter (uuid, settings_id, type, label, predicate, query_records, order_priority, created_at, updated_at) +VALUES ('26913eb3-67dd-45c9-b8ff-4c97e8162a9b', '00000000-0000-0000-0000-000000000000', 'IRI', 'License', 'http://purl.org/dc/terms/license', True, 2, now(), now()); + +-- Search Filters: License +INSERT INTO settings_search_filter (uuid, settings_id, type, label, predicate, query_records, order_priority, created_at, updated_at) +VALUES ('cb25afb4-6169-42f8-bde5-181c803773a8', '00000000-0000-0000-0000-000000000000', 'IRI', 'Version', 'http://www.w3.org/ns/dcat#version', True, 3, now(), now()); + +-- Metrics +INSERT INTO settings_metric (uuid, settings_id, metric_uri, resource_uri, order_priority, created_at, updated_at) +VALUES ('8435491b-c16c-4457-ae94-e0f4128603d5', '00000000-0000-0000-0000-000000000000', 'https://purl.org/fair-metrics/FM_F1A', 'https://www.ietf.org/rfc/rfc3986.txt', 1, now(), now()); + +INSERT INTO settings_metric (uuid, settings_id, metric_uri, resource_uri, order_priority, created_at, updated_at) +VALUES ('af93d36a-0af0-4054-8c00-2675d460b231', '00000000-0000-0000-0000-000000000000', 'https://purl.org/fair-metrics/FM_A1.1', 'https://www.wikidata.org/wiki/Q8777', 2, now(), now()); diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/shape-catalog.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/fixtures/shape-catalog.ttl similarity index 100% rename from src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/shape-catalog.ttl rename to src/main/resources/nl/dtls/fairdatapoint/database/fixtures/shape-catalog.ttl diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/shape-custom-edited.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/fixtures/shape-custom-edited.ttl similarity index 100% rename from src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/shape-custom-edited.ttl rename to src/main/resources/nl/dtls/fairdatapoint/database/fixtures/shape-custom-edited.ttl diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/shape-custom.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/fixtures/shape-custom.ttl similarity index 100% rename from src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/shape-custom.ttl rename to src/main/resources/nl/dtls/fairdatapoint/database/fixtures/shape-custom.ttl diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/shape-data-service.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/fixtures/shape-data-service.ttl similarity index 100% rename from src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/shape-data-service.ttl rename to src/main/resources/nl/dtls/fairdatapoint/database/fixtures/shape-data-service.ttl diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/shape-dataset.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/fixtures/shape-dataset.ttl similarity index 100% rename from src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/shape-dataset.ttl rename to src/main/resources/nl/dtls/fairdatapoint/database/fixtures/shape-dataset.ttl diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/shape-distribution.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/fixtures/shape-distribution.ttl similarity index 100% rename from src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/shape-distribution.ttl rename to src/main/resources/nl/dtls/fairdatapoint/database/fixtures/shape-distribution.ttl diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/shape-fdp.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/fixtures/shape-fdp.ttl similarity index 100% rename from src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/shape-fdp.ttl rename to src/main/resources/nl/dtls/fairdatapoint/database/fixtures/shape-fdp.ttl diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/shape-metadata-service.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/fixtures/shape-metadata-service.ttl similarity index 100% rename from src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/shape-metadata-service.ttl rename to src/main/resources/nl/dtls/fairdatapoint/database/fixtures/shape-metadata-service.ttl diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/shape-resource.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/fixtures/shape-resource.ttl similarity index 100% rename from src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/development/schema/data/shape-resource.ttl rename to src/main/resources/nl/dtls/fairdatapoint/database/fixtures/shape-resource.ttl diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-catalog.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-catalog.ttl deleted file mode 100644 index a3ec568c1..000000000 --- a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-catalog.ttl +++ /dev/null @@ -1,24 +0,0 @@ -@prefix : . -@prefix sh: . -@prefix dcat: . -@prefix dct: . -@prefix foaf: . -@prefix dash: . - -:CatalogShape a sh:NodeShape ; - sh:targetClass dcat:Catalog ; - sh:property [ - sh:path dct:isPartOf ; - sh:nodeKind sh:IRI ; - sh:minCount 1 ; - sh:maxCount 1 ; - ], - [ - sh:path foaf:homePage ; - sh:maxCount 1 ; - ], - [ - sh:path dcat:themeTaxonomy ; - sh:nodeKind sh:IRI ; - dash:viewer dash:LabelViewer ; - ] . diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-dataset.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-dataset.ttl deleted file mode 100644 index 8f5b142ff..000000000 --- a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-dataset.ttl +++ /dev/null @@ -1,36 +0,0 @@ -@prefix : . -@prefix sh: . -@prefix dcat: . -@prefix dct: . -@prefix dash: . - -:DatasetShape a sh:NodeShape ; - sh:targetClass dcat:Dataset ; - sh:property [ - sh:path dct:isPartOf ; - sh:nodeKind sh:IRI ; - sh:minCount 1 ; - sh:maxCount 1 ; - ], - [ - sh:path dcat:landingPage ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - ], - [ - sh:path dcat:theme ; - sh:nodeKind sh:IRI ; - dash:editor dash:URIEditor ; - dash:viewer dash:LabelViewer ; - ], - [ - sh:path dcat:keyword ; - sh:nodeKind sh:Literal ; - dash:editor dash:TextFieldEditor ; - dash:viewer dash:LiteralViewer ; - ], - [ - sh:path dcat:contactPoint ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - ] . diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-distribution.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-distribution.ttl deleted file mode 100644 index f03df092a..000000000 --- a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-distribution.ttl +++ /dev/null @@ -1,45 +0,0 @@ -@prefix : . -@prefix sh: . -@prefix dcat: . -@prefix dct: . -@prefix dash: . - -:DistributionShape a sh:NodeShape ; - sh:targetClass dcat:Distribution ; - sh:property [ - sh:path dct:isPartOf ; - sh:nodeKind sh:IRI ; - sh:minCount 1 ; - sh:maxCount 1 ; - ], - [ - sh:path dcat:accessURL ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - dash:editor dash:URIEditor ; - ], - [ - sh:path dcat:downloadURL ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - dash:editor dash:URIEditor ; - ], - [ - sh:path dcat:mediaType ; - sh:nodeKind sh:Literal ; - sh:minCount 1 ; - sh:maxCount 1 ; - dash:editor dash:TextFieldEditor ; - dash:viewer dash:LiteralViewer ; - ], - [ - sh:path dcat:format ; - sh:nodeKind sh:Literal ; - sh:maxCount 1 ; - dash:editor dash:TextFieldEditor ; - ], - [ - sh:path dcat:byteSize ; - sh:nodeKind sh:Literal ; - sh:maxCount 1 ; - ] . diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-repository.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-repository.ttl deleted file mode 100644 index bb7712fbc..000000000 --- a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-repository.ttl +++ /dev/null @@ -1,27 +0,0 @@ -@prefix : . -@prefix sh: . -@prefix xsd: . -@prefix r3d: . - -:RepositoryShape a sh:NodeShape ; - sh:targetClass r3d:Repository ; - sh:property [ - sh:path r3d:startDate ; - sh:datatype xsd:date ; - sh:maxCount 1 ; - ] , - [ - sh:path r3d:lastUpdate ; - sh:datatype xsd:date ; - sh:maxCount 1 ; - ] , - [ - sh:path r3d:institution ; - sh:class r3d:Institution ; - sh:maxCount 1 ; - ] , - [ - sh:path r3d:institutionCountry ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - ] . diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-resource.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-resource.ttl deleted file mode 100644 index 9662882d7..000000000 --- a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0003_shape-resource.ttl +++ /dev/null @@ -1,59 +0,0 @@ -@prefix : . -@prefix sh: . -@prefix dcat: . -@prefix dct: . -@prefix xsd: . -@prefix dash: . - -:ResourceShape a sh:NodeShape ; - sh:targetClass dcat:Resource ; - sh:property [ - sh:path dct:title ; - sh:nodeKind sh:Literal ; - sh:minCount 1 ; - sh:maxCount 1 ; - dash:editor dash:TextFieldEditor ; - ], [ - sh:path dct:description ; - sh:nodeKind sh:Literal ; - sh:maxCount 1 ; - dash:editor dash:TextAreaEditor ; - ], [ - sh:path dct:hasVersion ; - sh:name "version" ; - sh:nodeKind sh:Literal ; - sh:minCount 1 ; - sh:maxCount 1 ; - dash:editor dash:TextFieldEditor ; - dash:viewer dash:LiteralViewer ; - ], [ - sh:path dct:license ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - dash:editor dash:URIEditor ; - dash:viewer dash:LabelViewer ; - ], [ - sh:path dct:conformsTo ; - sh:name "specification" ; - sh:maxCount 1 ; - sh:nodeKind sh:IRI ; - dash:viewer dash:LabelViewer ; - ], [ - sh:path dct:language ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - dash:editor dash:URIEditor ; - dash:viewer dash:LabelViewer ; - ], [ - sh:path dct:rights ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - ], [ - sh:path dct:issued ; - sh:datatype xsd:dateTime ; - sh:maxCount 1 ; - ], [ - sh:path dct:modified ; - sh:datatype xsd:dateTime ; - sh:maxCount 1 ; - ] . diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-catalog.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-catalog.ttl deleted file mode 100644 index 6d823dd50..000000000 --- a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-catalog.ttl +++ /dev/null @@ -1,30 +0,0 @@ -@prefix : . -@prefix dash: . -@prefix dcat: . -@prefix dct: . -@prefix foaf: . -@prefix sh: . - -:CatalogShape a sh:NodeShape ; - sh:targetClass dcat:Catalog ; - sh:property [ - sh:path dct:issued ; - sh:datatype xsd:dateTime ; - sh:maxCount 1 ; - dash:viewer dash:LiteralViewer ; - ], [ - sh:path dct:modified ; - sh:datatype xsd:dateTime ; - sh:maxCount 1 ; - dash:viewer dash:LiteralViewer ; - ], [ - sh:path foaf:homePage ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - dash:editor dash:URIEditor ; - dash:viewer dash:LabelViewer ; - ], [ - sh:path dcat:themeTaxonomy ; - sh:nodeKind sh:IRI ; - dash:viewer dash:LabelViewer ; - ] . diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-dataset.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-dataset.ttl deleted file mode 100644 index a47a56a50..000000000 --- a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-dataset.ttl +++ /dev/null @@ -1,44 +0,0 @@ -@prefix : . -@prefix dash: . -@prefix dcat: . -@prefix dct: . -@prefix sh: . - -:DatasetShape a sh:NodeShape ; - sh:targetClass dcat:Dataset ; - sh:property [ - sh:path dct:issued ; - sh:datatype xsd:dateTime ; - sh:maxCount 1 ; - dash:editor dash:DatePickerEditor ; - dash:viewer dash:LiteralViewer ; - ], [ - sh:path dct:modified ; - sh:datatype xsd:dateTime ; - sh:maxCount 1 ; - dash:editor dash:DatePickerEditor ; - dash:viewer dash:LiteralViewer ; - ], [ - sh:path dcat:theme ; - sh:nodeKind sh:IRI ; - sh:minCount 1 ; - dash:editor dash:URIEditor ; - dash:viewer dash:LabelViewer ; - ], [ - sh:path dcat:contactPoint ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - dash:editor dash:URIEditor ; - dash:viewer dash:LabelViewer ; - ], [ - sh:path dcat:keyword ; - sh:nodeKind sh:Literal ; - dash:editor dash:TextFieldEditor ; - dash:viewer dash:LiteralViewer ; - ], [ - sh:path dcat:landingPage ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - dash:editor dash:URIEditor ; - dash:viewer dash:LabelViewer ; - ] . diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-distribution.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-distribution.ttl deleted file mode 100644 index a26eae1e4..000000000 --- a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-distribution.ttl +++ /dev/null @@ -1,50 +0,0 @@ -@prefix : . -@prefix dash: . -@prefix dcat: . -@prefix dct: . -@prefix sh: . - -:DistributionShape a sh:NodeShape ; - sh:targetClass dcat:Distribution ; - sh:property [ - sh:path dct:issued ; - sh:datatype xsd:dateTime ; - sh:maxCount 1 ; - dash:editor dash:DatePickerEditor ; - dash:viewer dash:LiteralViewer ; - ], [ - sh:path dct:modified ; - sh:datatype xsd:dateTime ; - sh:maxCount 1 ; - dash:editor dash:DatePickerEditor ; - dash:viewer dash:LiteralViewer ; - ], [ - sh:path dcat:accessURL ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - dash:editor dash:URIEditor ; - ], [ - sh:path dcat:downloadURL ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - dash:editor dash:URIEditor ; - ], [ - sh:path dcat:mediaType ; - sh:nodeKind sh:Literal ; - sh:minCount 1 ; - sh:maxCount 1 ; - dash:editor dash:TextFieldEditor ; - dash:viewer dash:LiteralViewer ; - ], [ - sh:path dcat:format ; - sh:nodeKind sh:Literal ; - sh:maxCount 1 ; - dash:editor dash:TextFieldEditor ; - dash:viewer dash:LiteralViewer ; - ], [ - sh:path dcat:byteSize ; - sh:nodeKind sh:Literal ; - sh:maxCount 1 ; - dash:editor dash:TextFieldEditor ; - dash:viewer dash:LiteralViewer ; - ] . diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-repository.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-repository.ttl deleted file mode 100644 index 29ade853c..000000000 --- a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-repository.ttl +++ /dev/null @@ -1,40 +0,0 @@ -@prefix : . -@prefix dash: . -@prefix dct: . -@prefix r3d: . -@prefix sh: . -@prefix xsd: . - -:RepositoryShape a sh:NodeShape ; - sh:targetClass r3d:Repository ; - sh:property [ - sh:path dct:references ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - dash:editor dash:URIEditor ; - dash:viewer dash:LabelViewer ; - ], [ - sh:path r3d:institution ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - dash:editor dash:URIEditor ; - dash:viewer dash:LabelViewer ; - ], [ - sh:path r3d:startDate ; - sh:datatype xsd:dateTime ; - sh:maxCount 1 ; - dash:editor dash:DatePickerEditor ; - dash:viewer dash:LiteralViewer ; - ], [ - sh:path r3d:lastUpdate ; - sh:datatype xsd:dateTime ; - sh:maxCount 1 ; - dash:editor dash:DatePickerEditor ; - dash:viewer dash:LiteralViewer ; - ], [ - sh:path r3d:institutionCountry ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - dash:editor dash:URIEditor ; - dash:viewer dash:LabelViewer ; - ] . diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-resource.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-resource.ttl deleted file mode 100644 index 2587f288d..000000000 --- a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0005_shape-resource.ttl +++ /dev/null @@ -1,64 +0,0 @@ -@prefix : . -@prefix dash: . -@prefix dcat: . -@prefix dct: . -@prefix foaf: . -@prefix sh: . -@prefix xsd: . - -:ResourceShape a sh:NodeShape ; - sh:targetClass dcat:Resource ; - sh:property [ - sh:path dct:title ; - sh:nodeKind sh:Literal ; - sh:minCount 1 ; - sh:maxCount 1 ; - dash:editor dash:TextFieldEditor ; - ], [ - sh:path dct:description ; - sh:nodeKind sh:Literal ; - sh:maxCount 1 ; - dash:editor dash:TextAreaEditor ; - ], [ - sh:path dct:publisher ; - sh:node :AgentShape ; - sh:minCount 1 ; - sh:maxCount 1 ; - dash:editor dash:BlankNodeEditor ; - ], [ - sh:path dct:hasVersion ; - sh:name "version" ; - sh:nodeKind sh:Literal ; - sh:minCount 1 ; - sh:maxCount 1 ; - dash:editor dash:TextFieldEditor ; - dash:viewer dash:LiteralViewer ; - ], [ - sh:path dct:language ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - dash:editor dash:URIEditor ; - dash:viewer dash:LabelViewer ; - ], [ - sh:path dct:license ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - dash:editor dash:URIEditor ; - dash:viewer dash:LabelViewer ; - ], [ - sh:path dct:rights ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - dash:editor dash:URIEditor ; - dash:viewer dash:LabelViewer ; - ] . - -:AgentShape a sh:NodeShape ; - sh:targetClass foaf:Agent ; - sh:property [ - sh:path foaf:name; - sh:nodeKind sh:Literal ; - sh:minCount 1 ; - sh:maxCount 1 ; - dash:editor dash:TextFieldEditor ; - ] . diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0011_shape-data-service.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0011_shape-data-service.ttl deleted file mode 100644 index e23084794..000000000 --- a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0011_shape-data-service.ttl +++ /dev/null @@ -1,20 +0,0 @@ -@prefix : . -@prefix dash: . -@prefix dcat: . -@prefix dct: . -@prefix sh: . -@prefix xsd: . - -:DataServiceShape a sh:NodeShape ; - sh:targetClass dcat:DataService ; - sh:property [ - sh:path dcat:endpointURL ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - ] , [ - sh:path dcat:endpointDescription ; - sh:nodeKind sh:Literal ; - sh:maxCount 1 ; - dash:editor dash:TextAreaEditor ; - dash:viewer dash:LiteralViewer ; -] . diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0011_shape-fdp.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0011_shape-fdp.ttl deleted file mode 100644 index 02acd7106..000000000 --- a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0011_shape-fdp.ttl +++ /dev/null @@ -1,47 +0,0 @@ -@prefix : . -@prefix dash: . -@prefix dct: . -@prefix fdp: . -@prefix sh: . -@prefix xsd: . - -:FDPShape a sh:NodeShape ; - sh:targetClass fdp:FAIRDataPoint ; - sh:property [ - sh:path fdp:startDate ; - sh:datatype xsd:dateTime ; - sh:maxCount 1 ; - dash:editor dash:DatePickerEditor ; - dash:viewer dash:LiteralViewer ; - ] , [ - sh:path fdp:endDate ; - sh:datatype xsd:dateTime ; - sh:maxCount 1 ; - dash:editor dash:DatePickerEditor ; - dash:viewer dash:LiteralViewer ; - ] , [ - sh:path fdp:uiLanguage ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - sh:defaultValue ; - dash:editor dash:URIEditor ; - dash:viewer dash:LabelViewer ; - ] , [ - sh:path fdp:metadataIdentifier ; - sh:nodeKind sh:IRI ; - sh:maxCount 1 ; - dash:editor dash:URIEditor ; - dash:viewer dash:LabelViewer ; - ] , [ - sh:path fdp:metadataIssued ; - sh:datatype xsd:dateTime ; - sh:maxCount 1 ; - dash:editor dash:DatePickerEditor ; - dash:viewer dash:LiteralViewer ; - ] , [ - sh:path fdp:metadataModified ; - sh:datatype xsd:dateTime ; - sh:maxCount 1 ; - dash:editor dash:DatePickerEditor ; - dash:viewer dash:LiteralViewer ; - ] . diff --git a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0011_shape-metadata-service.ttl b/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0011_shape-metadata-service.ttl deleted file mode 100644 index 3943c4675..000000000 --- a/src/main/resources/nl/dtls/fairdatapoint/database/mongo/migration/production/0011_shape-metadata-service.ttl +++ /dev/null @@ -1,6 +0,0 @@ -@prefix : . -@prefix fdp: . -@prefix sh: . - -:MetadataServiceShape a sh:NodeShape ; - sh:targetClass fdp:MetadataService . diff --git a/src/test/java/nl/dtls/fairdatapoint/BaseIntegrationTest.java b/src/test/java/nl/dtls/fairdatapoint/BaseIntegrationTest.java index 5533fd1ad..af5203646 100644 --- a/src/test/java/nl/dtls/fairdatapoint/BaseIntegrationTest.java +++ b/src/test/java/nl/dtls/fairdatapoint/BaseIntegrationTest.java @@ -24,11 +24,13 @@ import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit.jupiter.SpringExtension; @ExtendWith(SpringExtension.class) @ActiveProfiles(Profiles.TESTING) @SpringBootTest(properties = {"spring.main.allow-bean-definition-overriding=true"}) +@DirtiesContext public abstract class BaseIntegrationTest { } diff --git a/src/test/java/nl/dtls/fairdatapoint/WebIntegrationTest.java b/src/test/java/nl/dtls/fairdatapoint/WebIntegrationTest.java index fc47bde48..4b51cf2e8 100644 --- a/src/test/java/nl/dtls/fairdatapoint/WebIntegrationTest.java +++ b/src/test/java/nl/dtls/fairdatapoint/WebIntegrationTest.java @@ -22,14 +22,15 @@ */ package nl.dtls.fairdatapoint; -import nl.dtls.fairdatapoint.database.mongo.migration.development.MigrationRunner; -import nl.dtls.fairdatapoint.database.rdf.migration.development.RdfDevelopmentMigrationRunner; +import nl.dtls.fairdatapoint.database.rdf.migration.development.metadata.AclMigration; +import org.flywaydb.core.Flyway; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.extension.ExtendWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit.jupiter.SpringExtension; @@ -39,33 +40,34 @@ webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, properties = {"spring.main.allow-bean-definition-overriding=true"}) @AutoConfigureMockMvc +@DirtiesContext public abstract class WebIntegrationTest { - public static final String ADMIN_TOKEN = "Bearer eyJhbGciOiJIUzUxMiJ9" + - ".eyJzdWIiOiI5NTU4OWU1MC1kMjYxLTQ5MmItODg1Mi05MzI0ZTlhNjZhNDIiLCJpYXQiOjE2MjA4Mzg3NjUsImV4cCI6MjUzMzcwNzY4NDYxfQ" + - ".hF8SnFH_1m00bjQOja77OzPgpPbX-wJH8RUdcOOR7F-QrTRCqwOdrqDfgN1lFW0XrrIljIvYqCo20pcYTvh2Dw"; + public static final String ADMIN_TOKEN = "Bearer eyJhbGciOiJIUzI1NiJ9" + + ".eyJzdWIiOiI5NTU4OWU1MC1kMjYxLTQ5MmItODg1Mi05MzI0ZTlhNjZhNDIiLCJpYXQiOjE3MTAwNjIxMjEsImV4cCI6ODgxMTAwNjIxMjF9" + + ".yJJ8nnIWjF0OjwreTQz6s6nEgSICOE8VSV1Cjq70RmE"; - public static final String ALBERT_TOKEN = "Bearer eyJhbGciOiJIUzUxMiJ9" + - ".eyJzdWIiOiI3ZTY0ODE4ZC02Mjc2LTQ2ZmItOGJiMS03MzJlNmUwOWY3ZTkiLCJpYXQiOjE2MjA4Mzg3NDUsImV4cCI6MjUzMzcwNzY4NDYxfQ" + - ".jLq89vH-YVPzKDSe44dV8CA2jpb8Or_xPf2gboiwaMTZwF_riNaVGJaziw8uYHRAIMb4bFBBd6MHbDiwrLlZZg"; + public static final String ALBERT_TOKEN = "Bearer eyJhbGciOiJIUzI1NiJ9" + + ".eyJzdWIiOiI3ZTY0ODE4ZC02Mjc2LTQ2ZmItOGJiMS03MzJlNmUwOWY3ZTkiLCJpYXQiOjE3MTAwNjIwODIsImV4cCI6ODgxMTAwNjIwODJ9" + + ".xBT99pCVytFfg7qybVFsuPhtOTVG8tqgHVGidZXw-lA"; - public static final String NIKOLA_TOKEN = "Bearer eyJhbGciOiJIUzUxMiJ9" + - ".eyJzdWIiOiJiNWI5MmM2OS01ZWQ5LTQwNTQtOTU0ZC0wMTIxYzI5YjY4MDAiLCJpYXQiOjE2MjA4Mzg3MDgsImV4cCI6MjUzMzcwNzY4NDYxfQ" + - ".U3mPUE0fREeVlresvl6uHR-aTj3ATFYn7CsAJ0cyOhqvaICTvURewF8QPfw2WVZ4GGc8Ej46BqHI9rpwKqRxpQ"; + public static final String NIKOLA_TOKEN = "Bearer eyJhbGciOiJIUzI1NiJ9" + + ".eyJzdWIiOiJiNWI5MmM2OS01ZWQ5LTQwNTQtOTU0ZC0wMTIxYzI5YjY4MDAiLCJpYXQiOjE3MTAwNjIxNjcsImV4cCI6ODgxMTAwNjIxNjd9" + + ".Jgnb1NauGNab7KX3Ym6qG5jRGnAWAISTxNASU9cnjN0"; @Autowired protected TestRestTemplate client; @Autowired - protected MigrationRunner migrationRunner; + protected Flyway flyway; @Autowired - protected RdfDevelopmentMigrationRunner rdfDevelopmentMigrationRunner; + protected AclMigration aclMigration; @BeforeEach public void setup() { - migrationRunner.run(); - rdfDevelopmentMigrationRunner.run(); + flyway.clean(); + flyway.migrate(); + aclMigration.runMigration(); } - -} \ No newline at end of file +} diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/apikey/Detail_DELETE.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/apikey/Detail_DELETE.java index a703089c2..ebd08e186 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/apikey/Detail_DELETE.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/apikey/Detail_DELETE.java @@ -23,8 +23,9 @@ package nl.dtls.fairdatapoint.acceptance.apikey; import nl.dtls.fairdatapoint.WebIntegrationTest; -import nl.dtls.fairdatapoint.database.mongo.migration.development.apikey.data.ApiKeyFixtures; +import nl.dtls.fairdatapoint.database.db.repository.ApiKeyRepository; import nl.dtls.fairdatapoint.entity.apikey.ApiKey; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -35,6 +36,7 @@ import org.springframework.http.ResponseEntity; import java.net.URI; +import java.util.UUID; import static java.lang.String.format; import static nl.dtls.fairdatapoint.acceptance.common.ForbiddenTest.createNoUserForbiddenTestDelete; @@ -47,18 +49,18 @@ @DisplayName("DELETE /api-keys/:apikeyUuid") public class Detail_DELETE extends WebIntegrationTest { - private URI url(String uuid) { + @Autowired + private ApiKeyRepository apiKeyRepository; + + private URI url(UUID uuid) { return URI.create(format("/api-keys/%s", uuid)); } - @Autowired - private ApiKeyFixtures apikeyFixtures; - @Test @DisplayName("HTTP 204") public void res204() { // GIVEN: - ApiKey apikey = apikeyFixtures.albertApiKey(); + final ApiKey apikey = apiKeyRepository.findByUuid(KnownUUIDs.API_KEY_ALBERT_UUID).get(); RequestEntity request = RequestEntity .delete(url(apikey.getUuid())) .header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN) @@ -76,21 +78,21 @@ public void res204() { @Test @DisplayName("HTTP 403: User is not authenticated") public void res403_notAuthenticated() { - ApiKey apikey = apikeyFixtures.albertApiKey(); + final ApiKey apikey = apiKeyRepository.findByUuid(KnownUUIDs.API_KEY_ALBERT_UUID).get(); createNoUserForbiddenTestDelete(client, url(apikey.getUuid())); } @Test @DisplayName("HTTP 403: User is not an owner") public void res403_apikey() { - ApiKey apikey = apikeyFixtures.nikolaApiKey(); + final ApiKey apikey = apiKeyRepository.findByUuid(KnownUUIDs.API_KEY_NIKOLA_UUID).get(); createUserForbiddenTestDelete(client, url(apikey.getUuid())); } @Test @DisplayName("HTTP 404") public void res404() { - createAdminNotFoundTestDelete(client, url("nonExisting")); + createAdminNotFoundTestDelete(client, url(KnownUUIDs.NULL_UUID)); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/apikey/List_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/apikey/List_GET.java index e775328d2..be64bafdc 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/apikey/List_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/apikey/List_GET.java @@ -24,10 +24,8 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.apikey.ApiKeyDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.apikey.data.ApiKeyFixtures; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -49,9 +47,6 @@ private URI url() { return URI.create("/api-keys"); } - @Autowired - private ApiKeyFixtures apikeyFixtures; - @Test @DisplayName("HTTP 200") public void res200() { @@ -70,7 +65,7 @@ public void res200() { assertThat(result.getStatusCode(), is(equalTo(HttpStatus.OK))); List body = result.getBody(); assertThat(body.size(), is(equalTo(1))); - body.get(0).equals(apikeyFixtures.albertApiKey()); + body.get(0).equals(null); } @Test diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/dashboard/List_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/dashboard/List_GET.java index d1098f2f7..07ad52ea1 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/dashboard/List_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/dashboard/List_GET.java @@ -24,9 +24,9 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.dashboard.DashboardItemDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; import nl.dtls.fairdatapoint.entity.metadata.Metadata; import nl.dtls.fairdatapoint.service.member.MemberService; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; @@ -58,9 +58,6 @@ private URI url() { @Autowired private MemberService memberService; - @Autowired - private UserFixtures userFixtures; - @Test public void res200() { // GIVEN: @@ -70,8 +67,7 @@ public void res200() { .build(); ParameterizedTypeReference> responseType = new ParameterizedTypeReference<>() { }; - String nikolaUuid = userFixtures.nikola().getUuid(); - memberService.deleteMember(format("%s/catalog/catalog-1", persistentUrl), Metadata.class, nikolaUuid); + memberService.deleteMember(format("%s/catalog/catalog-1", persistentUrl), Metadata.class, KnownUUIDs.USER_NIKOLA_UUID); // WHEN: ResponseEntity> result = client.exchange(request, responseType); diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/general/SecurityTest.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/general/SecurityTest.java index 52b9566ec..5d56da544 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/general/SecurityTest.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/general/SecurityTest.java @@ -23,7 +23,9 @@ package nl.dtls.fairdatapoint.acceptance.general; import nl.dtls.fairdatapoint.WebIntegrationTest; -import nl.dtls.fairdatapoint.database.mongo.migration.development.apikey.data.ApiKeyFixtures; +import nl.dtls.fairdatapoint.database.db.repository.ApiKeyRepository; +import nl.dtls.fairdatapoint.entity.apikey.ApiKey; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import nl.dtls.fairdatapoint.util.RdfIOUtil; import nl.dtls.fairdatapoint.utils.TestRdfMetadataFixtures; import org.eclipse.rdf4j.rio.RDFFormat; @@ -45,10 +47,10 @@ public class SecurityTest extends WebIntegrationTest { @Autowired - private TestRdfMetadataFixtures testMetadataFixtures; + private ApiKeyRepository apiKeyRepository; @Autowired - private ApiKeyFixtures apiKeyFixtures; + private TestRdfMetadataFixtures testMetadataFixtures; @Test public void postRequestsAreSecured() { @@ -91,13 +93,14 @@ public void putRequestsAreSecured() { @Test public void apiKeyIsWorking() { // GIVEN: Prepare data + ApiKey apiKey = apiKeyRepository.findByUuid(KnownUUIDs.API_KEY_ALBERT_UUID).get(); String reqDto = RdfIOUtil.write(testMetadataFixtures.c1_d1_distribution1(), RDFFormat.TURTLE); // AND: Prepare request RequestEntity request = RequestEntity .post(URI.create("/distribution")) .header(HttpHeaders.CONTENT_TYPE, "text/turtle") .header(HttpHeaders.ACCEPT, "text/turtle") - .header(HttpHeaders.AUTHORIZATION, format("Bearer %s", apiKeyFixtures.ALBERT_API_KEY)) + .header(HttpHeaders.AUTHORIZATION, format("Bearer %s", apiKey.getToken())) .body(reqDto); ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { }; diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/index/admin/List_TriggerAll_POST.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/index/admin/List_TriggerAll_POST.java index 307005646..3252a8cff 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/index/admin/List_TriggerAll_POST.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/index/admin/List_TriggerAll_POST.java @@ -23,13 +23,10 @@ package nl.dtls.fairdatapoint.acceptance.index.admin; import nl.dtls.fairdatapoint.WebIntegrationTest; -import nl.dtls.fairdatapoint.api.dto.index.ping.PingDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.EventRepository; -import nl.dtls.fairdatapoint.database.mongo.repository.IndexEntryRepository; -import nl.dtls.fairdatapoint.entity.index.entry.IndexEntry; -import nl.dtls.fairdatapoint.entity.index.event.Event; -import nl.dtls.fairdatapoint.entity.index.event.EventType; -import nl.dtls.fairdatapoint.utils.TestIndexEntryFixtures; +import nl.dtls.fairdatapoint.database.db.repository.IndexEntryRepository; +import nl.dtls.fairdatapoint.database.db.repository.IndexEventRepository; +import nl.dtls.fairdatapoint.entity.index.event.IndexEvent; +import nl.dtls.fairdatapoint.entity.index.event.IndexEventType; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -50,7 +47,7 @@ public class List_TriggerAll_POST extends WebIntegrationTest { @Autowired - private EventRepository eventRepository; + private IndexEventRepository eventRepository; @Autowired private IndexEntryRepository indexEntryRepository; @@ -120,11 +117,11 @@ public void res204_triggerAll() { // WHEN ResponseEntity result = client.exchange(request, responseType); - List events = eventRepository.getAllByType(EventType.AdminTrigger); + List events = eventRepository.getAllByType(IndexEventType.ADMIN_TRIGGER); // THEN: assertThat("Correct response code is received", result.getStatusCode(), is(equalTo(HttpStatus.NO_CONTENT))); assertThat("One AdminTrigger event is created", events.size(), is(equalTo(1))); - assertThat("Records correct client URL as null", events.get(0).getAdminTrigger().getClientUrl(), is(equalTo(null))); + assertThat("Records correct client URL as null", events.get(0).getPayload().getAdminTrigger().getClientUrl(), is(equalTo(null))); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/index/admin/List_Trigger_POST.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/index/admin/List_Trigger_POST.java index 297d8fb46..c2778a467 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/index/admin/List_Trigger_POST.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/index/admin/List_Trigger_POST.java @@ -24,12 +24,12 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.index.ping.PingDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.EventRepository; -import nl.dtls.fairdatapoint.database.mongo.repository.IndexEntryRepository; -import nl.dtls.fairdatapoint.database.mongo.repository.IndexSettingsRepository; +import nl.dtls.fairdatapoint.database.db.repository.IndexEntryRepository; +import nl.dtls.fairdatapoint.database.db.repository.IndexEventRepository; +import nl.dtls.fairdatapoint.database.db.repository.IndexSettingsRepository; import nl.dtls.fairdatapoint.entity.index.entry.IndexEntry; -import nl.dtls.fairdatapoint.entity.index.event.Event; -import nl.dtls.fairdatapoint.entity.index.event.EventType; +import nl.dtls.fairdatapoint.entity.index.event.IndexEvent; +import nl.dtls.fairdatapoint.entity.index.event.IndexEventType; import nl.dtls.fairdatapoint.utils.TestIndexEntryFixtures; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -51,7 +51,7 @@ public class List_Trigger_POST extends WebIntegrationTest { @Autowired - private EventRepository eventRepository; + private IndexEventRepository eventRepository; @Autowired private IndexEntryRepository indexEntryRepository; @@ -170,12 +170,12 @@ public void res204_triggerOne() { // WHEN ResponseEntity result = client.exchange(request, responseType); - List events = eventRepository.getAllByType(EventType.AdminTrigger); + List events = eventRepository.getAllByType(IndexEventType.ADMIN_TRIGGER); // THEN: assertThat("Correct response code is received", result.getStatusCode(), is(equalTo(HttpStatus.NO_CONTENT))); assertThat("One AdminTrigger event is created", events.size(), is(equalTo(1))); - assertThat("Records correct client URL", events.get(0).getAdminTrigger().getClientUrl(), is(equalTo(entry.getClientUrl()))); + assertThat("Records correct client URL", events.get(0).getPayload().getAdminTrigger().getClientUrl(), is(equalTo(entry.getClientUrl()))); } @Test @@ -195,11 +195,11 @@ public void res404_triggerOne() { // WHEN ResponseEntity result = client.exchange(request, responseType); - List events = eventRepository.getAllByType(EventType.AdminTrigger); + List events = eventRepository.getAllByType(IndexEventType.ADMIN_TRIGGER); // THEN: assertThat("Correct response code is received", result.getStatusCode(), is(equalTo(HttpStatus.NO_CONTENT))); assertThat("One AdminTrigger event is created", events.size(), is(equalTo(1))); - assertThat("Records correct client URL", events.get(0).getAdminTrigger().getClientUrl(), is(equalTo(entry.getClientUrl()))); + assertThat("Records correct client URL", events.get(0).getPayload().getAdminTrigger().getClientUrl(), is(equalTo(entry.getClientUrl()))); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/index/entry/List_All_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/index/entry/List_All_GET.java index 33f9b3ac6..ae7fa1abf 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/index/entry/List_All_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/index/entry/List_All_GET.java @@ -24,7 +24,7 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.index.entry.IndexEntryDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.IndexEntryRepository; +import nl.dtls.fairdatapoint.database.db.repository.IndexEntryRepository; import nl.dtls.fairdatapoint.entity.index.entry.IndexEntry; import nl.dtls.fairdatapoint.entity.index.entry.IndexEntryPermit; import nl.dtls.fairdatapoint.utils.TestIndexEntryFixtures; diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/index/entry/List_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/index/entry/List_GET.java index 530e8b558..d3a16968d 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/index/entry/List_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/index/entry/List_GET.java @@ -24,7 +24,7 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.index.entry.IndexEntryDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.IndexEntryRepository; +import nl.dtls.fairdatapoint.database.db.repository.IndexEntryRepository; import nl.dtls.fairdatapoint.entity.index.entry.IndexEntry; import nl.dtls.fairdatapoint.entity.index.entry.IndexEntryPermit; import nl.dtls.fairdatapoint.utils.CustomPageImpl; diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/index/entry/List_Info_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/index/entry/List_Info_GET.java index 811716979..8853e5242 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/index/entry/List_Info_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/index/entry/List_Info_GET.java @@ -24,7 +24,7 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.index.entry.IndexEntryInfoDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.IndexEntryRepository; +import nl.dtls.fairdatapoint.database.db.repository.IndexEntryRepository; import nl.dtls.fairdatapoint.entity.index.entry.IndexEntry; import nl.dtls.fairdatapoint.utils.TestIndexEntryFixtures; import org.junit.jupiter.api.DisplayName; @@ -66,6 +66,9 @@ private URI urlWithPermit(String permitQuery) { @DisplayName("HTTP 200: list default") public void res200_listMany() { // GIVEN: Prepare request + indexEntryRepository.deleteAll(); + List entries = TestIndexEntryFixtures.entriesDefault(); + indexEntryRepository.saveAll(entries); RequestEntity request = RequestEntity .get(url()) .accept(MediaType.APPLICATION_JSON) diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/index/ping/List_POST.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/index/ping/List_POST.java index 3ff48545d..1a2988a8d 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/index/ping/List_POST.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/index/ping/List_POST.java @@ -24,7 +24,7 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.index.ping.PingDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.IndexEntryRepository; +import nl.dtls.fairdatapoint.database.db.repository.IndexEntryRepository; import nl.dtls.fairdatapoint.entity.index.entry.IndexEntry; import nl.dtls.fairdatapoint.utils.TestIndexEntryFixtures; import org.junit.jupiter.api.DisplayName; diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/index/settings/List_DELETE.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/index/settings/List_DELETE.java index bb1a0b9d5..c548a08e2 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/index/settings/List_DELETE.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/index/settings/List_DELETE.java @@ -24,10 +24,11 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.index.settings.IndexSettingsDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.IndexSettingsRepository; +import nl.dtls.fairdatapoint.database.db.repository.IndexSettingsRepository; import nl.dtls.fairdatapoint.entity.index.settings.IndexSettings; -import nl.dtls.fairdatapoint.entity.index.settings.IndexSettingsPing; -import nl.dtls.fairdatapoint.entity.index.settings.IndexSettingsRetrieval; +import nl.dtls.fairdatapoint.entity.index.settings.SettingsIndexPing; +import nl.dtls.fairdatapoint.entity.index.settings.SettingsIndexRetrieval; +import nl.dtls.fairdatapoint.service.index.settings.IndexSettingsDefaults; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -50,6 +51,9 @@ public class List_DELETE extends WebIntegrationTest { @Autowired private IndexSettingsRepository indexSettingsRepository; + @Autowired + private IndexSettingsDefaults indexSettingsDefaults; + private final ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { }; @@ -58,38 +62,30 @@ private URI url() { return URI.create("/index/settings"); } - private IndexSettings customSettings() { - return new IndexSettings() - .toBuilder() - .ping( - new IndexSettingsPing() - .toBuilder() - .denyList(Collections.singletonList("http://localhost.*$")) - .rateLimitDuration(Duration.ofMinutes(17)) - .validDuration(Duration.ofDays(5)) - .rateLimitHits(666) - .build() - ) - .retrieval( - new IndexSettingsRetrieval() - .toBuilder() - .rateLimitWait(Duration.ofHours(16)) - .timeout(Duration.ofSeconds(55)) - .build() - ) - .build(); + private IndexSettings customSettings(IndexSettings indexSettings) { + indexSettings.setPing( + SettingsIndexPing.builder() + .denyList(Collections.singletonList("http://localhost.*$")) + .rateLimitDuration(Duration.ofMinutes(17)) + .validDuration(Duration.ofDays(5)) + .rateLimitHits(666) + .build() + ); + indexSettings.setRetrieval( + SettingsIndexRetrieval.builder() + .rateLimitWait(Duration.ofHours(16)) + .timeout(Duration.ofSeconds(55)) + .build() + ); + indexSettings.setAutoPermit(false); + return indexSettings; } @Test @DisplayName("HTTP 200: default settings") public void res200_defaultSettings() { // GIVEN: prepare data - IndexSettings settings = IndexSettings - .builder() - .ping(IndexSettingsPing.getDefault()) - .retrieval(IndexSettingsRetrieval.getDefault()) - .autoPermit(true) - .build(); + IndexSettings settings = indexSettingsDefaults.getDefaults(); indexSettingsRepository.deleteAll(); // AND: prepare request @@ -118,15 +114,9 @@ public void res200_defaultSettings() { @DisplayName("HTTP 200: custom settings") public void res200_customSettings() { // GIVEN: prepare data - IndexSettings settings = IndexSettings - .builder() - .ping(IndexSettingsPing.getDefault()) - .retrieval(IndexSettingsRetrieval.getDefault()) - .autoPermit(true) - .build(); - IndexSettings customSettings = customSettings(); - indexSettingsRepository.deleteAll(); - indexSettingsRepository.insert(customSettings); + IndexSettings settings = indexSettingsDefaults.getDefaults(); + IndexSettings newSettings = customSettings(indexSettingsDefaults.getDefaults()); + indexSettingsRepository.saveAndFlush(newSettings); // AND: prepare request RequestEntity request = RequestEntity diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/index/settings/List_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/index/settings/List_GET.java index ec3832b29..bb9957080 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/index/settings/List_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/index/settings/List_GET.java @@ -24,10 +24,11 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.index.settings.IndexSettingsDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.IndexSettingsRepository; +import nl.dtls.fairdatapoint.database.db.repository.IndexSettingsRepository; import nl.dtls.fairdatapoint.entity.index.settings.IndexSettings; -import nl.dtls.fairdatapoint.entity.index.settings.IndexSettingsPing; -import nl.dtls.fairdatapoint.entity.index.settings.IndexSettingsRetrieval; +import nl.dtls.fairdatapoint.entity.index.settings.SettingsIndexPing; +import nl.dtls.fairdatapoint.entity.index.settings.SettingsIndexRetrieval; +import nl.dtls.fairdatapoint.service.index.settings.IndexSettingsDefaults; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -50,6 +51,9 @@ public class List_GET extends WebIntegrationTest { @Autowired private IndexSettingsRepository indexSettingsRepository; + @Autowired + private IndexSettingsDefaults indexSettingsDefaults; + private final ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { }; @@ -58,38 +62,30 @@ private URI url() { return URI.create("/index/settings"); } - private IndexSettings customSettings() { - return new IndexSettings() - .toBuilder() - .ping( - new IndexSettingsPing() - .toBuilder() - .denyList(Collections.singletonList("http://localhost.*$")) - .rateLimitDuration(Duration.ofMinutes(17)) - .validDuration(Duration.ofDays(5)) - .rateLimitHits(666) - .build() - ) - .retrieval( - new IndexSettingsRetrieval() - .toBuilder() - .rateLimitWait(Duration.ofHours(16)) - .timeout(Duration.ofSeconds(55)) - .build() - ) - .build(); + private IndexSettings customSettings(IndexSettings indexSettings) { + indexSettings.setPing( + SettingsIndexPing.builder() + .denyList(Collections.singletonList("http://localhost.*$")) + .rateLimitDuration(Duration.ofMinutes(17)) + .validDuration(Duration.ofDays(5)) + .rateLimitHits(666) + .build() + ); + indexSettings.setRetrieval( + SettingsIndexRetrieval.builder() + .rateLimitWait(Duration.ofHours(16)) + .timeout(Duration.ofSeconds(55)) + .build() + ); + indexSettings.setAutoPermit(false); + return indexSettings; } @Test @DisplayName("HTTP 200: default settings") public void res200_defaultSettings() { // GIVEN: prepare data - IndexSettings settings = IndexSettings - .builder() - .ping(IndexSettingsPing.getDefault()) - .retrieval(IndexSettingsRetrieval.getDefault()) - .autoPermit(true) - .build(); + IndexSettings settings = indexSettingsDefaults.getDefaults(); indexSettingsRepository.deleteAll(); // AND: prepare request @@ -119,9 +115,8 @@ public void res200_defaultSettings() { @DisplayName("HTTP 200: custom settings") public void res200_customSettings() { // GIVEN: prepare data - IndexSettings settings = customSettings(); - indexSettingsRepository.deleteAll(); - indexSettingsRepository.insert(settings); + IndexSettings settings = customSettings(indexSettingsDefaults.getDefaults()); + indexSettingsRepository.saveAndFlush(settings); // AND: prepare request RequestEntity request = RequestEntity diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/index/settings/List_PUT.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/index/settings/List_PUT.java index 41b7b74fc..dc71e500d 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/index/settings/List_PUT.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/index/settings/List_PUT.java @@ -27,10 +27,11 @@ import nl.dtls.fairdatapoint.api.dto.index.settings.IndexSettingsPingDTO; import nl.dtls.fairdatapoint.api.dto.index.settings.IndexSettingsRetrievalDTO; import nl.dtls.fairdatapoint.api.dto.index.settings.IndexSettingsUpdateDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.IndexSettingsRepository; +import nl.dtls.fairdatapoint.database.db.repository.IndexSettingsRepository; import nl.dtls.fairdatapoint.entity.index.settings.IndexSettings; -import nl.dtls.fairdatapoint.entity.index.settings.IndexSettingsPing; -import nl.dtls.fairdatapoint.entity.index.settings.IndexSettingsRetrieval; +import nl.dtls.fairdatapoint.entity.index.settings.SettingsIndexPing; +import nl.dtls.fairdatapoint.entity.index.settings.SettingsIndexRetrieval; +import nl.dtls.fairdatapoint.service.index.settings.IndexSettingsDefaults; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -53,6 +54,9 @@ public class List_PUT extends WebIntegrationTest { @Autowired private IndexSettingsRepository indexSettingsRepository; + @Autowired + private IndexSettingsDefaults indexSettingsDefaults; + private final ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { }; @@ -61,25 +65,34 @@ private URI url() { return URI.create("/index/settings"); } + private IndexSettings customSettings(IndexSettings indexSettings) { + indexSettings.setPing( + SettingsIndexPing.builder() + .denyList(Collections.singletonList("http://localhost.*$")) + .rateLimitDuration(Duration.ofMinutes(17)) + .validDuration(Duration.ofDays(5)) + .rateLimitHits(666) + .build() + ); + indexSettings.setRetrieval( + SettingsIndexRetrieval.builder() + .rateLimitWait(Duration.ofHours(16)) + .timeout(Duration.ofSeconds(55)) + .build() + ); + indexSettings.setAutoPermit(false); + return indexSettings; + } + private IndexSettings customSettings1() { return new IndexSettings() .toBuilder() - .ping( - new IndexSettingsPing() - .toBuilder() - .denyList(Collections.singletonList("http://localhost.*$")) - .rateLimitDuration(Duration.ofMinutes(17)) - .validDuration(Duration.ofDays(5)) - .rateLimitHits(666) - .build() - ) - .retrieval( - new IndexSettingsRetrieval() - .toBuilder() - .rateLimitWait(Duration.ofHours(16)) - .timeout(Duration.ofSeconds(55)) - .build() - ) + .retrievalTimeout(Duration.ofSeconds(55).toString()) + .retrievalRateLimitWait(Duration.ofHours(16).toString()) + .pingValidDuration(Duration.ofDays(5).toString()) + .pingRateLimitDuration(Duration.ofMinutes(17).toString()) + .pingRateLimitHits(666) + .pingDenyList(Collections.singletonList("http://localhost.*$")) .autoPermit(true) .build(); } @@ -155,9 +168,9 @@ public void res200_updateSettingsFromDefaults() { public void res200_updateSettingsFromCustom() { // GIVEN: prepare data IndexSettingsUpdateDTO reqDTO = customSettingsUpdateDTO(); - IndexSettings settings = customSettings1(); + IndexSettings settings = customSettings(indexSettingsDefaults.getDefaults()); indexSettingsRepository.deleteAll(); - indexSettingsRepository.insert(customSettings2()); + indexSettingsRepository.saveAndFlush(settings); // AND: prepare request RequestEntity request = RequestEntity @@ -174,12 +187,12 @@ public void res200_updateSettingsFromCustom() { assertThat("Settings are created", indexSettingsRepository.findAll().size(), is(equalTo(1))); assertThat("Correct response code is received", result.getStatusCode(), is(equalTo(HttpStatus.OK))); assertThat("Response body is not null", result.getBody(), is(notNullValue())); - assertThat("Response contains default valid duration", Objects.requireNonNull(result.getBody()).getPing().getValidDuration(), is(equalTo(settings.getPing().getValidDuration().toString()))); - assertThat("Response contains default rate limit duration", Objects.requireNonNull(result.getBody()).getPing().getRateLimitDuration(), is(equalTo(settings.getPing().getRateLimitDuration().toString()))); - assertThat("Response contains default rate limit hits", Objects.requireNonNull(result.getBody()).getPing().getRateLimitHits(), is(equalTo(settings.getPing().getRateLimitHits()))); - assertThat("Response contains default deny list", Objects.requireNonNull(result.getBody()).getPing().getDenyList(), is(equalTo(settings.getPing().getDenyList()))); - assertThat("Response contains default timeout", Objects.requireNonNull(result.getBody()).getRetrieval().getTimeout(), is(equalTo(settings.getRetrieval().getTimeout().toString()))); - assertThat("Response contains default rate limit wait", Objects.requireNonNull(result.getBody()).getRetrieval().getRateLimitWait(), is(equalTo(settings.getRetrieval().getRateLimitWait().toString()))); + assertThat("Response contains default valid duration", Objects.requireNonNull(result.getBody()).getPing().getValidDuration(), is(equalTo(reqDTO.getPing().getValidDuration()))); + assertThat("Response contains default rate limit duration", Objects.requireNonNull(result.getBody()).getPing().getRateLimitDuration(), is(equalTo(reqDTO.getPing().getRateLimitDuration()))); + assertThat("Response contains default rate limit hits", Objects.requireNonNull(result.getBody()).getPing().getRateLimitHits(), is(equalTo(reqDTO.getPing().getRateLimitHits()))); + assertThat("Response contains default deny list", Objects.requireNonNull(result.getBody()).getPing().getDenyList(), is(equalTo(reqDTO.getPing().getDenyList()))); + assertThat("Response contains default timeout", Objects.requireNonNull(result.getBody()).getRetrieval().getTimeout(), is(equalTo(reqDTO.getRetrieval().getTimeout()))); + assertThat("Response contains default rate limit wait", Objects.requireNonNull(result.getBody()).getRetrieval().getRateLimitWait(), is(equalTo(reqDTO.getRetrieval().getRateLimitWait()))); } @Test @@ -210,7 +223,6 @@ public void res400_invalidDurationFormat() { public void res400_invalidList() { // GIVEN: prepare data IndexSettingsUpdateDTO reqDTO = invalidUpdateDTO2(); - indexSettingsRepository.deleteAll(); // AND: prepare request RequestEntity request = RequestEntity diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/membership/List_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/membership/List_GET.java index f99f142ea..676510cfe 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/membership/List_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/membership/List_GET.java @@ -24,9 +24,7 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.membership.MembershipDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.membership.data.MembershipFixtures; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -47,9 +45,6 @@ private URI url() { return URI.create("/memberships"); } - @Autowired - private MembershipFixtures membershipFixtures; - @Test public void res200() { // GIVEN: @@ -67,8 +62,11 @@ public void res200() { assertThat(result.getStatusCode(), is(equalTo(HttpStatus.OK))); List body = result.getBody(); assertThat(body.size(), is(equalTo(2))); + /* Common.compare(membershipFixtures.owner(), body.get(0)); Common.compare(membershipFixtures.dataProvider(), body.get(1)); + + */ } @Test diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/List_POST.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/List_POST.java index 73ae3f2b7..b2c9f2c6f 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/List_POST.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/List_POST.java @@ -23,7 +23,6 @@ package nl.dtls.fairdatapoint.acceptance.metadata.catalog; import nl.dtls.fairdatapoint.WebIntegrationTest; -import nl.dtls.fairdatapoint.database.rdf.migration.development.metadata.RdfMetadataMigration; import nl.dtls.fairdatapoint.util.RdfIOUtil; import nl.dtls.fairdatapoint.utils.TestRdfMetadataFixtures; import org.eclipse.rdf4j.model.Model; @@ -36,7 +35,6 @@ import org.springframework.http.HttpStatus; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; -import org.springframework.security.acls.dao.AclRepository; import org.springframework.security.acls.model.AclCache; import java.net.URI; @@ -52,15 +50,9 @@ public class List_POST extends WebIntegrationTest { @Autowired private TestRdfMetadataFixtures testMetadataFixtures; - @Autowired - private AclRepository aclRepository; - @Autowired private AclCache aclCache; - @Autowired - private RdfMetadataMigration rdfMetadataMigration; - private URI url() { return URI.create("/catalog"); } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/member/Detail_DELETE.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/member/Detail_DELETE.java index 361899b31..d577907cb 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/member/Detail_DELETE.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/member/Detail_DELETE.java @@ -23,10 +23,9 @@ package nl.dtls.fairdatapoint.acceptance.metadata.catalog.member; import nl.dtls.fairdatapoint.WebIntegrationTest; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -44,9 +43,6 @@ @DisplayName("DELETE /catalog/:catalogId/members/:userUuid") public class Detail_DELETE extends WebIntegrationTest { - @Autowired - private UserFixtures userFixtures; - private URI url(String catalogId, String userUuid) { return URI.create(format("/catalog/%s/members/%s", catalogId, userUuid)); } @@ -66,7 +62,7 @@ public void res204_admin() { private void create_res204(String token) { // GIVEN: RequestEntity request = RequestEntity - .delete(url("catalog-1", userFixtures.nikola().getUuid())) + .delete(url("catalog-1", KnownUUIDs.USER_NIKOLA_UUID.toString())) .header(HttpHeaders.AUTHORIZATION, token) .build(); ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { @@ -84,7 +80,7 @@ private void create_res204(String token) { public void res403() { // GIVEN: RequestEntity request = RequestEntity - .delete(url("catalog-1", userFixtures.nikola().getUuid())) + .delete(url("catalog-1", KnownUUIDs.USER_NIKOLA_UUID.toString())) .header(HttpHeaders.AUTHORIZATION, NIKOLA_TOKEN) .build(); ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { @@ -100,7 +96,7 @@ public void res403() { @Test @DisplayName("HTTP 404: non-existing catalog") public void res404_nonExistingCatalog() { - createUserNotFoundTestDelete(client, url("nonExisting", userFixtures.albert().getUuid())); + createUserNotFoundTestDelete(client, url("nonExisting", KnownUUIDs.USER_ALBERT_UUID.toString())); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/member/Detail_PUT.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/member/Detail_PUT.java index b07b13344..0ca3578b7 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/member/Detail_PUT.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/member/Detail_PUT.java @@ -26,9 +26,12 @@ import nl.dtls.fairdatapoint.api.dto.error.ErrorDTO; import nl.dtls.fairdatapoint.api.dto.member.MemberCreateDTO; import nl.dtls.fairdatapoint.api.dto.member.MemberDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.membership.data.MembershipFixtures; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; +import nl.dtls.fairdatapoint.database.db.repository.MembershipRepository; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; +import nl.dtls.fairdatapoint.entity.membership.Membership; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import nl.dtls.fairdatapoint.service.member.MemberMapper; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -36,6 +39,7 @@ import org.springframework.http.*; import java.net.URI; +import java.util.UUID; import static java.lang.String.format; import static nl.dtls.fairdatapoint.acceptance.common.NotFoundTest.createUserNotFoundTestPut; @@ -47,20 +51,20 @@ public class Detail_PUT extends WebIntegrationTest { @Autowired - private UserFixtures userFixtures; + private MemberMapper memberMapper; @Autowired - private MembershipFixtures membershipFixtures; + private UserAccountRepository userAccountRepository; @Autowired - private MemberMapper memberMapper; + private MembershipRepository membershipRepository; - private URI url(String catalogId, String userUuid) { + private URI url(String catalogId, UUID userUuid) { return URI.create(format("/catalog/%s/members/%s", catalogId, userUuid)); } private MemberCreateDTO reqDto() { - return new MemberCreateDTO(membershipFixtures.owner().getUuid()); + return new MemberCreateDTO(KnownUUIDs.MEMBERSHIP_OWNER_UUID.toString()); } @Test @@ -77,8 +81,10 @@ public void res200_admin() { private void create_res200(String token) { // GIVEN: + final UserAccount nikola = userAccountRepository.findByUuid(KnownUUIDs.USER_NIKOLA_UUID).get(); + final Membership owner = membershipRepository.findByUuid(KnownUUIDs.MEMBERSHIP_OWNER_UUID).get(); RequestEntity request = RequestEntity - .put(url("catalog-1", userFixtures.nikola().getUuid())) + .put(url("catalog-1", KnownUUIDs.USER_NIKOLA_UUID)) .header(HttpHeaders.AUTHORIZATION, token) .accept(MediaType.APPLICATION_JSON) .body(reqDto()); @@ -86,7 +92,7 @@ private void create_res200(String token) { }; // AND: prepare expectation - MemberDTO expDto = memberMapper.toDTO(userFixtures.nikola(), membershipFixtures.owner()); + MemberDTO expDto = memberMapper.toDTO(nikola, owner); // WHEN: ResponseEntity result = client.exchange(request, responseType); @@ -101,7 +107,7 @@ private void create_res200(String token) { public void res400_nonExistingUser() { // GIVEN: RequestEntity request = RequestEntity - .put(url("catalog-1", "nonExisting")) + .put(url("catalog-1", KnownUUIDs.NULL_UUID)) .header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN) .accept(MediaType.APPLICATION_JSON) .body(reqDto()); @@ -121,7 +127,7 @@ public void res400_nonExistingUser() { public void res403() { // GIVEN: RequestEntity request = RequestEntity - .put(url("catalog-1", userFixtures.nikola().getUuid())) + .put(url("catalog-1", KnownUUIDs.USER_NIKOLA_UUID)) .header(HttpHeaders.AUTHORIZATION, NIKOLA_TOKEN) .accept(MediaType.APPLICATION_JSON) .body(reqDto()); @@ -138,7 +144,7 @@ public void res403() { @Test @DisplayName("HTTP 404: non-existing catalog") public void res404_nonExistingCatalog() { - createUserNotFoundTestPut(client, url("nonExisting", userFixtures.albert().getUuid()), reqDto()); + createUserNotFoundTestPut(client, url("nonExisting", KnownUUIDs.USER_ALBERT_UUID), reqDto()); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/member/List_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/member/List_GET.java index 9187c17c4..96111cff2 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/member/List_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/member/List_GET.java @@ -25,9 +25,12 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.error.ErrorDTO; import nl.dtls.fairdatapoint.api.dto.member.MemberDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.membership.data.MembershipFixtures; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; +import nl.dtls.fairdatapoint.database.db.repository.MembershipRepository; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; +import nl.dtls.fairdatapoint.entity.membership.Membership; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import nl.dtls.fairdatapoint.service.member.MemberMapper; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -50,13 +53,13 @@ public class List_GET extends WebIntegrationTest { @Autowired - private UserFixtures userFixtures; + private MemberMapper memberMapper; @Autowired - private MembershipFixtures membershipFixtures; + private UserAccountRepository userAccountRepository; @Autowired - private MemberMapper memberMapper; + private MembershipRepository membershipRepository; private URI url(String id) { return URI.create(format("/catalog/%s/members", id)); @@ -76,6 +79,10 @@ public void res200_admin() { private void create_res200(String token) { // GIVEN: + final UserAccount albert = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); + final UserAccount nikola = userAccountRepository.findByUuid(KnownUUIDs.USER_NIKOLA_UUID).get(); + final Membership owner = membershipRepository.findByUuid(KnownUUIDs.MEMBERSHIP_OWNER_UUID).get(); + final Membership dataProvider = membershipRepository.findByUuid(KnownUUIDs.MEMBERSHIP_DATAPROVIDER_UUID).get(); RequestEntity request = RequestEntity .get(url("catalog-1")) .header(HttpHeaders.AUTHORIZATION, token) @@ -84,8 +91,8 @@ private void create_res200(String token) { }; // AND: prepare expectation - MemberDTO nikolaMember = memberMapper.toDTO(userFixtures.nikola(), membershipFixtures.dataProvider()); - MemberDTO albertMember = memberMapper.toDTO(userFixtures.albert(), membershipFixtures.owner()); + MemberDTO nikolaMember = memberMapper.toDTO(nikola, dataProvider); + MemberDTO albertMember = memberMapper.toDTO(albert, owner); List expDto = List.of(nikolaMember, albertMember); // WHEN: diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/meta/List_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/meta/List_GET.java index 427c0f21f..b0452e63b 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/meta/List_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/catalog/meta/List_GET.java @@ -26,10 +26,13 @@ import nl.dtls.fairdatapoint.api.dto.member.MemberDTO; import nl.dtls.fairdatapoint.api.dto.metadata.MetaDTO; import nl.dtls.fairdatapoint.api.dto.metadata.MetaStateDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.membership.data.MembershipFixtures; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; +import nl.dtls.fairdatapoint.database.db.repository.MembershipRepository; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; +import nl.dtls.fairdatapoint.entity.membership.Membership; import nl.dtls.fairdatapoint.entity.metadata.MetadataState; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import nl.dtls.fairdatapoint.service.member.MemberMapper; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -55,13 +58,13 @@ public class List_GET extends WebIntegrationTest { @Autowired - private UserFixtures userFixtures; + private MemberMapper memberMapper; @Autowired - private MembershipFixtures membershipFixtures; + private UserAccountRepository userAccountRepository; @Autowired - private MemberMapper memberMapper; + private MembershipRepository membershipRepository; @Autowired @Qualifier("persistentUrl") @@ -75,6 +78,8 @@ private URI url(String id) { @DisplayName("HTTP 200") public void res200() { // GIVEN: + final UserAccount albert = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); + final Membership owner = membershipRepository.findByUuid(KnownUUIDs.MEMBERSHIP_OWNER_UUID).get(); RequestEntity request = RequestEntity .get(url("catalog-1")) .header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN) @@ -84,7 +89,7 @@ public void res200() { }; // AND: prepare expectation - MemberDTO expMember = memberMapper.toDTO(userFixtures.albert(), membershipFixtures.owner()); + MemberDTO expMember = memberMapper.toDTO(albert, owner); // WHEN: ResponseEntity result = client.exchange(request, responseType); diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/dataset/member/Detail_DELETE.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/dataset/member/Detail_DELETE.java index a619541d4..014db2016 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/dataset/member/Detail_DELETE.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/dataset/member/Detail_DELETE.java @@ -23,10 +23,9 @@ package nl.dtls.fairdatapoint.acceptance.metadata.dataset.member; import nl.dtls.fairdatapoint.WebIntegrationTest; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -34,6 +33,7 @@ import org.springframework.http.ResponseEntity; import java.net.URI; +import java.util.UUID; import static java.lang.String.format; import static nl.dtls.fairdatapoint.acceptance.common.NotFoundTest.createUserNotFoundTestDelete; @@ -44,10 +44,7 @@ @DisplayName("DELETE /dataset/:datasetId/members/:userUuid") public class Detail_DELETE extends WebIntegrationTest { - @Autowired - private UserFixtures userFixtures; - - private URI url(String datasetId, String userUuid) { + private URI url(String datasetId, UUID userUuid) { return URI.create(format("/dataset/%s/members/%s", datasetId, userUuid)); } @@ -66,7 +63,7 @@ public void res204_admin() { private void create_res204(String token) { // GIVEN: RequestEntity request = RequestEntity - .delete(url("dataset-1", userFixtures.nikola().getUuid())) + .delete(url("dataset-1", KnownUUIDs.USER_NIKOLA_UUID)) .header(HttpHeaders.AUTHORIZATION, token) .build(); ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { @@ -84,7 +81,7 @@ private void create_res204(String token) { public void res403() { // GIVEN: RequestEntity request = RequestEntity - .delete(url("dataset-2", userFixtures.nikola().getUuid())) + .delete(url("dataset-2", KnownUUIDs.USER_NIKOLA_UUID)) .header(HttpHeaders.AUTHORIZATION, NIKOLA_TOKEN) .build(); ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { @@ -100,7 +97,7 @@ public void res403() { @Test @DisplayName("HTTP 404: non-existing dataset") public void res404_nonExistingCatalog() { - createUserNotFoundTestDelete(client, url("nonExisting", userFixtures.albert().getUuid())); + createUserNotFoundTestDelete(client, url("nonExisting", KnownUUIDs.USER_NIKOLA_UUID)); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/dataset/member/Detail_PUT.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/dataset/member/Detail_PUT.java index 6d7a9eb24..d0e83069c 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/dataset/member/Detail_PUT.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/dataset/member/Detail_PUT.java @@ -26,9 +26,12 @@ import nl.dtls.fairdatapoint.api.dto.error.ErrorDTO; import nl.dtls.fairdatapoint.api.dto.member.MemberCreateDTO; import nl.dtls.fairdatapoint.api.dto.member.MemberDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.membership.data.MembershipFixtures; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; +import nl.dtls.fairdatapoint.database.db.repository.MembershipRepository; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; +import nl.dtls.fairdatapoint.entity.membership.Membership; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import nl.dtls.fairdatapoint.service.member.MemberMapper; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -36,6 +39,7 @@ import org.springframework.http.*; import java.net.URI; +import java.util.UUID; import static java.lang.String.format; import static nl.dtls.fairdatapoint.acceptance.common.NotFoundTest.createUserNotFoundTestPut; @@ -47,20 +51,20 @@ public class Detail_PUT extends WebIntegrationTest { @Autowired - private UserFixtures userFixtures; + private MemberMapper memberMapper; @Autowired - private MembershipFixtures membershipFixtures; + private UserAccountRepository userAccountRepository; @Autowired - private MemberMapper memberMapper; + private MembershipRepository membershipRepository; - private URI url(String datasetId, String userUuid) { + private URI url(String datasetId, UUID userUuid) { return URI.create(format("/dataset/%s/members/%s", datasetId, userUuid)); } private MemberCreateDTO reqDto() { - return new MemberCreateDTO(membershipFixtures.owner().getUuid()); + return new MemberCreateDTO(KnownUUIDs.MEMBERSHIP_OWNER_UUID.toString()); } @Test @@ -77,8 +81,10 @@ public void res200_admin() { private void create_res200(String token) { // GIVEN: + final UserAccount nikola = userAccountRepository.findByUuid(KnownUUIDs.USER_NIKOLA_UUID).get(); + final Membership owner = membershipRepository.findByUuid(KnownUUIDs.MEMBERSHIP_OWNER_UUID).get(); RequestEntity request = RequestEntity - .put(url("dataset-1", userFixtures.nikola().getUuid())) + .put(url("dataset-1", KnownUUIDs.USER_NIKOLA_UUID)) .header(HttpHeaders.AUTHORIZATION, token) .accept(MediaType.APPLICATION_JSON) .body(reqDto()); @@ -86,7 +92,7 @@ private void create_res200(String token) { }; // AND: prepare expectation - MemberDTO expDto = memberMapper.toDTO(userFixtures.nikola(), membershipFixtures.owner()); + MemberDTO expDto = memberMapper.toDTO(nikola, owner); // WHEN: ResponseEntity result = client.exchange(request, responseType); @@ -101,7 +107,7 @@ private void create_res200(String token) { public void res400_nonExistingUser() { // GIVEN: RequestEntity request = RequestEntity - .put(url("dataset-1", "nonExisting")) + .put(url("dataset-1", KnownUUIDs.NULL_UUID)) .header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN) .accept(MediaType.APPLICATION_JSON) .body(reqDto()); @@ -121,7 +127,7 @@ public void res400_nonExistingUser() { public void res403() { // GIVEN: RequestEntity request = RequestEntity - .put(url("dataset-2", userFixtures.nikola().getUuid())) + .put(url("dataset-2", KnownUUIDs.USER_NIKOLA_UUID)) .header(HttpHeaders.AUTHORIZATION, NIKOLA_TOKEN) .accept(MediaType.APPLICATION_JSON) .body(reqDto()); @@ -138,7 +144,7 @@ public void res403() { @Test @DisplayName("HTTP 404: non-existing dataset") public void res404_nonExistingCatalog() { - createUserNotFoundTestPut(client, url("nonExisting", userFixtures.albert().getUuid()), reqDto()); + createUserNotFoundTestPut(client, url("nonExisting", KnownUUIDs.USER_ALBERT_UUID), reqDto()); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/dataset/member/List_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/dataset/member/List_GET.java index 7b50608fc..341473214 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/dataset/member/List_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/dataset/member/List_GET.java @@ -25,9 +25,12 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.error.ErrorDTO; import nl.dtls.fairdatapoint.api.dto.member.MemberDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.membership.data.MembershipFixtures; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; +import nl.dtls.fairdatapoint.database.db.repository.MembershipRepository; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; +import nl.dtls.fairdatapoint.entity.membership.Membership; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import nl.dtls.fairdatapoint.service.member.MemberMapper; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -50,13 +53,13 @@ public class List_GET extends WebIntegrationTest { @Autowired - private UserFixtures userFixtures; + private MemberMapper memberMapper; @Autowired - private MembershipFixtures membershipFixtures; + private UserAccountRepository userAccountRepository; @Autowired - private MemberMapper memberMapper; + private MembershipRepository membershipRepository; private URI url(String id) { return URI.create(format("/dataset/%s/members", id)); @@ -76,6 +79,9 @@ public void res200_admin() { private void create_res200(String token) { // GIVEN: + final UserAccount albert = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); + final UserAccount nikola = userAccountRepository.findByUuid(KnownUUIDs.USER_NIKOLA_UUID).get(); + final Membership owner = membershipRepository.findByUuid(KnownUUIDs.MEMBERSHIP_OWNER_UUID).get(); RequestEntity request = RequestEntity .get(url("dataset-1")) .header(HttpHeaders.AUTHORIZATION, token) @@ -84,8 +90,8 @@ private void create_res200(String token) { }; // AND: prepare expectation - MemberDTO nikolaMember = memberMapper.toDTO(userFixtures.nikola(), membershipFixtures.owner()); - MemberDTO albertMember = memberMapper.toDTO(userFixtures.albert(), membershipFixtures.owner()); + MemberDTO nikolaMember = memberMapper.toDTO(nikola, owner); + MemberDTO albertMember = memberMapper.toDTO(albert, owner); List expDto = List.of(nikolaMember, albertMember); // WHEN: diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/dataset/meta/List_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/dataset/meta/List_GET.java index a9c5c1117..6ee188a7f 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/dataset/meta/List_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/dataset/meta/List_GET.java @@ -26,16 +26,18 @@ import nl.dtls.fairdatapoint.api.dto.member.MemberDTO; import nl.dtls.fairdatapoint.api.dto.metadata.MetaDTO; import nl.dtls.fairdatapoint.api.dto.metadata.MetaStateDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.membership.data.MembershipFixtures; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; +import nl.dtls.fairdatapoint.database.db.repository.MembershipRepository; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; +import nl.dtls.fairdatapoint.entity.membership.Membership; import nl.dtls.fairdatapoint.entity.metadata.MetadataState; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import nl.dtls.fairdatapoint.service.member.MemberMapper; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.core.ParameterizedTypeReference; -import org.springframework.data.mongodb.core.query.Meta; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.RequestEntity; @@ -56,13 +58,13 @@ public class List_GET extends WebIntegrationTest { @Autowired - private UserFixtures userFixtures; + private MemberMapper memberMapper; @Autowired - private MembershipFixtures membershipFixtures; + private UserAccountRepository userAccountRepository; @Autowired - private MemberMapper memberMapper; + private MembershipRepository membershipRepository; @Autowired @Qualifier("persistentUrl") @@ -76,6 +78,8 @@ private URI url(String id) { @DisplayName("HTTP 200") public void res200() { // GIVEN: + final UserAccount albert = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); + final Membership owner = membershipRepository.findByUuid(KnownUUIDs.MEMBERSHIP_OWNER_UUID).get(); RequestEntity request = RequestEntity .get(url("dataset-1")) .header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN) @@ -85,7 +89,7 @@ public void res200() { }; // AND: prepare expectation - MemberDTO expMember = memberMapper.toDTO(userFixtures.albert(), membershipFixtures.owner()); + MemberDTO expMember = memberMapper.toDTO(albert, owner); // WHEN: ResponseEntity result = client.exchange(request, responseType); diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/distribution/member/Detail_DELETE.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/distribution/member/Detail_DELETE.java index 9bf315997..3e78eb6d9 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/distribution/member/Detail_DELETE.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/distribution/member/Detail_DELETE.java @@ -23,10 +23,9 @@ package nl.dtls.fairdatapoint.acceptance.metadata.distribution.member; import nl.dtls.fairdatapoint.WebIntegrationTest; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; @@ -34,6 +33,7 @@ import org.springframework.http.ResponseEntity; import java.net.URI; +import java.util.UUID; import static java.lang.String.format; import static nl.dtls.fairdatapoint.acceptance.common.NotFoundTest.createUserNotFoundTestDelete; @@ -44,10 +44,7 @@ @DisplayName("DELETE /distribution/:distributionId/members/:userUuid") public class Detail_DELETE extends WebIntegrationTest { - @Autowired - private UserFixtures userFixtures; - - private URI url(String distributionId, String userUuid) { + private URI url(String distributionId, UUID userUuid) { return URI.create(format("/distribution/%s/members/%s", distributionId, userUuid)); } @@ -66,7 +63,7 @@ public void res204_admin() { private void create_res204(String token) { // GIVEN: RequestEntity request = RequestEntity - .delete(url("distribution-1", userFixtures.nikola().getUuid())) + .delete(url("distribution-1", KnownUUIDs.USER_NIKOLA_UUID)) .header(HttpHeaders.AUTHORIZATION, token) .build(); ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { @@ -84,7 +81,7 @@ private void create_res204(String token) { public void res403() { // GIVEN: RequestEntity request = RequestEntity - .delete(url("distribution-2", userFixtures.nikola().getUuid())) + .delete(url("distribution-2", KnownUUIDs.USER_NIKOLA_UUID)) .header(HttpHeaders.AUTHORIZATION, NIKOLA_TOKEN) .build(); ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { @@ -100,7 +97,7 @@ public void res403() { @Test @DisplayName("HTTP 404: non-existing distribution") public void res404_nonExistingCatalog() { - createUserNotFoundTestDelete(client, url("nonExisting", userFixtures.albert().getUuid())); + createUserNotFoundTestDelete(client, url("nonExisting", KnownUUIDs.USER_ALBERT_UUID)); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/distribution/member/Detail_PUT.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/distribution/member/Detail_PUT.java index 60ba429fe..ff98c6683 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/distribution/member/Detail_PUT.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/distribution/member/Detail_PUT.java @@ -26,9 +26,12 @@ import nl.dtls.fairdatapoint.api.dto.error.ErrorDTO; import nl.dtls.fairdatapoint.api.dto.member.MemberCreateDTO; import nl.dtls.fairdatapoint.api.dto.member.MemberDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.membership.data.MembershipFixtures; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; +import nl.dtls.fairdatapoint.database.db.repository.MembershipRepository; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; +import nl.dtls.fairdatapoint.entity.membership.Membership; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import nl.dtls.fairdatapoint.service.member.MemberMapper; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -36,6 +39,7 @@ import org.springframework.http.*; import java.net.URI; +import java.util.UUID; import static java.lang.String.format; import static nl.dtls.fairdatapoint.acceptance.common.NotFoundTest.createUserNotFoundTestPut; @@ -47,20 +51,20 @@ public class Detail_PUT extends WebIntegrationTest { @Autowired - private UserFixtures userFixtures; + private MemberMapper memberMapper; @Autowired - private MembershipFixtures membershipFixtures; + private UserAccountRepository userAccountRepository; @Autowired - private MemberMapper memberMapper; + private MembershipRepository membershipRepository; - private URI url(String distributionId, String userUuid) { + private URI url(String distributionId, UUID userUuid) { return URI.create(format("/distribution/%s/members/%s", distributionId, userUuid)); } private MemberCreateDTO reqDto() { - return new MemberCreateDTO(membershipFixtures.owner().getUuid()); + return new MemberCreateDTO(KnownUUIDs.MEMBERSHIP_OWNER_UUID.toString()); } @Test @@ -77,8 +81,10 @@ public void res200_admin() { private void create_res200(String token) { // GIVEN: + final UserAccount nikola = userAccountRepository.findByUuid(KnownUUIDs.USER_NIKOLA_UUID).get(); + final Membership owner = membershipRepository.findByUuid(KnownUUIDs.MEMBERSHIP_OWNER_UUID).get(); RequestEntity request = RequestEntity - .put(url("distribution-1", userFixtures.nikola().getUuid())) + .put(url("distribution-1", KnownUUIDs.USER_NIKOLA_UUID)) .header(HttpHeaders.AUTHORIZATION, token) .accept(MediaType.APPLICATION_JSON) .body(reqDto()); @@ -86,7 +92,7 @@ private void create_res200(String token) { }; // AND: prepare expectation - MemberDTO expDto = memberMapper.toDTO(userFixtures.nikola(), membershipFixtures.owner()); + MemberDTO expDto = memberMapper.toDTO(nikola, owner); // WHEN: ResponseEntity result = client.exchange(request, responseType); @@ -101,7 +107,7 @@ private void create_res200(String token) { public void res400_nonExistingUser() { // GIVEN: RequestEntity request = RequestEntity - .put(url("distribution-1", "nonExisting")) + .put(url("distribution-1", KnownUUIDs.NULL_UUID)) .header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN) .accept(MediaType.APPLICATION_JSON) .body(reqDto()); @@ -121,7 +127,7 @@ public void res400_nonExistingUser() { public void res403() { // GIVEN: RequestEntity request = RequestEntity - .put(url("distribution-2", userFixtures.nikola().getUuid())) + .put(url("distribution-2", KnownUUIDs.USER_NIKOLA_UUID)) .header(HttpHeaders.AUTHORIZATION, NIKOLA_TOKEN) .accept(MediaType.APPLICATION_JSON) .body(reqDto()); @@ -138,7 +144,7 @@ public void res403() { @Test @DisplayName("HTTP 404: non-existing distribution") public void res404_nonExistingCatalog() { - createUserNotFoundTestPut(client, url("nonExisting", userFixtures.albert().getUuid()), reqDto()); + createUserNotFoundTestPut(client, url("nonExisting", KnownUUIDs.USER_ALBERT_UUID), reqDto()); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/distribution/member/List_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/distribution/member/List_GET.java index 977788fbc..fa348e631 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/distribution/member/List_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/distribution/member/List_GET.java @@ -25,9 +25,12 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.error.ErrorDTO; import nl.dtls.fairdatapoint.api.dto.member.MemberDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.membership.data.MembershipFixtures; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; +import nl.dtls.fairdatapoint.database.db.repository.MembershipRepository; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; +import nl.dtls.fairdatapoint.entity.membership.Membership; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import nl.dtls.fairdatapoint.service.member.MemberMapper; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -50,13 +53,13 @@ public class List_GET extends WebIntegrationTest { @Autowired - private UserFixtures userFixtures; + private MemberMapper memberMapper; @Autowired - private MembershipFixtures membershipFixtures; + private UserAccountRepository userAccountRepository; @Autowired - private MemberMapper memberMapper; + private MembershipRepository membershipRepository; private URI url(String id) { return URI.create(format("/distribution/%s/members", id)); @@ -76,6 +79,9 @@ public void res200_admin() { private void create_res200(String token) { // GIVEN: + final UserAccount albert = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); + final UserAccount nikola = userAccountRepository.findByUuid(KnownUUIDs.USER_NIKOLA_UUID).get(); + final Membership owner = membershipRepository.findByUuid(KnownUUIDs.MEMBERSHIP_OWNER_UUID).get(); RequestEntity request = RequestEntity .get(url("distribution-1")) .header(HttpHeaders.AUTHORIZATION, token) @@ -84,8 +90,8 @@ private void create_res200(String token) { }; // AND: prepare expectation - MemberDTO nikolaMember = memberMapper.toDTO(userFixtures.nikola(), membershipFixtures.owner()); - MemberDTO albertMember = memberMapper.toDTO(userFixtures.albert(), membershipFixtures.owner()); + MemberDTO nikolaMember = memberMapper.toDTO(nikola, owner); + MemberDTO albertMember = memberMapper.toDTO(albert, owner); List expDto = List.of(nikolaMember, albertMember); // WHEN: diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/distribution/meta/List_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/distribution/meta/List_GET.java index 3b62953be..c113b5c91 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/distribution/meta/List_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/metadata/distribution/meta/List_GET.java @@ -26,10 +26,13 @@ import nl.dtls.fairdatapoint.api.dto.member.MemberDTO; import nl.dtls.fairdatapoint.api.dto.metadata.MetaDTO; import nl.dtls.fairdatapoint.api.dto.metadata.MetaStateDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.membership.data.MembershipFixtures; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; +import nl.dtls.fairdatapoint.database.db.repository.MembershipRepository; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; +import nl.dtls.fairdatapoint.entity.membership.Membership; import nl.dtls.fairdatapoint.entity.metadata.MetadataState; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import nl.dtls.fairdatapoint.service.member.MemberMapper; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -54,13 +57,13 @@ public class List_GET extends WebIntegrationTest { @Autowired - private UserFixtures userFixtures; + private MemberMapper memberMapper; @Autowired - private MembershipFixtures membershipFixtures; + private UserAccountRepository userAccountRepository; @Autowired - private MemberMapper memberMapper; + private MembershipRepository membershipRepository; private URI url(String id) { return URI.create(format("/distribution/%s/meta", id)); @@ -70,6 +73,8 @@ private URI url(String id) { @DisplayName("HTTP 200") public void res200() { // GIVEN: + final UserAccount albert = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); + final Membership owner = membershipRepository.findByUuid(KnownUUIDs.MEMBERSHIP_OWNER_UUID).get(); RequestEntity request = RequestEntity .get(url("distribution-1")) .header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN) @@ -79,7 +84,7 @@ public void res200() { }; // AND: prepare expectation - MemberDTO expMember = memberMapper.toDTO(userFixtures.albert(), membershipFixtures.owner()); + MemberDTO expMember = memberMapper.toDTO(albert, owner); // WHEN: ResponseEntity result = client.exchange(request, responseType); diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/openapi/SwaggerUI_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/openapi/SwaggerUI_GET.java index 65d8b4ee1..c0b1cdffa 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/openapi/SwaggerUI_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/openapi/SwaggerUI_GET.java @@ -23,8 +23,6 @@ package nl.dtls.fairdatapoint.acceptance.openapi; import nl.dtls.fairdatapoint.WebIntegrationTest; -import nl.dtls.fairdatapoint.api.dto.index.entry.IndexEntryDTO; -import nl.dtls.fairdatapoint.utils.CustomPageImpl; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.core.ParameterizedTypeReference; diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/Detail_DELETE.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/Detail_DELETE.java index 85def67c0..56e5d7948 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/Detail_DELETE.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/Detail_DELETE.java @@ -23,8 +23,9 @@ package nl.dtls.fairdatapoint.acceptance.resource; import nl.dtls.fairdatapoint.WebIntegrationTest; -import nl.dtls.fairdatapoint.database.mongo.migration.development.resource.data.ResourceDefinitionFixtures; +import nl.dtls.fairdatapoint.database.db.repository.ResourceDefinitionRepository; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -35,6 +36,7 @@ import org.springframework.http.ResponseEntity; import java.net.URI; +import java.util.UUID; import static java.lang.String.format; import static nl.dtls.fairdatapoint.acceptance.common.ForbiddenTest.createUserForbiddenTestDelete; @@ -46,18 +48,18 @@ @DisplayName("DELETE /resource-definitions/:resourceDefinitionUuid") public class Detail_DELETE extends WebIntegrationTest { - private URI url(String uuid) { + @Autowired + private ResourceDefinitionRepository resourceDefinitionRepository; + + private URI url(UUID uuid) { return URI.create(format("/resource-definitions/%s", uuid)); } - @Autowired - private ResourceDefinitionFixtures resourceDefinitionFixtures; - @Test @DisplayName("HTTP 204") public void res204() { // GIVEN: - ResourceDefinition resourceDefinition = resourceDefinitionFixtures.fdpDefinition(); + ResourceDefinition resourceDefinition = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); RequestEntity request = RequestEntity .delete(url(resourceDefinition.getUuid())) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) @@ -70,26 +72,25 @@ public void res204() { // THEN: assertThat(result.getStatusCode(), is(equalTo(HttpStatus.NO_CONTENT))); + assertThat("No longer present", resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).isPresent(), is(equalTo(false))); } @Test @DisplayName("HTTP 403: User is not authenticated") public void res403_notAuthenticated() { - ResourceDefinition resourceDefinition = resourceDefinitionFixtures.fdpDefinition(); - createUserForbiddenTestDelete(client, url(resourceDefinition.getUuid())); + createUserForbiddenTestDelete(client, url(KnownUUIDs.RD_DISTRIBUTION_UUID)); } @Test @DisplayName("HTTP 403: User is not an admin") public void res403_resourceDefinition() { - ResourceDefinition resourceDefinition = resourceDefinitionFixtures.fdpDefinition(); - createUserForbiddenTestDelete(client, url(resourceDefinition.getUuid())); + createUserForbiddenTestDelete(client, url(KnownUUIDs.RD_DISTRIBUTION_UUID)); } @Test @DisplayName("HTTP 404") public void res404() { - createAdminNotFoundTestDelete(client, url("nonExisting")); + createAdminNotFoundTestDelete(client, url(KnownUUIDs.NULL_UUID)); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/Detail_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/Detail_GET.java index d4e5e8a60..21fdc8fb3 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/Detail_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/Detail_GET.java @@ -23,8 +23,10 @@ package nl.dtls.fairdatapoint.acceptance.resource; import nl.dtls.fairdatapoint.WebIntegrationTest; -import nl.dtls.fairdatapoint.database.mongo.migration.development.resource.data.ResourceDefinitionFixtures; +import nl.dtls.fairdatapoint.api.dto.resource.ResourceDefinitionDTO; +import nl.dtls.fairdatapoint.database.db.repository.ResourceDefinitionRepository; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -34,6 +36,7 @@ import org.springframework.http.ResponseEntity; import java.net.URI; +import java.util.UUID; import static java.lang.String.format; import static nl.dtls.fairdatapoint.acceptance.common.NotFoundTest.createUserNotFoundTestGet; @@ -44,36 +47,39 @@ @DisplayName("GET /resource-definitions/:resourceDefinitionUuid") public class Detail_GET extends WebIntegrationTest { - private URI url(String uuid) { + @Autowired + private ResourceDefinitionRepository resourceDefinitionRepository; + + private URI url(UUID uuid) { return URI.create(format("/resource-definitions/%s", uuid)); } - @Autowired - private ResourceDefinitionFixtures resourceDefinitionFixtures; - @Test @DisplayName("HTTP 200") public void res200() { // GIVEN: - ResourceDefinition resourceDefinition = resourceDefinitionFixtures.fdpDefinition(); + ResourceDefinition resourceDefinition = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); RequestEntity request = RequestEntity .get(url(resourceDefinition.getUuid())) .build(); - ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { + ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { }; // WHEN: - ResponseEntity result = client.exchange(request, responseType); + ResponseEntity result = client.exchange(request, responseType); // THEN: assertThat(result.getStatusCode(), is(equalTo(HttpStatus.OK))); - assertThat(result.getBody(), is(equalTo(resourceDefinition))); + assertThat(result.getBody().getUuid(), is(equalTo(resourceDefinition.getUuid()))); + assertThat(result.getBody().getName(), is(equalTo(resourceDefinition.getName()))); + assertThat(result.getBody().getChildren().size(), is(equalTo(resourceDefinition.getChildren().size()))); + assertThat(result.getBody().getExternalLinks().size(), is(equalTo(resourceDefinition.getExternalLinks().size()))); } @Test @DisplayName("HTTP 404") public void res404() { - createUserNotFoundTestGet(client, url("nonExisting")); + createUserNotFoundTestGet(client, url(KnownUUIDs.NULL_UUID)); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/Detail_PUT.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/Detail_PUT.java index ff79ec5b1..a0f090e34 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/Detail_PUT.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/Detail_PUT.java @@ -24,10 +24,11 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.resource.ResourceDefinitionChangeDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.resource.data.ResourceDefinitionFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.ResourceDefinitionRepository; +import nl.dtls.fairdatapoint.api.dto.resource.ResourceDefinitionDTO; +import nl.dtls.fairdatapoint.database.db.repository.ResourceDefinitionRepository; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionMapper; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -35,6 +36,7 @@ import org.springframework.http.*; import java.net.URI; +import java.util.UUID; import static java.lang.String.format; import static nl.dtls.fairdatapoint.acceptance.common.ForbiddenTest.createNoUserForbiddenTestPut; @@ -47,10 +49,13 @@ @DisplayName("PUT /resource-definitions/:resourceDefinitionUuid") public class Detail_PUT extends WebIntegrationTest { + @Autowired + private ResourceDefinitionRepository resourceDefinitionRepository; + @Autowired private ResourceDefinitionMapper resourceDefinitionMapper; - private URI url(String uuid) { + private URI url(UUID uuid) { return URI.create(format("/resource-definitions/%s", uuid)); } @@ -60,17 +65,11 @@ private ResourceDefinitionChangeDTO reqDto(ResourceDefinition rd) { return resourceDefinitionMapper.toChangeDTO(rd); } - @Autowired - private ResourceDefinitionFixtures resourceDefinitionFixtures; - - @Autowired - private ResourceDefinitionRepository resourceDefinitionRepository; - @Test @DisplayName("HTTP 200") public void res200() { // GIVEN: Prepare data - ResourceDefinition resourceDefinition = resourceDefinitionFixtures.catalogDefinition(); + ResourceDefinition resourceDefinition = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); ResourceDefinitionChangeDTO reqDto = reqDto(resourceDefinition); // AND: Prepare request @@ -79,11 +78,11 @@ public void res200() { .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .accept(MediaType.APPLICATION_JSON) .body(reqDto); - ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { + ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { }; // WHEN: - ResponseEntity result = client.exchange(request, responseType); + ResponseEntity result = client.exchange(request, responseType); // THEN: assertThat(result.getStatusCode(), is(equalTo(HttpStatus.OK))); @@ -94,22 +93,22 @@ public void res200() { @Test @DisplayName("HTTP 403: ResourceDefinition is not authenticated") public void res403_notAuthenticated() { - ResourceDefinition resourceDefinition = resourceDefinitionFixtures.catalogDefinition(); + ResourceDefinition resourceDefinition = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); createNoUserForbiddenTestPut(client, url(resourceDefinition.getUuid()), reqDto(resourceDefinition)); } @Test @DisplayName("HTTP 403: ResourceDefinition is not an admin") public void res403_resourceDefinition() { - ResourceDefinition resourceDefinition = resourceDefinitionFixtures.catalogDefinition(); + ResourceDefinition resourceDefinition = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); createUserForbiddenTestPut(client, url(resourceDefinition.getUuid()), reqDto(resourceDefinition)); } @Test @DisplayName("HTTP 404") public void res404() { - createAdminNotFoundTestPut(client, url("nonExisting"), - reqDto(resourceDefinitionFixtures.catalogDefinition())); + ResourceDefinition resourceDefinition = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); + createAdminNotFoundTestPut(client, url(KnownUUIDs.NULL_UUID), reqDto(resourceDefinition)); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/List_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/List_GET.java index 1c8eed227..c6310783c 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/List_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/List_GET.java @@ -23,11 +23,9 @@ package nl.dtls.fairdatapoint.acceptance.resource; import nl.dtls.fairdatapoint.WebIntegrationTest; -import nl.dtls.fairdatapoint.database.mongo.migration.development.resource.data.ResourceDefinitionFixtures; -import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; +import nl.dtls.fairdatapoint.api.dto.resource.ResourceDefinitionDTO; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpStatus; import org.springframework.http.RequestEntity; @@ -47,9 +45,6 @@ private URI url() { return URI.create("/resource-definitions"); } - @Autowired - private ResourceDefinitionFixtures resourceDefinitionFixtures; - @Test @DisplayName("HTTP 200") public void res200() { @@ -57,21 +52,16 @@ public void res200() { RequestEntity request = RequestEntity .get(url()) .build(); - ParameterizedTypeReference> responseType = new ParameterizedTypeReference<>() { + ParameterizedTypeReference> responseType = new ParameterizedTypeReference<>() { }; // WHEN: - ResponseEntity> result = client.exchange(request, responseType); + ResponseEntity> result = client.exchange(request, responseType); // THEN: assertThat(result.getStatusCode(), is(equalTo(HttpStatus.OK))); - List body = result.getBody(); - assertThat(body, is(equalTo(List.of( - resourceDefinitionFixtures.fdpDefinition(), - resourceDefinitionFixtures.catalogDefinition(), - resourceDefinitionFixtures.datasetDefinition(), - resourceDefinitionFixtures.distributionDefinition() - )))); + List body = result.getBody(); + assertThat(body.size(), is(equalTo(4))); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/List_POST.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/List_POST.java index 46dbfb8d3..76a35f743 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/List_POST.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/resource/List_POST.java @@ -24,9 +24,10 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.resource.ResourceDefinitionChangeDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.resource.data.ResourceDefinitionFixtures; +import nl.dtls.fairdatapoint.database.db.repository.ResourceDefinitionRepository; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionMapper; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -45,7 +46,7 @@ public class List_POST extends WebIntegrationTest { @Autowired - private ResourceDefinitionFixtures resourceDefinitionFixtures; + private ResourceDefinitionRepository resourceDefinitionRepository; @Autowired private ResourceDefinitionMapper resourceDefinitionMapper; @@ -55,14 +56,17 @@ private URI url() { } private ResourceDefinitionChangeDTO reqDto(ResourceDefinition resourceDefinition) { - return resourceDefinitionMapper.toChangeDTO(resourceDefinition); + final ResourceDefinitionChangeDTO dto = resourceDefinitionMapper.toChangeDTO(resourceDefinition); + dto.setName("Another Distribution"); + dto.setUrlPrefix("another-distribution"); + return dto; } @Test @DisplayName("HTTP 200") public void res200() { // GIVEN: Prepare data - ResourceDefinition resourceDefinition = resourceDefinitionFixtures.ontologyDefinition(); + ResourceDefinition resourceDefinition = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); ResourceDefinitionChangeDTO reqDto = reqDto(resourceDefinition); // AND: Prepare request @@ -85,13 +89,15 @@ public void res200() { @Test @DisplayName("HTTP 403: ResourceDefinition is not authenticated") public void res403_notAuthenticated() { - createNoUserForbiddenTestPost(client, url(), reqDto(resourceDefinitionFixtures.ontologyDefinition())); + ResourceDefinition resourceDefinition = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); + createNoUserForbiddenTestPost(client, url(), reqDto(resourceDefinition)); } @Test @DisplayName("HTTP 403: ResourceDefinition is not an admin") public void res403_resourceDefinition() { - createUserForbiddenTestPost(client, url(), reqDto(resourceDefinitionFixtures.ontologyDefinition())); + ResourceDefinition resourceDefinition = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); + createUserForbiddenTestPost(client, url(), reqDto(resourceDefinition)); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Common.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Common.java index 48964c948..03fb52ae6 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Common.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Common.java @@ -27,7 +27,9 @@ import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaDraftDTO; import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaVersionDTO; import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaDraft; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaVersion; + +import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @@ -35,6 +37,30 @@ public class Common { + public static final UUID SCHEMA_SIMPLE_UUID = UUID.fromString("e8b34158-3858-45c7-8e3e-d1e671dd9929"); + public static final UUID SCHEMA_SIMPLE_V1_UUID = UUID.fromString("53619e58-2bb0-4baf-afd8-00c5d01ff8a8"); + + public static final UUID SCHEMA_INTERNAL_UUID = UUID.fromString("fe98adbb-6a2c-4c7a-b2b2-a72db5140c61"); + public static final UUID SCHEMA_INTERNAL_V1_UUID = UUID.fromString("f0a4b358-69a3-44e6-9436-c68a56a9f2f2"); + + public static final UUID SCHEMA_DRAFT_UUID = UUID.fromString("bfa79edf-00b7-4a04-b5a6-a5144f1a77b7"); + public static final UUID SCHEMA_DRAFT_V1_UUID = UUID.fromString("cb9f6cd7-97af-45d0-b23d-d0aab23607d8"); + + public static final UUID SCHEMA_MULTI_UUID = UUID.fromString("978e5c1c-268d-4822-b60b-07d3eccc6896"); + public static final UUID SCHEMA_MULTI_V1_UUID = UUID.fromString("d7acec53-5ac9-4502-9bfa-92d1e9f79a24"); + public static final UUID SCHEMA_MULTI_V2_UUID = UUID.fromString("67896adc-b431-431d-8296-f0b80d8de412"); + public static final UUID SCHEMA_MULTI_V3_UUID = UUID.fromString("c62d4a97-baac-40b8-b6ea-e43b06ec78bd"); + + public static final UUID SCHEMA_MULTI_DRAFT_UUID = UUID.fromString("123e48d2-9995-4b44-8b2c-9c81bdbf2dd2"); + public static final UUID SCHEMA_MULTI_DRAFT_V1_UUID = UUID.fromString("fb24f92b-187f-4d53-b744-73024b537f30"); + public static final UUID SCHEMA_MULTI_DRAFT_V2_UUID = UUID.fromString("6011adfa-f8da-478d-86ea-84bb644b458b"); + public static final UUID SCHEMA_MULTI_DRAFT_DRAFT_UUID = UUID.fromString("6b84ec86-2096-48db-bfc7-23506b8c080c"); + + public static final UUID SCHEMA_MULTI_EXTS_UUID = UUID.fromString("7c8b8699-ca9f-4d14-86e2-2299b27c5711"); + public static final UUID SCHEMA_MULTI_EXTS_V1_UUID = UUID.fromString("4e44fb19-b9e0-46e9-957a-e7aa3adac7bf"); + public static final UUID SCHEMA_MULTI_EXTS_V2_UUID = UUID.fromString("abcf3a21-6f9a-45dc-a71a-4dde4440c81a"); + public static final UUID SCHEMA_MULTI_EXTS_DRAFT_UUID = UUID.fromString("a6d609ff-905f-4edd-bdb1-2dce000c9a45"); + public static void compare(MetadataSchemaChangeDTO entity, MetadataSchemaDTO dto) { assertThat(dto.getName(), is(equalTo(entity.getName()))); assertThat(dto.getLatest().getDefinition(), is(equalTo(entity.getDefinition()))); @@ -45,27 +71,25 @@ public static void compare(MetadataSchemaChangeDTO entity, MetadataSchemaDraftDT assertThat(dto.getDefinition(), is(equalTo(entity.getDefinition()))); } - public static void compare(MetadataSchema entity, MetadataSchemaDTO dto) { - assertThat(dto.getUuid(), is(equalTo(entity.getUuid()))); + public static void compare(MetadataSchemaVersion entity, MetadataSchemaDTO dto) { + assertThat(dto.getUuid(), is(equalTo(entity.getSchema().getUuid()))); assertThat(dto.getName(), is(equalTo(entity.getName()))); - assertThat(dto.getLatest().getDefinition(), is(equalTo(entity.getDefinition()))); } - public static void compare(MetadataSchemaDraft entity, MetadataSchemaDTO dto) { - assertThat(dto.getUuid(), is(equalTo(entity.getUuid()))); + public static void compare(MetadataSchemaVersion entity, MetadataSchemaVersionDTO dto) { + assertThat(dto.getUuid(), is(equalTo(entity.getSchema().getUuid()))); + assertThat(dto.getVersionUuid(), is(equalTo(entity.getUuid()))); assertThat(dto.getName(), is(equalTo(entity.getName()))); - assertThat(dto.getDraft().getDefinition(), is(equalTo(entity.getDefinition()))); + assertThat(dto.getDefinition(), is(equalTo(entity.getDefinition()))); } - public static void compare(MetadataSchema entity, MetadataSchemaVersionDTO dto) { + public static void compare(MetadataSchemaVersion entity, MetadataSchemaDraftDTO dto) { assertThat(dto.getUuid(), is(equalTo(entity.getUuid()))); assertThat(dto.getName(), is(equalTo(entity.getName()))); assertThat(dto.getDefinition(), is(equalTo(entity.getDefinition()))); } - public static void compare(MetadataSchemaDraft entity, MetadataSchemaDraftDTO dto) { + public static void compare(MetadataSchema entity, MetadataSchemaDTO dto) { assertThat(dto.getUuid(), is(equalTo(entity.getUuid()))); - assertThat(dto.getName(), is(equalTo(entity.getName()))); - assertThat(dto.getDefinition(), is(equalTo(entity.getDefinition()))); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Content_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Content_GET.java index 04fcb972f..3bbba00e2 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Content_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Content_GET.java @@ -23,21 +23,22 @@ package nl.dtls.fairdatapoint.acceptance.schema; import nl.dtls.fairdatapoint.WebIntegrationTest; -import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.schema.data.MetadataSchemaFixtures; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaVersionRepository; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaVersion; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.RequestEntity; import org.springframework.http.ResponseEntity; import java.net.URI; +import java.util.UUID; import static java.lang.String.format; -import static nl.dtls.fairdatapoint.acceptance.common.NotFoundTest.createUserNotFoundTestGet; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; @@ -45,13 +46,31 @@ @DisplayName("GET /metadata-schemas/:schemaUuid") public class Content_GET extends WebIntegrationTest { - private URI url(String uuid) { + @Autowired + private MetadataSchemaVersionRepository metadataSchemaVersionRepository; + + private URI url(UUID uuid) { return URI.create(format("/metadata-schemas/%s", uuid)); } - @Autowired - private MetadataSchemaFixtures metadataSchemaFixtures; + @Test + @DisplayName("HTTP 200") + public void res200() { + // GIVEN: + MetadataSchemaVersion catalog = metadataSchemaVersionRepository.getLatestBySchemaUuid(KnownUUIDs.SCHEMA_CATALOG_UUID).get(); + RequestEntity request = RequestEntity + .get(url(catalog.getSchema().getUuid())) + .header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN) + .header(HttpHeaders.ACCEPT, "text/turtle") + .build(); + ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { + }; - // TODO + // WHEN: + ResponseEntity result = client.exchange(request, responseType); + + // THEN: + assertThat(result.getStatusCode(), is(equalTo(HttpStatus.OK))); + } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Detail_DELETE.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Detail_DELETE.java index 3d25302c7..e5af44a74 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Detail_DELETE.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Detail_DELETE.java @@ -24,9 +24,9 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.error.ErrorDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.schema.data.MetadataSchemaFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaRepository; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaRepository; import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -37,6 +37,7 @@ import org.springframework.http.ResponseEntity; import java.net.URI; +import java.util.UUID; import static java.lang.String.format; import static nl.dtls.fairdatapoint.acceptance.common.ForbiddenTest.createUserForbiddenTestDelete; @@ -48,13 +49,10 @@ @DisplayName("DELETE /metadata-schemas/:schemaUuid") public class Detail_DELETE extends WebIntegrationTest { - private URI url(String uuid) { + private URI url(UUID uuid) { return URI.create(format("/metadata-schemas/%s", uuid)); } - @Autowired - private MetadataSchemaFixtures metadataSchemaFixtures; - @Autowired private MetadataSchemaRepository metadataSchemaRepository; @@ -62,7 +60,7 @@ private URI url(String uuid) { @DisplayName("HTTP 204") public void res204() { // GIVEN: - MetadataSchema metadataSchema = metadataSchemaFixtures.customSchema(); + MetadataSchema metadataSchema = metadataSchemaRepository.findByUuid(Common.SCHEMA_MULTI_UUID).get(); metadataSchemaRepository.save(metadataSchema); RequestEntity request = RequestEntity .delete(url(metadataSchema.getUuid())) @@ -76,13 +74,14 @@ public void res204() { // THEN: assertThat(result.getStatusCode(), is(equalTo(HttpStatus.NO_CONTENT))); + assertThat(metadataSchemaRepository.findByUuid(Common.SCHEMA_MULTI_UUID).isEmpty(), is(true)); } @Test @DisplayName("HTTP 400") public void res400_used() { // GIVEN: - MetadataSchema metadataSchema = metadataSchemaFixtures.datasetSchema(); + MetadataSchema metadataSchema = metadataSchemaRepository.findByUuid(KnownUUIDs.SCHEMA_CATALOG_UUID).get(); RequestEntity request = RequestEntity .delete(url(metadataSchema.getUuid())) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) @@ -101,7 +100,7 @@ public void res400_used() { @DisplayName("HTTP 400: Delete INTERNAL schema") public void res400_internal() { // GIVEN: - MetadataSchema metadataSchema = metadataSchemaFixtures.fdpSchema(); + MetadataSchema metadataSchema = metadataSchemaRepository.findByUuid(Common.SCHEMA_INTERNAL_UUID).get(); RequestEntity request = RequestEntity .delete(url(metadataSchema.getUuid())) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) @@ -119,21 +118,20 @@ public void res400_internal() { @Test @DisplayName("HTTP 403: User is not authenticated") public void res403_notAuthenticated() { - MetadataSchema metadataSchema = metadataSchemaFixtures.datasetSchema(); - createUserForbiddenTestDelete(client, url(metadataSchema.getUuid())); + createUserForbiddenTestDelete(client, url(UUID.randomUUID())); } @Test @DisplayName("HTTP 403: User is not an admin") public void res403_notAdmin() { - MetadataSchema metadataSchema = metadataSchemaFixtures.datasetSchema(); - createUserForbiddenTestDelete(client, url(metadataSchema.getUuid())); + MetadataSchema metadataSchema = null; + createUserForbiddenTestDelete(client, url(UUID.randomUUID())); } @Test @DisplayName("HTTP 404") public void res404() { - createAdminNotFoundTestDelete(client, url("nonExisting")); + createAdminNotFoundTestDelete(client, url(KnownUUIDs.NULL_UUID)); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Detail_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Detail_GET.java index d6ec40da7..6720e545b 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Detail_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Detail_GET.java @@ -24,8 +24,9 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.schema.data.MetadataSchemaFixtures; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaRepository; import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -35,6 +36,7 @@ import org.springframework.http.ResponseEntity; import java.net.URI; +import java.util.UUID; import static java.lang.String.format; import static nl.dtls.fairdatapoint.acceptance.common.NotFoundTest.createUserNotFoundTestGet; @@ -45,20 +47,20 @@ @DisplayName("GET /metadata-schemas/:schemaUuid") public class Detail_GET extends WebIntegrationTest { - private URI url(String uuid) { + private URI url(UUID uuid) { return URI.create(format("/metadata-schemas/%s", uuid)); } @Autowired - private MetadataSchemaFixtures metadataSchemaFixtures; + private MetadataSchemaRepository metadataSchemaRepository; @Test @DisplayName("HTTP 200") public void res200() { // GIVEN: - MetadataSchema metadataSchema = metadataSchemaFixtures.fdpSchema(); + MetadataSchema metadataSchema = metadataSchemaRepository.findById(KnownUUIDs.SCHEMA_FDP_UUID).get(); RequestEntity request = RequestEntity - .get(url(metadataSchema.getUuid())) + .get(url(KnownUUIDs.SCHEMA_FDP_UUID)) .build(); ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { }; @@ -74,7 +76,7 @@ public void res200() { @Test @DisplayName("HTTP 404") public void res404() { - createUserNotFoundTestGet(client, url("nonExisting")); + createUserNotFoundTestGet(client, url(KnownUUIDs.NULL_UUID)); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Draft_DELETE.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Draft_DELETE.java index d270faba5..fb7c49690 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Draft_DELETE.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Draft_DELETE.java @@ -23,20 +23,24 @@ package nl.dtls.fairdatapoint.acceptance.schema; import nl.dtls.fairdatapoint.WebIntegrationTest; -import nl.dtls.fairdatapoint.database.mongo.migration.development.schema.data.MetadataSchemaFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaDraftRepository; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaDraft; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaVersionRepository; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaVersion; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.*; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpStatus; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; import java.net.URI; import java.util.UUID; import static java.lang.String.format; -import static nl.dtls.fairdatapoint.acceptance.common.ForbiddenTest.*; +import static nl.dtls.fairdatapoint.acceptance.common.ForbiddenTest.createNoUserForbiddenTestDelete; +import static nl.dtls.fairdatapoint.acceptance.common.ForbiddenTest.createUserForbiddenTestDelete; import static nl.dtls.fairdatapoint.acceptance.common.NotFoundTest.createAdminNotFoundTestDelete; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @@ -45,27 +49,22 @@ @DisplayName("DELETE /metadata-schemas/:schemaUuid/draft") public class Draft_DELETE extends WebIntegrationTest { - private URI url(String uuid) { + private URI url(UUID uuid) { return URI.create(format("/metadata-schemas/%s/draft", uuid)); } @Autowired - private MetadataSchemaFixtures metadataSchemaFixtures; - - @Autowired - private MetadataSchemaDraftRepository metadataSchemaDraftRepository; + private MetadataSchemaVersionRepository metadataSchemaVersionRepository; @Test @DisplayName("HTTP 200") public void res200() { // GIVEN: Prepare data - MetadataSchemaDraft draft = metadataSchemaFixtures.customSchemaDraft1(); - metadataSchemaDraftRepository.deleteAll(); - metadataSchemaDraftRepository.save(draft); + MetadataSchemaVersion draft = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_DRAFT_DRAFT_UUID).get(); // AND: Prepare request RequestEntity request = RequestEntity - .delete(url(draft.getUuid())) + .delete(url(draft.getSchema().getUuid())) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .build(); ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { @@ -76,25 +75,27 @@ public void res200() { // THEN: assertThat(result.getStatusCode(), is(equalTo(HttpStatus.NO_CONTENT))); - assertThat(metadataSchemaDraftRepository.findAll().isEmpty(), is(true)); + assertThat(metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_DRAFT_DRAFT_UUID).isPresent(), is(false)); + assertThat(metadataSchemaVersionRepository.getLatestBySchemaUuid(Common.SCHEMA_MULTI_DRAFT_UUID).isPresent(), is(true)); + assertThat(metadataSchemaVersionRepository.getDraftBySchemaUuid(Common.SCHEMA_MULTI_DRAFT_UUID).isPresent(), is(false)); } @Test @DisplayName("HTTP 404") public void res404() { - createAdminNotFoundTestDelete(client, url("nonExisting")); + createAdminNotFoundTestDelete(client, url(KnownUUIDs.NULL_UUID)); } @Test @DisplayName("HTTP 403: User is not authenticated") public void res403_notAuthenticated() { - createNoUserForbiddenTestDelete(client, url(UUID.randomUUID().toString())); + createNoUserForbiddenTestDelete(client, url(UUID.randomUUID())); } @Test @DisplayName("HTTP 403: User is not an admin") public void res403_notAdmin() { - createUserForbiddenTestDelete(client, url(UUID.randomUUID().toString())); + createUserForbiddenTestDelete(client, url(UUID.randomUUID())); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Draft_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Draft_GET.java index 1cc759c47..01480e34e 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Draft_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Draft_GET.java @@ -24,9 +24,9 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaDraftDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.schema.data.MetadataSchemaFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaDraftRepository; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaDraft; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaVersionRepository; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaVersion; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -37,7 +37,8 @@ import java.util.UUID; import static java.lang.String.format; -import static nl.dtls.fairdatapoint.acceptance.common.ForbiddenTest.*; +import static nl.dtls.fairdatapoint.acceptance.common.ForbiddenTest.createNoUserForbiddenTestGet; +import static nl.dtls.fairdatapoint.acceptance.common.ForbiddenTest.createUserForbiddenTestGet; import static nl.dtls.fairdatapoint.acceptance.common.NotFoundTest.createAdminNotFoundTestGet; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @@ -46,27 +47,22 @@ @DisplayName("GET /metadata-schemas/:schemaUuid/draft") public class Draft_GET extends WebIntegrationTest { - private URI url(String uuid) { + private URI url(UUID uuid) { return URI.create(format("/metadata-schemas/%s/draft", uuid)); } @Autowired - private MetadataSchemaFixtures metadataSchemaFixtures; - - @Autowired - private MetadataSchemaDraftRepository metadataSchemaDraftRepository; + private MetadataSchemaVersionRepository metadataSchemaVersionRepository; @Test @DisplayName("HTTP 200") public void res200() { // GIVEN: Prepare data - MetadataSchemaDraft draft = metadataSchemaFixtures.customSchemaDraft1(); - metadataSchemaDraftRepository.deleteAll(); - metadataSchemaDraftRepository.save(draft); + MetadataSchemaVersion draft = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_DRAFT_DRAFT_UUID).get(); // AND: Prepare request RequestEntity request = RequestEntity - .get(url(draft.getUuid())) + .get(url(draft.getSchema().getUuid())) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .accept(MediaType.APPLICATION_JSON) .build(); @@ -84,18 +80,18 @@ public void res200() { @Test @DisplayName("HTTP 404") public void res404() { - createAdminNotFoundTestGet(client, url("nonExisting")); + createAdminNotFoundTestGet(client, url(KnownUUIDs.NULL_UUID)); } @Test @DisplayName("HTTP 403: User is not authenticated") public void res403_notAuthenticated() { - createNoUserForbiddenTestGet(client, url(UUID.randomUUID().toString())); + createNoUserForbiddenTestGet(client, url(UUID.randomUUID())); } @Test @DisplayName("HTTP 403: User is not an admin") public void res403_notAdmin() { - createUserForbiddenTestGet(client, url(UUID.randomUUID().toString())); + createUserForbiddenTestGet(client, url(UUID.randomUUID())); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Draft_PUT.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Draft_PUT.java index 499820239..8c0fab6ec 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Draft_PUT.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Draft_PUT.java @@ -25,11 +25,11 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaChangeDTO; import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaDraftDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.schema.data.MetadataSchemaFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaDraftRepository; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaRepository; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaRepository; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaVersionRepository; import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaDraft; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaVersion; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -53,7 +53,7 @@ @DisplayName("PUT /metadata-schemas/:schemaUuid/draft") public class Draft_PUT extends WebIntegrationTest { - private URI url(String uuid) { + private URI url(UUID uuid) { return URI.create(format("/metadata-schemas/%s/draft", uuid)); } @@ -68,10 +68,7 @@ private MetadataSchemaChangeDTO reqDto() { } @Autowired - private MetadataSchemaFixtures metadataSchemaFixtures; - - @Autowired - private MetadataSchemaDraftRepository metadataSchemaDraftRepository; + private MetadataSchemaVersionRepository metadataSchemaVersionRepository; @Autowired private MetadataSchemaRepository metadataSchemaRepository; @@ -80,14 +77,12 @@ private MetadataSchemaChangeDTO reqDto() { @DisplayName("HTTP 200") public void res200() { // GIVEN: Prepare data - metadataSchemaDraftRepository.deleteAll(); - MetadataSchemaDraft draft = metadataSchemaFixtures.customSchemaDraft1(); - metadataSchemaDraftRepository.save(draft); + MetadataSchemaVersion draft = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_DRAFT_DRAFT_UUID).get(); MetadataSchemaChangeDTO reqDto = reqDto(); // AND: Prepare request RequestEntity request = RequestEntity - .put(url(draft.getUuid())) + .put(url(draft.getSchema().getUuid())) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .accept(MediaType.APPLICATION_JSON) .body(reqDto); @@ -111,18 +106,14 @@ public void res200() { @DisplayName("HTTP 200: with extends") public void res200_extends() { // GIVEN: Prepare data - metadataSchemaDraftRepository.deleteAll(); - metadataSchemaRepository.deleteAll(); - MetadataSchema parentSchema = metadataSchemaFixtures.resourceSchema(); - MetadataSchemaDraft draft = metadataSchemaFixtures.customSchemaDraft1(); - metadataSchemaDraftRepository.save(draft); - metadataSchemaRepository.save(parentSchema); + MetadataSchema parentSchema = metadataSchemaRepository.findByUuid(KnownUUIDs.SCHEMA_RESOURCE_UUID).get(); + MetadataSchemaVersion draft = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_DRAFT_DRAFT_UUID).get(); MetadataSchemaChangeDTO reqDto = reqDto(); reqDto.setExtendsSchemaUuids(List.of(parentSchema.getUuid())); // AND: Prepare request RequestEntity request = RequestEntity - .put(url(draft.getUuid())) + .put(url(draft.getSchema().getUuid())) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .accept(MediaType.APPLICATION_JSON) .body(reqDto); @@ -142,17 +133,14 @@ public void res200_extends() { @DisplayName("HTTP 400: non-existing schema") public void res400_nonExistingSchema() { // GIVEN: Prepare data - metadataSchemaDraftRepository.deleteAll(); - metadataSchemaRepository.deleteAll(); - MetadataSchema parentSchema = metadataSchemaFixtures.resourceSchema(); - MetadataSchemaDraft draft = metadataSchemaFixtures.customSchemaDraft1(); - metadataSchemaDraftRepository.save(draft); + MetadataSchema parentSchema = metadataSchemaRepository.findByUuid(KnownUUIDs.SCHEMA_RESOURCE_UUID).get(); + MetadataSchemaVersion draft = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_DRAFT_DRAFT_UUID).get(); MetadataSchemaChangeDTO reqDto = reqDto(); - reqDto.setExtendsSchemaUuids(List.of(parentSchema.getUuid())); + reqDto.setExtendsSchemaUuids(List.of(parentSchema.getUuid(), KnownUUIDs.NULL_UUID)); // AND: Prepare request RequestEntity request = RequestEntity - .put(url(draft.getUuid())) + .put(url(draft.getSchema().getUuid())) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .accept(MediaType.APPLICATION_JSON) .body(reqDto); @@ -170,16 +158,13 @@ public void res400_nonExistingSchema() { @DisplayName("HTTP 400: simple schema loop") public void res400_schemaLoopSimple() { // GIVEN: Prepare data - metadataSchemaDraftRepository.deleteAll(); - metadataSchemaRepository.deleteAll(); - MetadataSchemaDraft draft = metadataSchemaFixtures.customSchemaDraft1(); - metadataSchemaDraftRepository.save(draft); + MetadataSchemaVersion draft = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_DRAFT_DRAFT_UUID).get(); MetadataSchemaChangeDTO reqDto = reqDto(); - reqDto.setExtendsSchemaUuids(List.of(draft.getUuid())); + reqDto.setExtendsSchemaUuids(List.of(draft.getSchema().getUuid())); // AND: Prepare request RequestEntity request = RequestEntity - .put(url(draft.getUuid())) + .put(url(draft.getSchema().getUuid())) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .accept(MediaType.APPLICATION_JSON) .body(reqDto); @@ -197,22 +182,14 @@ public void res400_schemaLoopSimple() { @DisplayName("HTTP 400: complex schema loop") public void res400_schemaLoopComplex() { // GIVEN: Prepare data - MetadataSchema resourceSchema = metadataSchemaFixtures.resourceSchema(); - MetadataSchema catalogSchema = metadataSchemaFixtures.catalogSchema(); - MetadataSchemaDraft draft = metadataSchemaFixtures.customSchemaDraft1(); - catalogSchema.setExtendSchemas(List.of(resourceSchema.getUuid())); - resourceSchema.setExtendSchemas(List.of(draft.getUuid())); - metadataSchemaDraftRepository.deleteAll(); - metadataSchemaDraftRepository.save(draft); - metadataSchemaRepository.deleteAll(); - metadataSchemaRepository.save(resourceSchema); - metadataSchemaRepository.save(catalogSchema); + MetadataSchema extendedSchema = metadataSchemaRepository.findByUuid(Common.SCHEMA_MULTI_EXTS_UUID).get(); + MetadataSchemaVersion draft = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_DRAFT_DRAFT_UUID).get();; MetadataSchemaChangeDTO reqDto = reqDto(); - reqDto.setExtendsSchemaUuids(List.of(catalogSchema.getUuid())); + reqDto.setExtendsSchemaUuids(List.of(extendedSchema.getUuid())); // AND: Prepare request RequestEntity request = RequestEntity - .put(url(draft.getUuid())) + .put(url(draft.getSchema().getUuid())) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .accept(MediaType.APPLICATION_JSON) .body(reqDto); @@ -229,18 +206,18 @@ public void res400_schemaLoopComplex() { @Test @DisplayName("HTTP 404") public void res404() { - createAdminNotFoundTestPut(client, url("nonExisting"), reqDto()); + createAdminNotFoundTestPut(client, url(KnownUUIDs.NULL_UUID), reqDto()); } @Test @DisplayName("HTTP 403: User is not authenticated") public void res403_notAuthenticated() { - createNoUserForbiddenTestPut(client, url(UUID.randomUUID().toString()), reqDto()); + createNoUserForbiddenTestPut(client, url(UUID.randomUUID()), reqDto()); } @Test @DisplayName("HTTP 403: User is not an admin") public void res403_notAdmin() { - createUserForbiddenTestPut(client, url(UUID.randomUUID().toString()), reqDto()); + createUserForbiddenTestPut(client, url(UUID.randomUUID()), reqDto()); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Import_POST.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Import_POST.java index 23af7b311..ebd51901f 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Import_POST.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Import_POST.java @@ -23,10 +23,10 @@ package nl.dtls.fairdatapoint.acceptance.schema; import nl.dtls.fairdatapoint.WebIntegrationTest; -import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaRemoteDTO; import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaVersionDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.schema.data.MetadataSchemaFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaRepository; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaRepository; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaVersionRepository; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaType; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -49,7 +49,7 @@ public class Import_POST extends WebIntegrationTest { private MetadataSchemaRepository metadataSchemaRepository; @Autowired - private MetadataSchemaFixtures metadataSchemaFixtures; + private MetadataSchemaVersionRepository metadataSchemaVersionRepository; private final ParameterizedTypeReference> responseType = new ParameterizedTypeReference<>() { @@ -60,38 +60,38 @@ private URI url() { } private MetadataSchemaVersionDTO schemaPublicDTO1() { - String schemaUuid = UUID.randomUUID().toString(); - String versionUuid = UUID.randomUUID().toString(); return MetadataSchemaVersionDTO.builder() - .uuid(schemaUuid) - .versionUuid(versionUuid) + .uuid(UUID.randomUUID()) + .versionUuid(UUID.randomUUID()) .previousVersionUuid(null) + .type(MetadataSchemaType.CUSTOM) .importedFrom("http://example.com/remote-fdp") .origin("http://example.com/remote-fdp") .version("1.0.0") - .name(metadataSchemaFixtures.customSchema().getName()) - .description(metadataSchemaFixtures.customSchema().getDescription()) - .definition(metadataSchemaFixtures.customSchema().getDefinition()) - .abstractSchema(metadataSchemaFixtures.customSchema().isAbstractSchema()) - .extendsSchemaUuids(Collections.emptyList()) + .name("Custom external schema 1") + .description("Custom external schema 2 description") + .definition("") + .abstractSchema(true) + .extendsSchemaUuids(List.of()) + .targetClasses(List.of()) .build(); } private MetadataSchemaVersionDTO schemaPublicDTO2() { - String schemaUuid = UUID.randomUUID().toString(); - String versionUuid = UUID.randomUUID().toString(); return MetadataSchemaVersionDTO.builder() - .uuid(schemaUuid) - .versionUuid(versionUuid) + .uuid(UUID.randomUUID()) + .versionUuid(UUID.randomUUID()) .previousVersionUuid(null) + .type(MetadataSchemaType.CUSTOM) .importedFrom("http://example.com/remote-fdp") .origin("http://example.com/other-remote-fdp") .version("1.2.3") - .name(metadataSchemaFixtures.customSchema().getName()) - .description(metadataSchemaFixtures.customSchema().getDescription()) - .definition(metadataSchemaFixtures.customSchema().getDefinition()) - .abstractSchema(metadataSchemaFixtures.customSchema().isAbstractSchema()) - .extendsSchemaUuids(Collections.emptyList()) + .name("Custom external schema 2") + .description("Custom external schema 2 description") + .definition("") + .abstractSchema(false) + .extendsSchemaUuids(List.of()) + .targetClasses(List.of()) .build(); } @@ -99,8 +99,9 @@ private MetadataSchemaVersionDTO schemaPublicDTO2() { @DisplayName("HTTP 200: empty import") public void res200_emptyImport() { // GIVEN: prepare data - metadataSchemaRepository.deleteAll(); List reqDTOs = Collections.emptyList(); + long schemas = metadataSchemaRepository.count(); + long versions = metadataSchemaVersionRepository.count(); // AND: prepare request RequestEntity request = RequestEntity @@ -116,16 +117,18 @@ public void res200_emptyImport() { assertThat("Correct response code is received", result.getStatusCode(), is(equalTo(HttpStatus.OK))); assertThat("Response body is not null", result.getBody(), is(notNullValue())); assertThat("Result is an empty list", result.getBody().size(), is(equalTo(0))); - assertThat("Metadata schema repository is empty", metadataSchemaRepository.count(), is(equalTo(0L))); + assertThat("Metadata schemas count is unchanged", metadataSchemaRepository.count(), is(equalTo(schemas))); + assertThat("Metadata schema versions count is unchanged", metadataSchemaVersionRepository.count(), is(equalTo(versions))); } @Test @DisplayName("HTTP 200: single import") public void res200_singleImport() { // GIVEN: prepare data - metadataSchemaRepository.deleteAll(); MetadataSchemaVersionDTO schema = schemaPublicDTO1(); List reqDTOs = Collections.singletonList(schema); + long schemas = metadataSchemaRepository.count(); + long versions = metadataSchemaVersionRepository.count(); // AND: prepare request RequestEntity request = RequestEntity @@ -141,14 +144,14 @@ public void res200_singleImport() { assertThat("Correct response code is received", result.getStatusCode(), is(equalTo(HttpStatus.OK))); assertThat("Response body is not null", result.getBody(), is(notNullValue())); assertThat("Result contains one schema", result.getBody().size(), is(equalTo(1))); - assertThat("Schema is in the metadata schema repository", metadataSchemaRepository.count(), is(equalTo(1L))); + assertThat("Schema is in the metadata schema repository", metadataSchemaRepository.count(), is(equalTo(schemas + 1))); + assertThat("Schema version is in the metadata schema repository", metadataSchemaVersionRepository.count(), is(equalTo(versions + 1))); } @Test @DisplayName("HTTP 200: multiple import") public void res200_multipleImport() { // GIVEN: prepare data - metadataSchemaRepository.deleteAll(); MetadataSchemaVersionDTO schema1 = schemaPublicDTO1(); MetadataSchemaVersionDTO schema2 = schemaPublicDTO2(); List reqDTOs = Arrays.asList(schema1, schema2); @@ -167,14 +170,14 @@ public void res200_multipleImport() { assertThat("Correct response code is received", result.getStatusCode(), is(equalTo(HttpStatus.OK))); assertThat("Response body is not null", result.getBody(), is(notNullValue())); assertThat("Result contains one schema", result.getBody().size(), is(equalTo(2))); - assertThat("Schema is in the metadata schema repository", metadataSchemaRepository.count(), is(equalTo(2L))); + assertThat("Schemas are in the repository", metadataSchemaRepository.count(), is(equalTo(16L))); + assertThat("Schema versions are in the repository", metadataSchemaVersionRepository.count(), is(equalTo(22L))); } @Test @DisplayName("HTTP 200: import versions of the same schema") public void res200_multipleVersions() { // GIVEN: prepare data - metadataSchemaRepository.deleteAll(); MetadataSchemaVersionDTO schema1 = schemaPublicDTO1(); MetadataSchemaVersionDTO schema2 = schemaPublicDTO2(); schema2.setPreviousVersionUuid(schema1.getVersionUuid()); @@ -194,15 +197,15 @@ public void res200_multipleVersions() { // THEN assertThat("Correct response code is received", result.getStatusCode(), is(equalTo(HttpStatus.OK))); assertThat("Response body is not null", result.getBody(), is(notNullValue())); - assertThat("Result contains one schema", result.getBody().size(), is(equalTo(2))); - assertThat("Schema is in the metadata schema repository", metadataSchemaRepository.count(), is(equalTo(2L))); + assertThat("Result contains two schemas", result.getBody().size(), is(equalTo(2))); + assertThat("Schema is in the repository", metadataSchemaRepository.count(), is(equalTo(15L))); + assertThat("Schema versions are in the repository", metadataSchemaVersionRepository.count(), is(equalTo(22L))); } @Test @DisplayName("HTTP 200: import with extends") public void res200_withExtends() { // GIVEN: prepare data - metadataSchemaRepository.deleteAll(); MetadataSchemaVersionDTO schema1 = schemaPublicDTO1(); MetadataSchemaVersionDTO schema2 = schemaPublicDTO2(); schema2.setExtendsSchemaUuids(Collections.singletonList(schema1.getUuid())); @@ -222,16 +225,17 @@ public void res200_withExtends() { assertThat("Correct response code is received", result.getStatusCode(), is(equalTo(HttpStatus.OK))); assertThat("Response body is not null", result.getBody(), is(notNullValue())); assertThat("Result contains one schema", result.getBody().size(), is(equalTo(2))); - assertThat("Schema is in the metadata schema repository", metadataSchemaRepository.count(), is(equalTo(2L))); + assertThat("Schemas are in the repository", metadataSchemaRepository.count(), is(equalTo(16L))); + assertThat("Schema versions are in the repository", metadataSchemaVersionRepository.count(), is(equalTo(22L))); + assertThat("Schema 2 extends schema 1", result.getBody().get(1).getExtendsSchemaUuids(), is(equalTo(Collections.singletonList(schema1.getUuid())))); } @Test @DisplayName("HTTP 400: missing extends") public void res400_missingExtends() { // GIVEN: prepare data - metadataSchemaRepository.deleteAll(); MetadataSchemaVersionDTO schema1 = schemaPublicDTO1(); - schema1.setExtendsSchemaUuids(Collections.singletonList(UUID.randomUUID().toString())); + schema1.setExtendsSchemaUuids(Collections.singletonList(UUID.randomUUID())); List reqDTOs = Collections.singletonList(schema1); // AND: prepare request @@ -246,14 +250,13 @@ public void res400_missingExtends() { // THEN assertThat("Correct response code is received", result.getStatusCode(), is(equalTo(HttpStatus.BAD_REQUEST))); - assertThat("Nothings changes in metadata schema repository", metadataSchemaRepository.count(), is(equalTo(0L))); + assertThat("Nothings changes in metadata schema repository", metadataSchemaRepository.count(), is(equalTo(14L))); } @Test @DisplayName("HTTP 403: no token") public void res403_noToken() { // GIVEN: prepare data - metadataSchemaRepository.deleteAll(); MetadataSchemaVersionDTO schema = schemaPublicDTO1(); List reqDTOs = Collections.singletonList(schema); @@ -268,14 +271,13 @@ public void res403_noToken() { // THEN: assertThat("Correct response code is received", result.getStatusCode(), is(equalTo(HttpStatus.FORBIDDEN))); - assertThat("Metadata schema repository stays empty", metadataSchemaRepository.count(), is(equalTo(0L))); + assertThat("Metadata schema repository stays empty", metadataSchemaRepository.count(), is(equalTo(14L))); } @Test @DisplayName("HTTP 403: non-admin token") public void res403_nonAdminToken() { // GIVEN: prepare data - metadataSchemaRepository.deleteAll(); MetadataSchemaVersionDTO schema1 = schemaPublicDTO1(); MetadataSchemaVersionDTO schema2 = schemaPublicDTO2(); List reqDTOs = Arrays.asList(schema1, schema2); @@ -285,6 +287,7 @@ public void res403_nonAdminToken() { .post(url()) .accept(MediaType.APPLICATION_JSON) .header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN) + .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .body(reqDTOs); // WHEN @@ -292,6 +295,6 @@ public void res403_nonAdminToken() { // THEN: assertThat("Correct response code is received", result.getStatusCode(), is(equalTo(HttpStatus.FORBIDDEN))); - assertThat("Metadata schema repository stays empty", metadataSchemaRepository.count(), is(equalTo(0L))); + assertThat("Metadata schema repository stays empty", metadataSchemaRepository.count(), is(equalTo(14L))); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/List_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/List_GET.java index d51fd0d2d..23a821f81 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/List_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/List_GET.java @@ -24,10 +24,9 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.schema.data.MetadataSchemaFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaDraftRepository; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaRepository; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaRepository; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaVersionRepository; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaVersion; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -64,26 +63,13 @@ private URI url(boolean includeDrafts, boolean includeAbstract) { private MetadataSchemaRepository metadataSchemaRepository; @Autowired - private MetadataSchemaDraftRepository metadataSchemaDraftRepository; - - @Autowired - private MetadataSchemaFixtures metadataSchemaFixtures; + private MetadataSchemaVersionRepository metadataSchemaVersionRepository; @Test @DisplayName("HTTP 200: regular user") public void res200_regularUser() { - // GIVEN: prepare data - metadataSchemaDraftRepository.deleteAll(); - metadataSchemaRepository.deleteAll(); - metadataSchemaRepository.insert(metadataSchemaFixtures.resourceSchema()); - metadataSchemaRepository.insert(metadataSchemaFixtures.fdpSchema()); - metadataSchemaRepository.insert(metadataSchemaFixtures.dataServiceSchema()); - metadataSchemaRepository.insert(metadataSchemaFixtures.metadataServiceSchema()); - metadataSchemaRepository.insert(metadataSchemaFixtures.catalogSchema()); - metadataSchemaRepository.insert(metadataSchemaFixtures.datasetSchema()); - metadataSchemaRepository.insert(metadataSchemaFixtures.distributionSchema()); - - // AND: prepare request + // GIVEN: + List all = metadataSchemaVersionRepository.getAllLatest(); RequestEntity request = RequestEntity .get(url(false, true)) .build(); @@ -96,29 +82,22 @@ public void res200_regularUser() { // THEN: assertThat(result.getStatusCode(), is(equalTo(HttpStatus.OK))); List body = result.getBody(); - assertThat(body.size(), is(equalTo(7))); - Common.compare(metadataSchemaFixtures.resourceSchema(), body.get(0)); - Common.compare(metadataSchemaFixtures.fdpSchema(), body.get(1)); - Common.compare(metadataSchemaFixtures.dataServiceSchema(), body.get(2)); - Common.compare(metadataSchemaFixtures.metadataServiceSchema(), body.get(3)); - Common.compare(metadataSchemaFixtures.catalogSchema(), body.get(4)); - Common.compare(metadataSchemaFixtures.datasetSchema(), body.get(5)); - Common.compare(metadataSchemaFixtures.distributionSchema(), body.get(6)); + assertThat(body.size(), is(equalTo(12))); + + Common.compare(all.get(0), body.get(0)); + Common.compare(all.get(1), body.get(1)); + Common.compare(all.get(2), body.get(2)); + Common.compare(all.get(3), body.get(3)); + Common.compare(all.get(4), body.get(4)); + Common.compare(all.get(5), body.get(5)); + Common.compare(all.get(6), body.get(6)); } @Test @DisplayName("HTTP 200: regular user, no abstract") public void res200_regularUserNoAbstract() { // GIVEN: prepare data - metadataSchemaDraftRepository.deleteAll(); - metadataSchemaRepository.deleteAll(); - metadataSchemaRepository.insert(metadataSchemaFixtures.resourceSchema()); - metadataSchemaRepository.insert(metadataSchemaFixtures.fdpSchema()); - metadataSchemaRepository.insert(metadataSchemaFixtures.dataServiceSchema()); - metadataSchemaRepository.insert(metadataSchemaFixtures.metadataServiceSchema()); - metadataSchemaRepository.insert(metadataSchemaFixtures.catalogSchema()); - metadataSchemaRepository.insert(metadataSchemaFixtures.datasetSchema()); - metadataSchemaRepository.insert(metadataSchemaFixtures.distributionSchema()); + List all = metadataSchemaVersionRepository.getAllLatest().stream().filter(v -> !v.isAbstractSchema()).toList(); // AND: prepare request RequestEntity request = RequestEntity @@ -133,29 +112,20 @@ public void res200_regularUserNoAbstract() { // THEN: assertThat(result.getStatusCode(), is(equalTo(HttpStatus.OK))); List body = result.getBody(); - assertThat(body.size(), is(equalTo(6))); - Common.compare(metadataSchemaFixtures.fdpSchema(), body.get(0)); - Common.compare(metadataSchemaFixtures.dataServiceSchema(), body.get(1)); - Common.compare(metadataSchemaFixtures.metadataServiceSchema(), body.get(2)); - Common.compare(metadataSchemaFixtures.catalogSchema(), body.get(3)); - Common.compare(metadataSchemaFixtures.datasetSchema(), body.get(4)); - Common.compare(metadataSchemaFixtures.distributionSchema(), body.get(5)); + assertThat(body.size(), is(equalTo(11))); + + Common.compare(all.get(0), body.get(0)); + Common.compare(all.get(1), body.get(1)); + Common.compare(all.get(2), body.get(2)); + Common.compare(all.get(3), body.get(3)); + Common.compare(all.get(4), body.get(4)); + Common.compare(all.get(5), body.get(5)); } @Test @DisplayName("HTTP 200: admin with drafts") public void res200_adminDrafts() { - // GIVEN: prepare data - metadataSchemaDraftRepository.deleteAll(); - metadataSchemaRepository.deleteAll(); - metadataSchemaRepository.insert(metadataSchemaFixtures.resourceSchema()); - metadataSchemaRepository.insert(metadataSchemaFixtures.fdpSchema()); - metadataSchemaRepository.insert(metadataSchemaFixtures.dataServiceSchema()); - metadataSchemaRepository.insert(metadataSchemaFixtures.metadataServiceSchema()); - metadataSchemaRepository.insert(metadataSchemaFixtures.catalogSchema()); - metadataSchemaRepository.insert(metadataSchemaFixtures.datasetSchema()); - metadataSchemaRepository.insert(metadataSchemaFixtures.distributionSchema()); - metadataSchemaDraftRepository.insert(metadataSchemaFixtures.customSchemaDraft1()); + List all = metadataSchemaVersionRepository.getAllLatest(); // AND: prepare request RequestEntity request = RequestEntity @@ -171,26 +141,21 @@ public void res200_adminDrafts() { // THEN: assertThat(result.getStatusCode(), is(equalTo(HttpStatus.OK))); List body = result.getBody(); - assertThat(body.size(), is(equalTo(8))); - Common.compare(metadataSchemaFixtures.resourceSchema(), body.get(0)); - Common.compare(metadataSchemaFixtures.fdpSchema(), body.get(1)); - Common.compare(metadataSchemaFixtures.dataServiceSchema(), body.get(2)); - Common.compare(metadataSchemaFixtures.metadataServiceSchema(), body.get(3)); - Common.compare(metadataSchemaFixtures.catalogSchema(), body.get(4)); - Common.compare(metadataSchemaFixtures.datasetSchema(), body.get(5)); - Common.compare(metadataSchemaFixtures.distributionSchema(), body.get(6)); - Common.compare(metadataSchemaFixtures.customSchemaDraft1(), body.get(7)); + assertThat(body.size(), is(equalTo(14))); + + Common.compare(all.get(0), body.get(0)); + Common.compare(all.get(1), body.get(1)); + Common.compare(all.get(2), body.get(2)); + Common.compare(all.get(3), body.get(3)); + Common.compare(all.get(4), body.get(4)); + Common.compare(all.get(5), body.get(5)); + Common.compare(all.get(6), body.get(6)); } - @Test @DisplayName("HTTP 403: unauthorized for drafts") public void res403_unauthorized() { - // GIVEN: prepare data - metadataSchemaDraftRepository.deleteAll(); - metadataSchemaRepository.deleteAll(); - - // AND: prepare request + // GIVEN: request RequestEntity request = RequestEntity .get(url(true, true)) .build(); diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/List_POST.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/List_POST.java index be3336f18..dc1c0c10e 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/List_POST.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/List_POST.java @@ -25,16 +25,15 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaChangeDTO; import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaDraftDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.schema.data.MetadataSchemaFixtures; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; import java.net.URI; import java.util.Collections; +import java.util.List; import static nl.dtls.fairdatapoint.acceptance.common.ForbiddenTest.createNoUserForbiddenTestPost; import static nl.dtls.fairdatapoint.acceptance.common.ForbiddenTest.createUserForbiddenTestPost; @@ -45,19 +44,22 @@ @DisplayName("POST /metadata-schemas") public class List_POST extends WebIntegrationTest { - @Autowired - private MetadataSchemaFixtures metadataSchemaFixtures; - private URI url() { return URI.create("/metadata-schemas"); } - private MetadataSchemaChangeDTO reqDto(MetadataSchema metadataSchema) { + private MetadataSchemaChangeDTO reqDto() { return MetadataSchemaChangeDTO.builder() - .name(metadataSchema.getName()) + .name("Example") .description("") .abstractSchema(false) - .definition(metadataSchema.getDefinition()) + .extendsSchemaUuids(List.of(KnownUUIDs.SCHEMA_RESOURCE_UUID)) + .definition(""" + @prefix : . + @prefix sh: . + + :ExampleShape a sh:NodeShape . + """) .extendsSchemaUuids(Collections.emptyList()) .build(); } @@ -66,8 +68,7 @@ private MetadataSchemaChangeDTO reqDto(MetadataSchema metadataSchema) { @DisplayName("HTTP 200") public void res200() { // GIVEN: Prepare data - MetadataSchema metadataSchema = metadataSchemaFixtures.customSchema(); - MetadataSchemaChangeDTO reqDto = reqDto(metadataSchema); + MetadataSchemaChangeDTO reqDto = reqDto(); // AND: Prepare request RequestEntity request = RequestEntity @@ -89,13 +90,13 @@ public void res200() { @Test @DisplayName("HTTP 403: User is not authenticated") public void res403_notAuthenticated() { - createNoUserForbiddenTestPost(client, url(), reqDto(metadataSchemaFixtures.customSchema())); + createNoUserForbiddenTestPost(client, url(), reqDto()); } @Test @DisplayName("HTTP 403: User is not an admin") public void res403_notAdmin() { - createUserForbiddenTestPost(client, url(), reqDto(metadataSchemaFixtures.customSchema())); + createUserForbiddenTestPost(client, url(), reqDto()); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Public_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Public_GET.java index 71f4c3710..7883eac5b 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Public_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Public_GET.java @@ -23,13 +23,10 @@ package nl.dtls.fairdatapoint.acceptance.schema; import nl.dtls.fairdatapoint.WebIntegrationTest; -import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaDTO; -import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaRemoteDTO; import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaVersionDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.schema.data.MetadataSchemaFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaRepository; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; -import nl.dtls.fairdatapoint.entity.schema.SemVer; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaRepository; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaVersionRepository; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaVersion; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -41,8 +38,6 @@ import java.net.URI; import java.util.List; -import java.util.Set; -import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @@ -53,10 +48,10 @@ public class Public_GET extends WebIntegrationTest { @Autowired - private MetadataSchemaRepository metadataSchemaRepository; + private MetadataSchemaVersionRepository metadataSchemaVersionRepository; @Autowired - private MetadataSchemaFixtures metadataSchemaFixtures; + private MetadataSchemaRepository metadataSchemaRepository; private final ParameterizedTypeReference> responseType = new ParameterizedTypeReference<>() { @@ -66,28 +61,15 @@ private URI url() { return URI.create("/metadata-schemas/public"); } - private MetadataSchema makeSchema(Boolean published) { - SemVer version = new SemVer("1.0.0"); - return MetadataSchema.builder() - .uuid(UUID.randomUUID().toString()) - .version(version) - .versionString(version.toString()) - .versionUuid(UUID.randomUUID().toString()) - .name(metadataSchemaFixtures.customSchema().getName()) - .definition(metadataSchemaFixtures.customSchema().getDefinition()) - .published(published) - .previousVersionUuid(null) - .targetClasses(Set.of()) - .build(); - } - @Test @DisplayName("HTTP 200: no published") public void res200_noPublished() { // GIVEN: prepare data - metadataSchemaRepository.deleteAll(); - MetadataSchema metadataSchema = makeSchema(false); - metadataSchemaRepository.insert(metadataSchema); + final MetadataSchemaVersion published1 = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_SIMPLE_V1_UUID).get(); + final MetadataSchemaVersion published2 = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_INTERNAL_V1_UUID).get(); + + metadataSchemaVersionRepository.deleteAll(List.of(published1, published2)); + metadataSchemaRepository.deleteAll(List.of(published1.getSchema(), published2.getSchema())); // AND: prepare request RequestEntity request = RequestEntity @@ -108,11 +90,8 @@ public void res200_noPublished() { @DisplayName("HTTP 200: published") public void res200_published() { // GIVEN: prepare data - metadataSchemaRepository.deleteAll(); - MetadataSchema metadataSchemaNotPublished = makeSchema(false); - MetadataSchema metadataSchemaPublished = makeSchema(true); - metadataSchemaRepository.insert(metadataSchemaNotPublished); - metadataSchemaRepository.insert(metadataSchemaPublished); + final MetadataSchemaVersion published1 = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_SIMPLE_V1_UUID).get(); + final MetadataSchemaVersion published2 = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_INTERNAL_V1_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity @@ -126,8 +105,10 @@ public void res200_published() { // THEN assertThat("Correct response code is received", result.getStatusCode(), is(equalTo(HttpStatus.OK))); assertThat("Response body is not null", result.getBody(), is(notNullValue())); - assertThat("Result is an empty list", result.getBody().size(), is(equalTo(1))); - assertThat("UUID matches the published schema", result.getBody().get(0).getUuid(), is(equalTo(metadataSchemaPublished.getUuid()))); - assertThat("UUID matches the published schema", result.getBody().get(0).getVersionUuid(), is(equalTo(metadataSchemaPublished.getVersionUuid()))); + assertThat("Result is an empty list", result.getBody().size(), is(equalTo(2))); + assertThat("UUID matches the published schema", result.getBody().get(0).getUuid(), is(equalTo(published1.getSchema().getUuid()))); + assertThat("UUID matches the published schema", result.getBody().get(0).getVersionUuid(), is(equalTo(published1.getUuid()))); + assertThat("UUID matches the published schema", result.getBody().get(1).getUuid(), is(equalTo(published2.getSchema().getUuid()))); + assertThat("UUID matches the published schema", result.getBody().get(1).getVersionUuid(), is(equalTo(published2.getUuid()))); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Version_DELETE.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Version_DELETE.java index 3522f3e52..868a5bdb8 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Version_DELETE.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Version_DELETE.java @@ -23,9 +23,10 @@ package nl.dtls.fairdatapoint.acceptance.schema; import nl.dtls.fairdatapoint.WebIntegrationTest; -import nl.dtls.fairdatapoint.database.mongo.migration.development.schema.data.MetadataSchemaFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaRepository; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaRepository; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaVersionRepository; import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaVersion; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -49,27 +50,26 @@ @DisplayName("DELETE /metadata-schemas/:schemaUuid/versions/:version") public class Version_DELETE extends WebIntegrationTest { - private URI url(String uuid, String version) { - return URI.create(format("/metadata-schemas/%s/versions/%s", uuid, version)); + private URI url(UUID uuid, String version) { + return URI.create(format("/metadata-schemas/%s/versions/%s", uuid.toString(), version)); } @Autowired - private MetadataSchemaFixtures metadataSchemaFixtures; + private MetadataSchemaRepository metadataSchemaRepository; @Autowired - private MetadataSchemaRepository metadataSchemaRepository; + private MetadataSchemaVersionRepository metadataSchemaVersionRepository; @Test @DisplayName("HTTP 200: delete single") public void res200_deleteSingle() { // GIVEN: Prepare data - metadataSchemaRepository.deleteAll(); - MetadataSchema schema = metadataSchemaFixtures.customSchema(); - metadataSchemaRepository.save(schema); + MetadataSchema schema = metadataSchemaRepository.findByUuid(Common.SCHEMA_SIMPLE_UUID).get(); + MetadataSchemaVersion schemaV1 = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_SIMPLE_V1_UUID).get(); // AND: Prepare request RequestEntity request = RequestEntity - .delete(url(schema.getUuid(), schema.getVersionString())) + .delete(url(schema.getUuid(), schemaV1.getVersion())) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .build(); ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { @@ -80,21 +80,22 @@ public void res200_deleteSingle() { // THEN: assertThat(result.getStatusCode(), is(equalTo(HttpStatus.NO_CONTENT))); - assertThat(metadataSchemaRepository.findAll().isEmpty(), is(true)); + assertThat(metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_SIMPLE_V1_UUID).isPresent(), is(false)); + assertThat(metadataSchemaRepository.findByUuid(Common.SCHEMA_SIMPLE_UUID).isPresent(), is(false)); } @Test @DisplayName("HTTP 200: delete latest") public void res200_deleteLatest() { // GIVEN: Prepare data - metadataSchemaRepository.deleteAll(); - MetadataSchema schemaV1 = metadataSchemaRepository.save(metadataSchemaFixtures.customSchemaV1(false)); - MetadataSchema schemaV2 = metadataSchemaRepository.save(metadataSchemaFixtures.customSchemaV2(schemaV1, false)); - MetadataSchema schemaV3 = metadataSchemaRepository.save(metadataSchemaFixtures.customSchemaV3(schemaV2, true)); + MetadataSchema schema = metadataSchemaRepository.findByUuid(Common.SCHEMA_MULTI_UUID).get(); + MetadataSchemaVersion schemaV1 = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_V1_UUID).get(); + MetadataSchemaVersion schemaV2 = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_V2_UUID).get(); + MetadataSchemaVersion schemaV3 = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_V3_UUID).get(); // AND: Prepare request RequestEntity request = RequestEntity - .delete(url(schemaV3.getUuid(), schemaV3.getVersionString())) + .delete(url(schema.getUuid(), schemaV3.getVersion())) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .build(); ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { @@ -106,24 +107,27 @@ public void res200_deleteLatest() { // THEN: assertThat(result.getStatusCode(), is(equalTo(HttpStatus.NO_CONTENT))); assertThat(metadataSchemaRepository.findAll().isEmpty(), is(false)); - assertThat(metadataSchemaRepository.findAll().size(), is(equalTo(2))); - assertThat(metadataSchemaRepository.findByUuidAndLatestIsTrue(schemaV3.getUuid()).isPresent(), is(true)); - assertThat(metadataSchemaRepository.findByUuidAndLatestIsTrue(schemaV3.getUuid()).get().getVersion(), is(equalTo(schemaV2.getVersion()))); - assertThat(metadataSchemaRepository.findByUuidAndLatestIsTrue(schemaV3.getUuid()).get().isLatest(), is(true)); + + assertThat(metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_V1_UUID).isPresent(), is(true)); + assertThat(metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_V2_UUID).isPresent(), is(true)); + assertThat(metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_V3_UUID).isPresent(), is(false)); + assertThat(metadataSchemaVersionRepository.getLatestBySchemaUuid(Common.SCHEMA_MULTI_UUID).isPresent(), is(true)); + assertThat(metadataSchemaVersionRepository.getLatestBySchemaUuid(Common.SCHEMA_MULTI_UUID).get().getVersion(), is(equalTo(schemaV2.getVersion()))); + assertThat(metadataSchemaVersionRepository.getLatestBySchemaUuid(Common.SCHEMA_MULTI_UUID).get().isLatest(), is(true)); } @Test @DisplayName("HTTP 200: delete non-latest") public void res200_deleteNonLatest() { // GIVEN: Prepare data - metadataSchemaRepository.deleteAll(); - MetadataSchema schemaV1 = metadataSchemaRepository.save(metadataSchemaFixtures.customSchemaV1(false)); - MetadataSchema schemaV2 = metadataSchemaRepository.save(metadataSchemaFixtures.customSchemaV2(schemaV1, false)); - MetadataSchema schemaV3 = metadataSchemaRepository.save(metadataSchemaFixtures.customSchemaV3(schemaV2, true)); + MetadataSchema schema = metadataSchemaRepository.findByUuid(Common.SCHEMA_MULTI_UUID).get(); + MetadataSchemaVersion schemaV1 = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_V1_UUID).get(); + MetadataSchemaVersion schemaV2 = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_V2_UUID).get(); + MetadataSchemaVersion schemaV3 = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_V3_UUID).get(); // AND: Prepare request RequestEntity request = RequestEntity - .delete(url(schemaV2.getUuid(), schemaV2.getVersionString())) + .delete(url(schema.getUuid(), schemaV2.getVersion())) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .build(); ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { @@ -135,27 +139,28 @@ public void res200_deleteNonLatest() { // THEN: assertThat(result.getStatusCode(), is(equalTo(HttpStatus.NO_CONTENT))); assertThat(metadataSchemaRepository.findAll().isEmpty(), is(false)); - assertThat(metadataSchemaRepository.findAll().size(), is(equalTo(2))); - assertThat(metadataSchemaRepository.findByUuidAndLatestIsTrue(schemaV3.getUuid()).isPresent(), is(true)); - assertThat(metadataSchemaRepository.findByUuidAndLatestIsTrue(schemaV3.getUuid()).get().getVersion(), is(equalTo(schemaV3.getVersion()))); - assertThat(metadataSchemaRepository.findByUuidAndLatestIsTrue(schemaV3.getUuid()).get().isLatest(), is(true)); + + assertThat(metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_V2_UUID).isPresent(), is(false)); + assertThat(metadataSchemaVersionRepository.getLatestBySchemaUuid(Common.SCHEMA_MULTI_UUID).isPresent(), is(true)); + assertThat(metadataSchemaVersionRepository.getLatestBySchemaUuid(Common.SCHEMA_MULTI_UUID).get().getVersion(), is(equalTo(schemaV3.getVersion()))); + assertThat(metadataSchemaVersionRepository.getLatestBySchemaUuid(Common.SCHEMA_MULTI_UUID).get().isLatest(), is(true)); } @Test @DisplayName("HTTP 404") public void res404() { - createAdminNotFoundTestDelete(client, url("nonExisting", "1.0.0")); + createAdminNotFoundTestDelete(client, url(UUID.randomUUID(), "1.0.0")); } @Test @DisplayName("HTTP 403: User is not authenticated") public void res403_notAuthenticated() { - createNoUserForbiddenTestDelete(client, url(UUID.randomUUID().toString(), "1.0.0")); + createNoUserForbiddenTestDelete(client, url(UUID.randomUUID(), "1.0.0")); } @Test @DisplayName("HTTP 403: User is not an admin") public void res403_notAdmin() { - createUserForbiddenTestDelete(client, url(UUID.randomUUID().toString(), "1.0.0")); + createUserForbiddenTestDelete(client, url(UUID.randomUUID(), "1.0.0")); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Version_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Version_GET.java index d5dd693b8..ca839f61f 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Version_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Version_GET.java @@ -24,9 +24,9 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaVersionDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.schema.data.MetadataSchemaFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaRepository; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaVersionRepository; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaVersion; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -47,27 +47,20 @@ @DisplayName("GET /metadata-schemas/:schemaUuid/versions/:version") public class Version_GET extends WebIntegrationTest { - private URI url(String uuid, String version) { - return URI.create(format("/metadata-schemas/%s/versions/%s", uuid, version)); - } - @Autowired - private MetadataSchemaFixtures metadataSchemaFixtures; + private MetadataSchemaVersionRepository metadataSchemaRepository; - @Autowired - private MetadataSchemaRepository metadataSchemaRepository; + private URI url(UUID uuid, String version) { + return URI.create(format("/metadata-schemas/%s/versions/%s", uuid, version)); + } @Test @DisplayName("HTTP 200") public void res200() { - // GIVEN: Prepare data - MetadataSchema schema = metadataSchemaFixtures.resourceSchema(); - metadataSchemaRepository.deleteAll(); - metadataSchemaRepository.save(schema); - - // AND: Prepare request + // GIVEN: + final MetadataSchemaVersion schema = metadataSchemaRepository.getLatestBySchemaUuid(KnownUUIDs.SCHEMA_FDP_UUID).get(); RequestEntity request = RequestEntity - .get(url(schema.getUuid(), schema.getVersionString())) + .get(url(KnownUUIDs.SCHEMA_FDP_UUID, "1.0.0")) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .accept(MediaType.APPLICATION_JSON) .build(); @@ -85,14 +78,10 @@ public void res200() { @Test @DisplayName("HTTP 200") public void res200_latest() { - // GIVEN: Prepare data - MetadataSchema schema = metadataSchemaFixtures.resourceSchema(); - metadataSchemaRepository.deleteAll(); - metadataSchemaRepository.save(schema); - - // AND: Prepare request + // GIVEN: + final MetadataSchemaVersion schema = metadataSchemaRepository.getLatestBySchemaUuid(KnownUUIDs.SCHEMA_FDP_UUID).get(); RequestEntity request = RequestEntity - .get(url(schema.getUuid(), "latest")) + .get(url(KnownUUIDs.SCHEMA_FDP_UUID, "latest")) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .accept(MediaType.APPLICATION_JSON) .build(); @@ -110,22 +99,19 @@ public void res200_latest() { @Test @DisplayName("HTTP 404") public void res404() { - MetadataSchema schema = metadataSchemaFixtures.resourceSchema(); - metadataSchemaRepository.deleteAll(); - metadataSchemaRepository.save(schema); - createAdminNotFoundTestGet(client, url("nonExisting", "1.0.0")); - createAdminNotFoundTestGet(client, url(schema.getUuid(), "1.0.1")); + createAdminNotFoundTestGet(client, url(KnownUUIDs.NULL_UUID, "1.0.0")); + createAdminNotFoundTestGet(client, url(KnownUUIDs.SCHEMA_FDP_UUID, "1.0.1")); } @Test @DisplayName("HTTP 403: User is not authenticated") public void res403_notAuthenticated() { - createNoUserForbiddenTestGet(client, url(UUID.randomUUID().toString(), "1.0.0")); + createNoUserForbiddenTestGet(client, url(UUID.randomUUID(), "1.0.0")); } @Test @DisplayName("HTTP 403: User is not an admin") public void res403_notAdmin() { - createUserForbiddenTestGet(client, url(UUID.randomUUID().toString(), "1.0.0")); + createUserForbiddenTestGet(client, url(UUID.randomUUID(), "1.0.0")); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Version_PUT.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Version_PUT.java index 1b065ee4c..5acc9ca7e 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Version_PUT.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Version_PUT.java @@ -25,9 +25,13 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaUpdateDTO; import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaVersionDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.schema.data.MetadataSchemaFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaRepository; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaRepository; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaVersionRepository; import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaState; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaType; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaVersion; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -35,6 +39,7 @@ import org.springframework.http.*; import java.net.URI; +import java.util.List; import java.util.UUID; import static java.lang.String.format; @@ -48,7 +53,13 @@ @DisplayName("PUT /metadata-schemas/:schemaUuid/versions/:version") public class Version_PUT extends WebIntegrationTest { - private URI url(String uuid, String version) { + @Autowired + private MetadataSchemaRepository metadataSchemaRepository; + + @Autowired + private MetadataSchemaVersionRepository metadataSchemaVersionRepository; + + private URI url(UUID uuid, String version) { return URI.create(format("/metadata-schemas/%s/versions/%s", uuid, version)); } @@ -60,24 +71,16 @@ private MetadataSchemaUpdateDTO reqDto() { ); } - @Autowired - private MetadataSchemaFixtures metadataSchemaFixtures; - - @Autowired - private MetadataSchemaRepository metadataSchemaRepository; - @Test @DisplayName("HTTP 200") public void res200() { // GIVEN: Prepare data - MetadataSchema schema = metadataSchemaFixtures.customSchema(); - metadataSchemaRepository.deleteAll(); - metadataSchemaRepository.save(schema); + MetadataSchemaVersion schema = createCustomSchema(); MetadataSchemaUpdateDTO reqDto = reqDto(); // AND: Prepare request RequestEntity request = RequestEntity - .put(url(schema.getUuid(), schema.getVersionString())) + .put(url(schema.getSchema().getUuid(), schema.getVersion())) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .accept(MediaType.APPLICATION_JSON) .body(reqDto); @@ -96,22 +99,46 @@ public void res200() { assertThat(result.getBody().isAbstractSchema(), is(equalTo(schema.isAbstractSchema()))); } + private MetadataSchemaVersion createCustomSchema() { + final MetadataSchema schema = metadataSchemaRepository.saveAndFlush( + MetadataSchema.builder() + .uuid(UUID.randomUUID()) + .build() + ); + + return metadataSchemaVersionRepository.saveAndFlush( + MetadataSchemaVersion.builder() + .uuid(UUID.randomUUID()) + .schema(schema) + .version("0.1.0") + .name("Custom schema") + .state(MetadataSchemaState.DRAFT) + .description("") + .definition("") + .targetClasses(List.of()) + .type(MetadataSchemaType.CUSTOM) + .abstractSchema(false) + .published(false) + .build() + ); + } + @Test @DisplayName("HTTP 404") public void res404() { - createAdminNotFoundTestPut(client, url("nonExisting", "1.0.0"), reqDto()); + createAdminNotFoundTestPut(client, url(KnownUUIDs.NULL_UUID, "1.0.0"), reqDto()); } @Test @DisplayName("HTTP 403: User is not authenticated") public void res403_notAuthenticated() { - createNoUserForbiddenTestPut(client, url(UUID.randomUUID().toString(), "1.0.0"), reqDto()); + createNoUserForbiddenTestPut(client, url(UUID.randomUUID(), "1.0.0"), reqDto()); } @Test @DisplayName("HTTP 403: User is not an admin") public void res403_notAdmin() { - createUserForbiddenTestPut(client, url(UUID.randomUUID().toString(), "1.0.0"), reqDto()); + createUserForbiddenTestPut(client, url(UUID.randomUUID(), "1.0.0"), reqDto()); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Versions_POST.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Versions_POST.java index 9ca311b2d..798eb550e 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Versions_POST.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/schema/Versions_POST.java @@ -25,11 +25,10 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaDTO; import nl.dtls.fairdatapoint.api.dto.schema.MetadataSchemaReleaseDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.schema.data.MetadataSchemaFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaDraftRepository; -import nl.dtls.fairdatapoint.database.mongo.repository.MetadataSchemaRepository; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchema; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaDraft; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaRepository; +import nl.dtls.fairdatapoint.database.db.repository.MetadataSchemaVersionRepository; +import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaVersion; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -50,7 +49,7 @@ @DisplayName("POST /metadata-schemas/:schemaUuid/versions") public class Versions_POST extends WebIntegrationTest { - private URI url(String uuid) { + private URI url(UUID uuid) { return URI.create(format("/metadata-schemas/%s/versions", uuid)); } @@ -62,14 +61,11 @@ private MetadataSchemaReleaseDTO reqDto(String version, boolean published) { ); } - @Autowired - private MetadataSchemaFixtures metadataSchemaFixtures; - @Autowired private MetadataSchemaRepository metadataSchemaRepository; @Autowired - private MetadataSchemaDraftRepository metadataSchemaDraftRepository; + private MetadataSchemaVersionRepository metadataSchemaVersionRepository; private final ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { @@ -79,15 +75,12 @@ private MetadataSchemaReleaseDTO reqDto(String version, boolean published) { @DisplayName("HTTP 200: publish new") public void res200_publishNew() { // GIVEN: prepare data - metadataSchemaRepository.deleteAll(); - metadataSchemaDraftRepository.deleteAll(); - MetadataSchemaDraft draft = metadataSchemaFixtures.customSchemaDraft1(); - metadataSchemaDraftRepository.save(draft); + MetadataSchemaVersion draft = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_DRAFT_V1_UUID).get(); MetadataSchemaReleaseDTO reqDto = reqDto("0.1.0", true); // AND: prepare request RequestEntity request = RequestEntity - .post(url(draft.getUuid())) + .post(url(draft.getSchema().getUuid())) .accept(MediaType.APPLICATION_JSON) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .body(reqDto); @@ -102,23 +95,22 @@ public void res200_publishNew() { assertThat("Result is published", result.getBody().getLatest().isPublished(), is(equalTo(true))); assertThat("Result has correct name", result.getBody().getName(), is(equalTo(draft.getName()))); assertThat("Result has correct version", result.getBody().getLatest().getVersion(), is(equalTo(reqDto.getVersion()))); - assertThat("Metadata schema repository has one schema", metadataSchemaRepository.count(), is(equalTo(1L))); + assertThat("Metadata schema repository has one schema", metadataSchemaRepository.count(), is(equalTo(14L))); + assertThat("Draft is now latest version", metadataSchemaVersionRepository.findByUuid(draft.getUuid()).get().isDraft(), is(false)); + assertThat("Draft is now latest version", metadataSchemaVersionRepository.findByUuid(draft.getUuid()).get().isLatest(), is(true)); } @Test @DisplayName("HTTP 200: publish newer version") public void res200_publishNewerVersion() { // GIVEN: prepare data - metadataSchemaRepository.deleteAll(); - metadataSchemaDraftRepository.deleteAll(); - MetadataSchema schemaV1 = metadataSchemaRepository.save(metadataSchemaFixtures.customSchemaV1(true)); - MetadataSchemaDraft draft = metadataSchemaFixtures.customSchemaDraft1(); - metadataSchemaDraftRepository.save(draft); - MetadataSchemaReleaseDTO reqDto = reqDto("2.0.0", true); + MetadataSchemaVersion existing = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_DRAFT_V2_UUID).get(); + MetadataSchemaVersion draft = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_DRAFT_DRAFT_UUID).get(); + MetadataSchemaReleaseDTO reqDto = reqDto("4.0.0", true); // AND: prepare request RequestEntity request = RequestEntity - .post(url(draft.getUuid())) + .post(url(draft.getSchema().getUuid())) .accept(MediaType.APPLICATION_JSON) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .body(reqDto); @@ -133,25 +125,24 @@ public void res200_publishNewerVersion() { assertThat("Result is published", result.getBody().getLatest().isPublished(), is(equalTo(true))); assertThat("Result has correct name", result.getBody().getName(), is(equalTo(draft.getName()))); assertThat("Result has correct version", result.getBody().getLatest().getVersion(), is(equalTo(reqDto.getVersion()))); - assertThat("Metadata schema repository has 2 schemas", metadataSchemaRepository.count(), is(equalTo(2L))); - assertThat("Older version is still stored", metadataSchemaRepository.findByUuidAndVersionString(schemaV1.getUuid(), schemaV1.getVersionString()).isPresent(), is(true)); - assertThat("Older version is no longer the latest", metadataSchemaRepository.findByUuidAndVersionString(schemaV1.getUuid(), schemaV1.getVersionString()).get().isLatest(), is(false)); + assertThat("Metadata schema repository has 2 schemas", metadataSchemaRepository.count(), is(equalTo(14L))); + assertThat("Older version is still stored", metadataSchemaVersionRepository.findByUuid(existing.getUuid()).isPresent(), is(true)); + assertThat("Older version is no longer the latest", metadataSchemaVersionRepository.findByUuid(existing.getUuid()).get().isLatest(), is(false)); + assertThat("Older version is still stored", metadataSchemaVersionRepository.findByUuid(draft.getUuid()).isPresent(), is(true)); + assertThat("Older version is no longer the latest", metadataSchemaVersionRepository.findByUuid(draft.getUuid()).get().isDraft(), is(false)); + assertThat("Older version is no longer the latest", metadataSchemaVersionRepository.findByUuid(draft.getUuid()).get().isLatest(), is(true)); } @Test @DisplayName("HTTP 400: not newer version") public void res400_notNewerVersion() { // GIVEN: prepare data - metadataSchemaRepository.deleteAll(); - metadataSchemaDraftRepository.deleteAll(); - metadataSchemaRepository.save(metadataSchemaFixtures.customSchemaV1(true)); - MetadataSchemaDraft draft = metadataSchemaFixtures.customSchemaDraft1(); - metadataSchemaDraftRepository.save(draft); - MetadataSchemaReleaseDTO reqDto = reqDto("0.1.0", true); + MetadataSchemaVersion draft = metadataSchemaVersionRepository.findByUuid(Common.SCHEMA_MULTI_DRAFT_DRAFT_UUID).get(); + MetadataSchemaReleaseDTO reqDto = reqDto("0.0.1", true); // AND: prepare request RequestEntity request = RequestEntity - .post(url(draft.getUuid())) + .post(url(draft.getSchema().getUuid())) .accept(MediaType.APPLICATION_JSON) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .body(reqDto); @@ -166,18 +157,18 @@ public void res400_notNewerVersion() { @Test @DisplayName("HTTP 404") public void res404() { - createNoUserForbiddenTestPost(client, url("nonExisting"), reqDto("1.0.0", true)); + createNoUserForbiddenTestPost(client, url(KnownUUIDs.NULL_UUID), reqDto("1.0.0", true)); } @Test @DisplayName("HTTP 403: User is not authenticated") public void res403_notAuthenticated() { - createNoUserForbiddenTestPost(client, url(UUID.randomUUID().toString()), reqDto("1.0.0", true)); + createNoUserForbiddenTestPost(client, url(UUID.randomUUID()), reqDto("1.0.0", true)); } @Test @DisplayName("HTTP 403: User is not an admin") public void res403_notAdmin() { - createUserForbiddenTestPost(client, url(UUID.randomUUID().toString()), reqDto("1.0.0", true)); + createUserForbiddenTestPost(client, url(UUID.randomUUID()), reqDto("1.0.0", true)); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/search/Filters_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/search/Filters_GET.java index 376c7de9c..2c04459c2 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/search/Filters_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/search/Filters_GET.java @@ -24,14 +24,15 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.search.SearchFilterDTO; -import nl.dtls.fairdatapoint.api.dto.search.SearchQueryDTO; -import nl.dtls.fairdatapoint.api.dto.search.SearchResultDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.SettingsRepository; +import nl.dtls.fairdatapoint.database.db.repository.SettingsRepository; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; import java.net.URI; import java.util.List; diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/List_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/List_GET.java index 51f820206..c9c8a5fc6 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/List_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/List_GET.java @@ -27,7 +27,10 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; import java.net.URI; diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/List_POST.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/List_POST.java index 6504bae47..f987712ac 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/List_POST.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/List_POST.java @@ -28,7 +28,10 @@ import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.core.ParameterizedTypeReference; -import org.springframework.http.*; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.RequestEntity; +import org.springframework.http.ResponseEntity; import java.net.URI; import java.util.List; diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/Detail_DELETE.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/Detail_DELETE.java index 86d0477c1..b67232230 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/Detail_DELETE.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/Detail_DELETE.java @@ -23,13 +23,8 @@ package nl.dtls.fairdatapoint.acceptance.search.query.saved; import nl.dtls.fairdatapoint.WebIntegrationTest; -import nl.dtls.fairdatapoint.api.dto.search.SearchQueryVariablesDTO; -import nl.dtls.fairdatapoint.api.dto.search.SearchSavedQueryChangeDTO; -import nl.dtls.fairdatapoint.api.dto.search.SearchSavedQueryDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.search.SearchSavedQueryFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.SearchSavedQueryRepository; +import nl.dtls.fairdatapoint.database.db.repository.SearchSavedQueryRepository; import nl.dtls.fairdatapoint.entity.search.SearchSavedQuery; -import nl.dtls.fairdatapoint.entity.search.SearchSavedQueryType; import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -41,6 +36,7 @@ import org.springframework.http.ResponseEntity; import java.net.URI; +import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @@ -49,22 +45,18 @@ @DisplayName("DELETE /search/query/saved/:uuid") public class Detail_DELETE extends WebIntegrationTest { - private URI url(String uuid) { - return URI.create("/search/query/saved/" + uuid); + private URI url(UUID uuid) { + return URI.create("/search/query/saved/" + uuid.toString()); } @Autowired private SearchSavedQueryRepository searchSavedQueryRepository; - @Autowired - private SearchSavedQueryFixtures searchSavedQueryFixtures; - @Test @DisplayName("HTTP 403: anonymous user") public void res403_anonymousUser() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery query = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPublic01()); + SearchSavedQuery query = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PUBLIC_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity @@ -78,15 +70,14 @@ public void res403_anonymousUser() { // THEN: assertThat(result.getStatusCode(), is(equalTo(HttpStatus.FORBIDDEN))); - assertThat(searchSavedQueryRepository.count(), is(equalTo(1L))); + assertThat(searchSavedQueryRepository.count(), is(equalTo(3L))); } @Test @DisplayName("HTTP 403: non-owner user") public void res403_nonOwnerUser() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery query = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPublic01()); + SearchSavedQuery query = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_INTERNAL_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity @@ -101,15 +92,14 @@ public void res403_nonOwnerUser() { // THEN: assertThat(result.getStatusCode(), is(equalTo(HttpStatus.FORBIDDEN))); - assertThat(searchSavedQueryRepository.count(), is(equalTo(1L))); + assertThat(searchSavedQueryRepository.count(), is(equalTo(3L))); } @Test @DisplayName("HTTP 200: owner") public void res200_owner() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery query = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPublic01()); + SearchSavedQuery query = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PUBLIC_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity @@ -124,15 +114,14 @@ public void res200_owner() { // THEN: assertThat(result.getStatusCode(), is(equalTo(HttpStatus.NO_CONTENT))); - assertThat(searchSavedQueryRepository.count(), is(equalTo(0L))); + assertThat(searchSavedQueryRepository.count(), is(equalTo(2L))); } @Test @DisplayName("HTTP 200: admin") public void res200_admin() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery query = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPublic01()); + SearchSavedQuery query = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PUBLIC_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity @@ -147,6 +136,6 @@ public void res200_admin() { // THEN: assertThat(result.getStatusCode(), is(equalTo(HttpStatus.NO_CONTENT))); - assertThat(searchSavedQueryRepository.count(), is(equalTo(0L))); + assertThat(searchSavedQueryRepository.count(), is(equalTo(2L))); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/Detail_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/Detail_GET.java index 221ca5bf7..fef9f2ad0 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/Detail_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/Detail_GET.java @@ -24,9 +24,9 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.search.SearchSavedQueryDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.search.SearchSavedQueryFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.SearchSavedQueryRepository; +import nl.dtls.fairdatapoint.database.db.repository.SearchSavedQueryRepository; import nl.dtls.fairdatapoint.entity.search.SearchSavedQuery; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -37,8 +37,8 @@ import org.springframework.http.ResponseEntity; import java.net.URI; -import java.util.List; import java.util.Objects; +import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @@ -47,22 +47,18 @@ @DisplayName("GET /search/query/saved/:uuid") public class Detail_GET extends WebIntegrationTest { - private URI url(String uuid) { - return URI.create("/search/query/saved/" + uuid); + private URI url(UUID uuid) { + return URI.create("/search/query/saved/" + uuid.toString()); } @Autowired private SearchSavedQueryRepository searchSavedQueryRepository; - @Autowired - private SearchSavedQueryFixtures searchSavedQueryFixtures; - @Test @DisplayName("HTTP 200: anonymous user, public query") public void res200_anonymousUserPublic() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery query = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPublic01()); + SearchSavedQuery query = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PUBLIC_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity @@ -83,8 +79,7 @@ public void res200_anonymousUserPublic() { @DisplayName("HTTP 404: anonymous user, internal query") public void res404_anonymousUserInternal() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery query = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryInternal01()); + SearchSavedQuery query = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_INTERNAL_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity @@ -104,8 +99,7 @@ public void res404_anonymousUserInternal() { @DisplayName("HTTP 404: anonymous user, private query") public void res404_anonymousUserPrivate() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery query = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPrivate01()); + SearchSavedQuery query = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PRIVATE_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity @@ -125,8 +119,7 @@ public void res404_anonymousUserPrivate() { @DisplayName("HTTP 200: user, public query") public void res200_userPublic() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery query = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPublic01()); + SearchSavedQuery query = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PUBLIC_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity @@ -148,8 +141,7 @@ public void res200_userPublic() { @DisplayName("HTTP 404: user, internal query") public void res404_userInternal() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery query = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryInternal01()); + SearchSavedQuery query = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_INTERNAL_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity @@ -171,13 +163,12 @@ public void res404_userInternal() { @DisplayName("HTTP 200: owner, private query") public void res200_ownerPrivate() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery query = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPrivate01()); + SearchSavedQuery query = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PRIVATE_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity .get(url(query.getUuid())) - .header(HttpHeaders.AUTHORIZATION, NIKOLA_TOKEN) + .header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN) .build(); ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { }; @@ -194,13 +185,12 @@ public void res200_ownerPrivate() { @DisplayName("HTTP 404: non-owner, private query") public void res404_nonOwnerPrivate() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery query = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPrivate01()); + SearchSavedQuery query = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PRIVATE_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity .get(url(query.getUuid())) - .header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN) + .header(HttpHeaders.AUTHORIZATION, NIKOLA_TOKEN) .build(); ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { }; @@ -216,8 +206,7 @@ public void res404_nonOwnerPrivate() { @DisplayName("HTTP 200: admin, private query") public void res200_adminPrivate() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery query = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPrivate01()); + SearchSavedQuery query = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PRIVATE_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/Detail_PUT.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/Detail_PUT.java index 16598d5cc..18dccae85 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/Detail_PUT.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/Detail_PUT.java @@ -26,8 +26,7 @@ import nl.dtls.fairdatapoint.api.dto.search.SearchQueryVariablesDTO; import nl.dtls.fairdatapoint.api.dto.search.SearchSavedQueryChangeDTO; import nl.dtls.fairdatapoint.api.dto.search.SearchSavedQueryDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.search.SearchSavedQueryFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.SearchSavedQueryRepository; +import nl.dtls.fairdatapoint.database.db.repository.SearchSavedQueryRepository; import nl.dtls.fairdatapoint.entity.search.SearchSavedQuery; import nl.dtls.fairdatapoint.entity.search.SearchSavedQueryType; import nl.dtls.fairdatapoint.util.KnownUUIDs; @@ -41,6 +40,7 @@ import org.springframework.http.ResponseEntity; import java.net.URI; +import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @@ -49,22 +49,18 @@ @DisplayName("PUT /search/query/saved/:uuid") public class Detail_PUT extends WebIntegrationTest { - private URI url(String uuid) { - return URI.create("/search/query/saved/" + uuid); + private URI url(UUID uuid) { + return URI.create("/search/query/saved/" + uuid.toString()); } @Autowired private SearchSavedQueryRepository searchSavedQueryRepository; - @Autowired - private SearchSavedQueryFixtures searchSavedQueryFixtures; - @Test @DisplayName("HTTP 403: anonymous user") public void res403_anonymousUser() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery query = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPublic01()); + SearchSavedQuery query = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PUBLIC_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity @@ -96,8 +92,7 @@ public void res403_anonymousUser() { @DisplayName("HTTP 403: non-owner user") public void res403_nonOwnerUser() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery query = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPublic01()); + SearchSavedQuery query = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PUBLIC_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity @@ -130,8 +125,7 @@ public void res403_nonOwnerUser() { @DisplayName("HTTP 200: owner") public void res200_owner() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery query = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPublic01()); + SearchSavedQuery query = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PUBLIC_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity @@ -170,8 +164,7 @@ public void res200_owner() { @DisplayName("HTTP 200: admin") public void res200_admin() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery query = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPublic01()); + SearchSavedQuery query = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PUBLIC_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/List_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/List_GET.java index 447479afe..d816059ba 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/List_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/List_GET.java @@ -24,9 +24,9 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.search.SearchSavedQueryDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.search.SearchSavedQueryFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.SearchSavedQueryRepository; +import nl.dtls.fairdatapoint.database.db.repository.SearchSavedQueryRepository; import nl.dtls.fairdatapoint.entity.search.SearchSavedQuery; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -53,17 +53,13 @@ private URI url() { @Autowired private SearchSavedQueryRepository searchSavedQueryRepository; - @Autowired - private SearchSavedQueryFixtures searchSavedQueryFixtures; - @Test @DisplayName("HTTP 200: anonymous user") public void res200_anonymousUser() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery q1 = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPublic01()); - SearchSavedQuery q2 = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryInternal01()); - SearchSavedQuery q3 = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPrivate01()); + SearchSavedQuery q1 = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PUBLIC_UUID).get(); + SearchSavedQuery q2 = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_INTERNAL_UUID).get(); + SearchSavedQuery q3 = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PRIVATE_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity @@ -86,15 +82,14 @@ public void res200_anonymousUser() { @DisplayName("HTTP 200: non-owner user") public void res200_nonOwnerUser() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery q1 = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPublic01()); - SearchSavedQuery q2 = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryInternal01()); - SearchSavedQuery q3 = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPrivate01()); + SearchSavedQuery q1 = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PUBLIC_UUID).get(); + SearchSavedQuery q2 = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_INTERNAL_UUID).get(); + SearchSavedQuery q3 = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PRIVATE_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity .get(url()) - .header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN) + .header(HttpHeaders.AUTHORIZATION, NIKOLA_TOKEN) .build(); ParameterizedTypeReference> responseType = new ParameterizedTypeReference<>() { }; @@ -114,15 +109,14 @@ public void res200_nonOwnerUser() { @DisplayName("HTTP 200: owner user") public void res200_ownerUser() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery q1 = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPublic01()); - SearchSavedQuery q2 = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryInternal01()); - SearchSavedQuery q3 = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPrivate01()); + SearchSavedQuery q1 = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PUBLIC_UUID).get(); + SearchSavedQuery q2 = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_INTERNAL_UUID).get(); + SearchSavedQuery q3 = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PRIVATE_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity .get(url()) - .header(HttpHeaders.AUTHORIZATION, NIKOLA_TOKEN) + .header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN) .build(); ParameterizedTypeReference> responseType = new ParameterizedTypeReference<>() { }; @@ -143,10 +137,9 @@ public void res200_ownerUser() { @DisplayName("HTTP 200: admin") public void res200_admin() { // GIVEN: prepare data - searchSavedQueryRepository.deleteAll(); - SearchSavedQuery q1 = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPublic01()); - SearchSavedQuery q2 = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryInternal01()); - SearchSavedQuery q3 = searchSavedQueryRepository.save(searchSavedQueryFixtures.savedQueryPrivate01()); + SearchSavedQuery q1 = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PUBLIC_UUID).get(); + SearchSavedQuery q2 = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_INTERNAL_UUID).get(); + SearchSavedQuery q3 = searchSavedQueryRepository.findByUuid(KnownUUIDs.SAVED_QUERY_PRIVATE_UUID).get(); // AND: prepare request RequestEntity request = RequestEntity diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/List_POST.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/List_POST.java index e814aa682..e4e48e697 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/List_POST.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/search/query/saved/List_POST.java @@ -26,9 +26,7 @@ import nl.dtls.fairdatapoint.api.dto.search.SearchQueryVariablesDTO; import nl.dtls.fairdatapoint.api.dto.search.SearchSavedQueryChangeDTO; import nl.dtls.fairdatapoint.api.dto.search.SearchSavedQueryDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.search.SearchSavedQueryFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.SearchSavedQueryRepository; -import nl.dtls.fairdatapoint.entity.search.SearchSavedQuery; +import nl.dtls.fairdatapoint.database.db.repository.SearchSavedQueryRepository; import nl.dtls.fairdatapoint.entity.search.SearchSavedQueryType; import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; @@ -41,7 +39,6 @@ import org.springframework.http.ResponseEntity; import java.net.URI; -import java.util.List; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/settings/List_DELETE.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/settings/List_DELETE.java index 5cd66bc5f..50dea6d2d 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/settings/List_DELETE.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/settings/List_DELETE.java @@ -23,10 +23,14 @@ package nl.dtls.fairdatapoint.acceptance.settings; import nl.dtls.fairdatapoint.WebIntegrationTest; +import nl.dtls.fairdatapoint.api.controller.settings.SettingsDefaults; import nl.dtls.fairdatapoint.api.dto.settings.SettingsDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.SettingsRepository; -import nl.dtls.fairdatapoint.entity.settings.*; +import nl.dtls.fairdatapoint.api.dto.settings.SettingsMetricDTO; +import nl.dtls.fairdatapoint.database.db.repository.SettingsRepository; +import nl.dtls.fairdatapoint.entity.settings.Settings; import nl.dtls.fairdatapoint.service.settings.SettingsCache; +import nl.dtls.fairdatapoint.service.settings.SettingsMapper; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -35,7 +39,6 @@ import org.springframework.http.*; import java.net.URI; -import java.util.Collections; import java.util.List; import java.util.Objects; @@ -53,6 +56,12 @@ public class List_DELETE extends WebIntegrationTest { @Autowired private SettingsCache settingsCache; + @Autowired + private SettingsDefaults settingsDefaults; + + @Autowired + private SettingsMapper settingsMapper; + private final ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { }; @@ -61,41 +70,12 @@ private URI url() { return URI.create("/settings"); } - private Settings customSettings() { - return Settings.builder() - .metadataMetrics( - List.of(new SettingsMetricsEntry( - "http://example.com/metric", - "http://example.com/resource" - )) - ) - .ping(SettingsPing.builder() - .enabled(false) - .endpoints(List.of( - "https://home.fairdatapoint.org", - "https://example.com/index" - )) - .build() - ) - .searchFilters(Collections.emptyList()) - .forms(SettingsForms - .builder() - .autocomplete(SettingsFormsAutocomplete - .builder() - .searchNamespace(true) - .sources(Collections.emptyList()) - .build() - ) - .build() - ) - .build(); - } - @Test @DisplayName("HTTP 200: default settings") public void res200_defaultSettings() { // GIVEN: prepare data - Settings defaultSettings = Settings.getDefault(); + Settings defaultSettings = settingsDefaults.getDefaults(); + List metrics = defaultSettings.getMetrics().stream().map(settingsMapper::toMetricDTO).toList(); settingsRepository.deleteAll(); settingsCache.updateCachedSettings(); @@ -112,19 +92,23 @@ public void res200_defaultSettings() { // THEN assertThat("Correct response code is received", result.getStatusCode(), is(equalTo(HttpStatus.OK))); assertThat("Response body is not null", result.getBody(), is(notNullValue())); - assertThat("Response contains default metrics", Objects.requireNonNull(result.getBody()).getMetadataMetrics(), is(equalTo(defaultSettings.getMetadataMetrics()))); - assertThat("Response contains default ping enabled", Objects.requireNonNull(result.getBody()).getPing().getEnabled(), is(equalTo(defaultSettings.getPing().isEnabled()))); - assertThat("Response contains default ping endpoints", Objects.requireNonNull(result.getBody()).getPing().getEndpoints(), is(equalTo(defaultSettings.getPing().getEndpoints()))); + assertThat("Response contains default metrics", Objects.requireNonNull(result.getBody()).getMetadataMetrics(), is(equalTo(metrics))); + assertThat("Response contains default ping enabled", Objects.requireNonNull(result.getBody()).getPing().getEnabled(), is(equalTo(defaultSettings.getPingEnabled()))); + assertThat("Response contains default ping endpoints", Objects.requireNonNull(result.getBody()).getPing().getEndpoints(), is(equalTo(defaultSettings.getPingEndpoints()))); } @Test @DisplayName("HTTP 200: custom settings") public void res200_customSettings() { // GIVEN: prepare data - Settings defaultSettings = Settings.getDefault(); - Settings customSettings = customSettings(); - settingsRepository.deleteAll(); - settingsRepository.insert(customSettings); + Settings defaultSettings = settingsDefaults.getDefaults(); + List metrics = defaultSettings.getMetrics().stream().map(settingsMapper::toMetricDTO).toList(); + Settings settings = settingsRepository.findByUuid(KnownUUIDs.SETTINGS_UUID).get(); + settings.setAppTitle("Custom title"); + settings.setAppSubtitle("Custom subtitle"); + settings.setPingEndpoints(List.of("http://example.com/ping")); + settings.setAutocompleteSearchNamespace(false); + settingsRepository.saveAndFlush(settings); settingsCache.updateCachedSettings(); // AND: prepare request @@ -141,9 +125,9 @@ public void res200_customSettings() { assertThat("No settings are created", settingsRepository.findAll().size(), is(equalTo(1))); assertThat("Correct response code is received", result.getStatusCode(), is(equalTo(HttpStatus.OK))); assertThat("Response body is not null", result.getBody(), is(notNullValue())); - assertThat("Response contains default metrics", Objects.requireNonNull(result.getBody()).getMetadataMetrics(), is(equalTo(defaultSettings.getMetadataMetrics()))); - assertThat("Response contains default ping enabled", Objects.requireNonNull(result.getBody()).getPing().getEnabled(), is(equalTo(defaultSettings.getPing().isEnabled()))); - assertThat("Response contains default ping endpoints", Objects.requireNonNull(result.getBody()).getPing().getEndpoints(), is(equalTo(defaultSettings.getPing().getEndpoints()))); + assertThat("Response contains default metrics", Objects.requireNonNull(result.getBody()).getMetadataMetrics(), is(equalTo(metrics))); + assertThat("Response contains default ping enabled", Objects.requireNonNull(result.getBody()).getPing().getEnabled(), is(equalTo(defaultSettings.getPingEnabled()))); + assertThat("Response contains default ping endpoints", Objects.requireNonNull(result.getBody()).getPing().getEndpoints(), is(equalTo(defaultSettings.getPingEndpoints()))); } @Test diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/settings/List_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/settings/List_GET.java index c3377409b..7398d95b4 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/settings/List_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/settings/List_GET.java @@ -23,13 +23,14 @@ package nl.dtls.fairdatapoint.acceptance.settings; import nl.dtls.fairdatapoint.WebIntegrationTest; +import nl.dtls.fairdatapoint.api.controller.settings.SettingsDefaults; import nl.dtls.fairdatapoint.api.dto.settings.SettingsDTO; -import nl.dtls.fairdatapoint.database.mongo.repository.SettingsRepository; +import nl.dtls.fairdatapoint.api.dto.settings.SettingsMetricDTO; +import nl.dtls.fairdatapoint.database.db.repository.SettingsRepository; import nl.dtls.fairdatapoint.entity.settings.Settings; -import nl.dtls.fairdatapoint.entity.settings.SettingsMetricsEntry; -import nl.dtls.fairdatapoint.entity.settings.SettingsPing; import nl.dtls.fairdatapoint.service.settings.SettingsCache; -import org.junit.jupiter.api.AfterAll; +import nl.dtls.fairdatapoint.service.settings.SettingsMapper; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -38,7 +39,6 @@ import org.springframework.http.*; import java.net.URI; -import java.util.Collections; import java.util.List; import java.util.Objects; @@ -56,6 +56,12 @@ public class List_GET extends WebIntegrationTest { @Autowired private SettingsCache settingsCache; + @Autowired + private SettingsDefaults settingsDefaults; + + @Autowired + private SettingsMapper settingsMapper; + private final ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { }; @@ -64,31 +70,12 @@ private URI url() { return URI.create("/settings"); } - private Settings customSettings() { - return Settings.builder() - .metadataMetrics( - List.of(new SettingsMetricsEntry( - "http://example.com/metric", - "http://example.com/resource" - )) - ) - .ping(SettingsPing.builder() - .enabled(false) - .endpoints(List.of( - "https://home.fairdatapoint.org", - "https://example.com/index" - )) - .build() - ) - .searchFilters(Collections.emptyList()) // TODO! - .build(); - } - @Test @DisplayName("HTTP 200: default settings") public void res200_defaultSettings() { // GIVEN: prepare data - Settings settings = Settings.getDefault(); + Settings settings = settingsDefaults.getDefaults(); + List metrics = settings.getMetrics().stream().map(settingsMapper::toMetricDTO).toList(); settingsRepository.deleteAll(); settingsCache.updateCachedSettings(); @@ -106,18 +93,21 @@ public void res200_defaultSettings() { assertThat("No settings are created", settingsRepository.findAll().size(), is(equalTo(0))); assertThat("Correct response code is received", result.getStatusCode(), is(equalTo(HttpStatus.OK))); assertThat("Response body is not null", result.getBody(), is(notNullValue())); - assertThat("Response contains default metrics", Objects.requireNonNull(result.getBody()).getMetadataMetrics(), is(equalTo(settings.getMetadataMetrics()))); - assertThat("Response contains default ping enabled", Objects.requireNonNull(result.getBody()).getPing().getEnabled(), is(equalTo(settings.getPing().isEnabled()))); - assertThat("Response contains default ping endpoints", Objects.requireNonNull(result.getBody()).getPing().getEndpoints(), is(equalTo(settings.getPing().getEndpoints()))); + assertThat("Response contains default metrics", Objects.requireNonNull(result.getBody()).getMetadataMetrics(), is(equalTo(metrics))); + assertThat("Response contains default ping enabled", Objects.requireNonNull(result.getBody()).getPing().getEnabled(), is(equalTo(settings.getPingEnabled()))); + assertThat("Response contains default ping endpoints", Objects.requireNonNull(result.getBody()).getPing().getEndpoints(), is(equalTo(settings.getPingEndpoints()))); } @Test @DisplayName("HTTP 200: custom settings") public void res200_customSettings() { // GIVEN: prepare data - Settings settings = customSettings(); - settingsRepository.deleteAll(); - settingsRepository.insert(settings); + Settings settings = settingsRepository.findByUuid(KnownUUIDs.NULL_UUID).get(); + settings.setAppTitle("Custom title"); + settings.setAppSubtitle("Custom subtitle"); + settings.setPingEndpoints(List.of("http://example.com/ping")); + settings.setAutocompleteSearchNamespace(false); + settingsRepository.saveAndFlush(settings); settingsCache.updateCachedSettings(); // AND: prepare request @@ -134,9 +124,9 @@ public void res200_customSettings() { assertThat("No settings are created", settingsRepository.findAll().size(), is(equalTo(1))); assertThat("Correct response code is received", result.getStatusCode(), is(equalTo(HttpStatus.OK))); assertThat("Response body is not null", result.getBody(), is(notNullValue())); - assertThat("Response contains custom metrics", Objects.requireNonNull(result.getBody()).getMetadataMetrics(), is(equalTo(settings.getMetadataMetrics()))); - assertThat("Response contains custom ping enabled", Objects.requireNonNull(result.getBody()).getPing().getEnabled(), is(equalTo(settings.getPing().isEnabled()))); - assertThat("Response contains custom ping endpoints", Objects.requireNonNull(result.getBody()).getPing().getEndpoints(), is(equalTo(settings.getPing().getEndpoints()))); + assertThat("Response contains custom app title", Objects.requireNonNull(result.getBody()).getAppTitle(), is(equalTo(settings.getAppTitle()))); + assertThat("Response contains custom ping enabled", Objects.requireNonNull(result.getBody()).getPing().getEnabled(), is(equalTo(settings.getPingEnabled()))); + assertThat("Response contains custom ping endpoints", Objects.requireNonNull(result.getBody()).getPing().getEndpoints(), is(equalTo(settings.getPingEndpoints()))); } @Test diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/settings/List_PUT.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/settings/List_PUT.java index 90415fc43..7d09ea609 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/settings/List_PUT.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/settings/List_PUT.java @@ -24,13 +24,10 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.settings.*; -import nl.dtls.fairdatapoint.database.mongo.repository.SettingsRepository; +import nl.dtls.fairdatapoint.database.db.repository.SettingsRepository; import nl.dtls.fairdatapoint.entity.settings.Settings; -import nl.dtls.fairdatapoint.entity.settings.SettingsFormsAutocomplete; -import nl.dtls.fairdatapoint.entity.settings.SettingsMetricsEntry; -import nl.dtls.fairdatapoint.entity.settings.SettingsPing; import nl.dtls.fairdatapoint.service.settings.SettingsCache; -import org.junit.jupiter.api.AfterAll; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -65,36 +62,16 @@ private URI url() { return URI.create("/settings"); } - private Settings customSettings() { - return Settings.builder() - .metadataMetrics( - List.of(new SettingsMetricsEntry( - "http://example.com/metric", - "http://example.com/resource" - )) - ) - .ping(SettingsPing.builder() - .enabled(false) - .endpoints(List.of( - "https://home.fairdatapoint.org", - "https://example.com/index" - )) - .build() - ) - .searchFilters(Collections.emptyList()) - .build(); - } private SettingsUpdateDTO customSettingsUpdateDTO() { - Settings customSettings = customSettings(); return new SettingsUpdateDTO( + "My title", null, - null, - customSettings.getMetadataMetrics(), + List.of(), SettingsPingUpdateDTO .builder() - .enabled(customSettings.getPing().isEnabled()) - .endpoints(customSettings.getPing().getEndpoints()) + .enabled(true) + .endpoints(List.of("http://example.com", "http://example.org")) .build(), SettingsSearchDTO .builder() @@ -113,15 +90,14 @@ private SettingsUpdateDTO customSettingsUpdateDTO() { } private SettingsUpdateDTO invalidUpdateDTO() { - Settings customSettings = customSettings(); return new SettingsUpdateDTO( null, null, null, SettingsPingUpdateDTO .builder() - .enabled(customSettings.getPing().isEnabled()) - .endpoints(customSettings.getPing().getEndpoints()) + .enabled(true) + .endpoints(List.of("http://example.com", "http://example.org")) .build(), SettingsSearchDTO .builder() @@ -143,17 +119,16 @@ private SettingsUpdateDTO invalidUpdateDTO() { @DisplayName("HTTP 200: update settings") public void res200_updateSettings() { // GIVEN: prepare data - Settings settings = customSettings(); - settingsRepository.deleteAll(); - settingsRepository.insert(settings); + Settings settings = settingsRepository.findByUuid(KnownUUIDs.NULL_UUID).get(); settingsCache.updateCachedSettings(); + SettingsUpdateDTO dto = customSettingsUpdateDTO(); // AND: prepare request RequestEntity request = RequestEntity .put(url()) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .accept(MediaType.APPLICATION_JSON) - .body(customSettingsUpdateDTO()); + .body(dto); // WHEN ResponseEntity result = client.exchange(request, responseType); @@ -162,9 +137,10 @@ public void res200_updateSettings() { assertThat("No settings are created", settingsRepository.findAll().size(), is(equalTo(1))); assertThat("Correct response code is received", result.getStatusCode(), is(equalTo(HttpStatus.OK))); assertThat("Response body is not null", result.getBody(), is(notNullValue())); - assertThat("Response contains custom metrics", Objects.requireNonNull(result.getBody()).getMetadataMetrics(), is(equalTo(settings.getMetadataMetrics()))); - assertThat("Response contains custom ping enabled", Objects.requireNonNull(result.getBody()).getPing().getEnabled(), is(equalTo(settings.getPing().isEnabled()))); - assertThat("Response contains custom ping endpoints", Objects.requireNonNull(result.getBody()).getPing().getEndpoints(), is(equalTo(settings.getPing().getEndpoints()))); + assertThat("Response contains custom app title", Objects.requireNonNull(result.getBody()).getAppTitle(), is(equalTo("My title"))); + assertThat("Response contains custom metrics", Objects.requireNonNull(result.getBody()).getMetadataMetrics(), is(equalTo(List.of()))); + assertThat("Response contains custom ping enabled", Objects.requireNonNull(result.getBody()).getPing().getEnabled(), is(equalTo(dto.getPing().isEnabled()))); + assertThat("Response contains custom ping endpoints", Objects.requireNonNull(result.getBody()).getPing().getEndpoints(), is(equalTo(dto.getPing().getEndpoints()))); } @Test diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/token/List_POST.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/token/List_POST.java index 2f53ffb48..cf10dd04d 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/token/List_POST.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/token/List_POST.java @@ -23,12 +23,10 @@ package nl.dtls.fairdatapoint.acceptance.token; import nl.dtls.fairdatapoint.WebIntegrationTest; -import nl.dtls.fairdatapoint.acceptance.user.Common; import nl.dtls.fairdatapoint.api.dto.auth.AuthDTO; import nl.dtls.fairdatapoint.api.dto.auth.TokenDTO; import nl.dtls.fairdatapoint.api.dto.error.ErrorDTO; import nl.dtls.fairdatapoint.api.dto.user.UserDTO; -import nl.dtls.fairdatapoint.entity.user.User; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.core.ParameterizedTypeReference; diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Common.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Common.java index 0218fc27f..d452d7505 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Common.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Common.java @@ -26,7 +26,7 @@ import nl.dtls.fairdatapoint.api.dto.user.UserCreateDTO; import nl.dtls.fairdatapoint.api.dto.user.UserDTO; import nl.dtls.fairdatapoint.api.dto.user.UserProfileChangeDTO; -import nl.dtls.fairdatapoint.entity.user.User; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @@ -52,7 +52,7 @@ public static void compare(UserProfileChangeDTO entity, UserDTO dto) { assertThat(dto.getEmail(), is(equalTo(entity.getEmail()))); } - public static void compare(User entity, UserDTO dto) { + public static void compare(UserAccount entity, UserDTO dto) { assertThat(dto.getUuid(), is(equalTo(entity.getUuid()))); assertThat(dto.getFirstName(), is(equalTo(entity.getFirstName()))); assertThat(dto.getLastName(), is(equalTo(entity.getLastName()))); diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Current_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Current_GET.java index a68331def..caf1f3553 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Current_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Current_GET.java @@ -24,8 +24,9 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.user.UserDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; -import nl.dtls.fairdatapoint.entity.user.User; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; +import nl.dtls.fairdatapoint.entity.user.UserAccount; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -45,18 +46,19 @@ @DisplayName("GET /users/current") public class Current_GET extends WebIntegrationTest { + @Autowired + private UserAccountRepository userAccountRepository; + private URI url() { return URI.create("/users/current"); } - @Autowired - private UserFixtures userFixtures; - @Test @DisplayName("HTTP 200") public void res200() { // GIVEN: - User user = userFixtures.albert(); + UserAccount user = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); + RequestEntity request = RequestEntity .get(url()) .header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN) diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_Current_PUT.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_Current_PUT.java index 2dbba395a..6f06dac46 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_Current_PUT.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_Current_PUT.java @@ -26,10 +26,8 @@ import nl.dtls.fairdatapoint.api.dto.error.ErrorDTO; import nl.dtls.fairdatapoint.api.dto.user.UserDTO; import nl.dtls.fairdatapoint.api.dto.user.UserProfileChangeDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.*; @@ -52,9 +50,6 @@ private UserProfileChangeDTO reqDto() { return new UserProfileChangeDTO("EDITED: Albert", "EDITED: Einstein", "albert.einstein.edited@example.com"); } - @Autowired - private UserFixtures userFixtures; - @Test @DisplayName("HTTP 200") public void res200() { diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_Current_Password_PUT.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_Current_Password_PUT.java index 1061af9bf..7c68edbd0 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_Current_Password_PUT.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_Current_Password_PUT.java @@ -25,8 +25,9 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.user.UserDTO; import nl.dtls.fairdatapoint.api.dto.user.UserPasswordDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; -import nl.dtls.fairdatapoint.entity.user.User; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; +import nl.dtls.fairdatapoint.entity.user.UserAccount; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -46,6 +47,9 @@ @DisplayName("PUT /users/current/password") public class Detail_Current_Password_PUT extends WebIntegrationTest { + @Autowired + private UserAccountRepository userAccountRepository; + private URI url() { return URI.create("/users/current/password"); } @@ -54,14 +58,12 @@ private UserPasswordDTO reqDto() { return new UserPasswordDTO("newPassword"); } - @Autowired - private UserFixtures userFixtures; @Test @DisplayName("HTTP 200") public void res200() { // GIVEN: - User user = userFixtures.albert(); + UserAccount user = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); RequestEntity request = RequestEntity .put(url()) .header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN) diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_DELETE.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_DELETE.java index 9fa4dc35a..b63c5fbc1 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_DELETE.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_DELETE.java @@ -23,8 +23,9 @@ package nl.dtls.fairdatapoint.acceptance.user; import nl.dtls.fairdatapoint.WebIntegrationTest; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; -import nl.dtls.fairdatapoint.entity.user.User; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; +import nl.dtls.fairdatapoint.entity.user.UserAccount; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -47,20 +48,21 @@ @DisplayName("DELETE /users/:userUuid") public class Detail_DELETE extends WebIntegrationTest { + @Autowired + private UserAccountRepository userAccountRepository; + private URI url(String uuid) { return URI.create(format("/users/%s", uuid)); } - @Autowired - private UserFixtures userFixtures; - @Test @DisplayName("HTTP 204") public void res204() { // GIVEN: - User user = userFixtures.albert(); + UserAccount user = userAccountRepository.findByUuid(KnownUUIDs.USER_NIKOLA_UUID).get(); + RequestEntity request = RequestEntity - .delete(url(user.getUuid())) + .delete(url(user.getUuid().toString())) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .build(); ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { @@ -71,26 +73,26 @@ public void res204() { // THEN: assertThat(result.getStatusCode(), is(equalTo(HttpStatus.NO_CONTENT))); + assertThat(userAccountRepository.findByUuid(KnownUUIDs.USER_NIKOLA_UUID).isPresent(), is(equalTo(false))); } @Test @DisplayName("HTTP 403: User is not authenticated") public void res403_notAuthenticated() { - User user = userFixtures.albert(); - createNoUserForbiddenTestDelete(client, url(user.getUuid())); + UserAccount user = userAccountRepository.findByUuid(KnownUUIDs.USER_NIKOLA_UUID).get(); + createNoUserForbiddenTestDelete(client, url(user.getUuid().toString())); } @Test @DisplayName("HTTP 403: User is not an admin") public void res403_user() { - User user = userFixtures.albert(); - createUserForbiddenTestDelete(client, url(user.getUuid())); + UserAccount user = userAccountRepository.findByUuid(KnownUUIDs.USER_NIKOLA_UUID).get(); + createUserForbiddenTestDelete(client, url(user.getUuid().toString())); } @Test @DisplayName("HTTP 404") public void res404() { - createAdminNotFoundTestDelete(client, url("nonExisting")); + createAdminNotFoundTestDelete(client, url(KnownUUIDs.NULL_UUID.toString())); } - } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_GET.java index b5746d0f3..926ab0be0 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_GET.java @@ -24,8 +24,9 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.user.UserDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; -import nl.dtls.fairdatapoint.entity.user.User; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; +import nl.dtls.fairdatapoint.entity.user.UserAccount; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -36,6 +37,7 @@ import org.springframework.http.ResponseEntity; import java.net.URI; +import java.util.UUID; import static java.lang.String.format; import static nl.dtls.fairdatapoint.acceptance.common.ForbiddenTest.createNoUserForbiddenTestGet; @@ -47,18 +49,18 @@ @DisplayName("GET /users/:userUuid") public class Detail_GET extends WebIntegrationTest { - private URI url(String uuid) { + @Autowired + private UserAccountRepository userAccountRepository; + + private URI url(UUID uuid) { return URI.create(format("/users/%s", uuid)); } - @Autowired - private UserFixtures userFixtures; - @Test @DisplayName("HTTP 200") public void res200() { // GIVEN: - User user = userFixtures.albert(); + UserAccount user = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); RequestEntity request = RequestEntity .get(url(user.getUuid())) .header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN) @@ -77,14 +79,14 @@ public void res200() { @Test @DisplayName("HTTP 403") public void res403() { - User user = userFixtures.albert(); + UserAccount user = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); createNoUserForbiddenTestGet(client, url(user.getUuid())); } @Test @DisplayName("HTTP 404") public void res404() { - createUserNotFoundTestGet(client, url("nonExisting")); + createUserNotFoundTestGet(client, url(KnownUUIDs.NULL_UUID)); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_PUT.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_PUT.java index b683824c9..6fa05468a 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_PUT.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_PUT.java @@ -26,9 +26,10 @@ import nl.dtls.fairdatapoint.api.dto.error.ErrorDTO; import nl.dtls.fairdatapoint.api.dto.user.UserChangeDTO; import nl.dtls.fairdatapoint.api.dto.user.UserDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; -import nl.dtls.fairdatapoint.entity.user.User; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; +import nl.dtls.fairdatapoint.entity.user.UserAccount; import nl.dtls.fairdatapoint.entity.user.UserRole; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -36,6 +37,7 @@ import org.springframework.http.*; import java.net.URI; +import java.util.UUID; import static java.lang.String.format; import static nl.dtls.fairdatapoint.acceptance.common.ForbiddenTest.createNoUserForbiddenTestPut; @@ -48,23 +50,27 @@ @DisplayName("PUT /users/:userUuid") public class Detail_PUT extends WebIntegrationTest { - private URI url(String uuid) { + @Autowired + private UserAccountRepository userAccountRepository; + + private URI url(UUID uuid) { return URI.create(format("/users/%s", uuid)); } private UserChangeDTO reqDto() { - return new UserChangeDTO("EDITED: Albert", "EDITED: Einstein", "albert.einstein.edited@example.com", - UserRole.USER); + return UserChangeDTO.builder() + .firstName("EDITED: Albert") + .lastName("EDITED: Einstein") + .email("albert.einstein.edited@example.com") + .role(UserRole.USER) + .build(); } - @Autowired - private UserFixtures userFixtures; - @Test @DisplayName("HTTP 200") public void res200() { // GIVEN: - User user = userFixtures.albert(); + UserAccount user = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); RequestEntity request = RequestEntity .put(url(user.getUuid())) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) @@ -85,7 +91,7 @@ public void res200() { @DisplayName("HTTP 400: Email Already Exists") public void res400_emailAlreadyExists() { // GIVEN: - User user = userFixtures.albert(); + UserAccount user = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); UserChangeDTO reqDto = new UserChangeDTO("EDITED: Albert", "EDITED: Einstein", "nikola.tesla@example.com", UserRole.USER); RequestEntity request = RequestEntity @@ -107,21 +113,21 @@ public void res400_emailAlreadyExists() { @Test @DisplayName("HTTP 403: User is not authenticated") public void res403_notAuthenticated() { - User user = userFixtures.albert(); + UserAccount user = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); createNoUserForbiddenTestPut(client, url(user.getUuid()), reqDto()); } @Test @DisplayName("HTTP 403: User is not an admin") public void res403_user() { - User user = userFixtures.albert(); + UserAccount user = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); createUserForbiddenTestPut(client, url(user.getUuid()), reqDto()); } @Test @DisplayName("HTTP 404") public void res404() { - createAdminNotFoundTestPut(client, url("nonExisting"), reqDto()); + createAdminNotFoundTestPut(client, url(KnownUUIDs.NULL_UUID), reqDto()); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_Password_PUT.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_Password_PUT.java index 4fa9f854a..0807eefdf 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_Password_PUT.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/Detail_Password_PUT.java @@ -25,8 +25,9 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.user.UserDTO; import nl.dtls.fairdatapoint.api.dto.user.UserPasswordDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; -import nl.dtls.fairdatapoint.entity.user.User; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; +import nl.dtls.fairdatapoint.entity.user.UserAccount; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -37,6 +38,7 @@ import org.springframework.http.ResponseEntity; import java.net.URI; +import java.util.UUID; import static java.lang.String.format; import static nl.dtls.fairdatapoint.acceptance.common.ForbiddenTest.createNoUserForbiddenTestPut; @@ -49,7 +51,10 @@ @DisplayName("PUT /users/:userUuid/password") public class Detail_Password_PUT extends WebIntegrationTest { - private URI url(String uuid) { + @Autowired + private UserAccountRepository userAccountRepository; + + private URI url(UUID uuid) { return URI.create(format("/users/%s/password", uuid)); } @@ -57,14 +62,11 @@ private UserPasswordDTO reqDto() { return new UserPasswordDTO("newPassword"); } - @Autowired - private UserFixtures userFixtures; - @Test @DisplayName("HTTP 200") public void res200() { // GIVEN: - User user = userFixtures.albert(); + UserAccount user = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); RequestEntity request = RequestEntity .put(url(user.getUuid())) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) @@ -83,21 +85,21 @@ public void res200() { @Test @DisplayName("HTTP 403: User is not authenticated") public void res403_notAuthenticated() { - User user = userFixtures.albert(); + UserAccount user = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); createNoUserForbiddenTestPut(client, url(user.getUuid()), reqDto()); } @Test @DisplayName("HTTP 403: User is not an admin") public void res403_user() { - User user = userFixtures.albert(); + UserAccount user = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); createUserForbiddenTestPut(client, url(user.getUuid()), reqDto()); } @Test @DisplayName("HTTP 404") public void res404() { - createAdminNotFoundTestPut(client, url("nonExisting"), reqDto()); + createAdminNotFoundTestPut(client, url(KnownUUIDs.NULL_UUID), reqDto()); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/List_GET.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/List_GET.java index 588d6a8ac..1c754cf32 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/List_GET.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/List_GET.java @@ -24,7 +24,9 @@ import nl.dtls.fairdatapoint.WebIntegrationTest; import nl.dtls.fairdatapoint.api.dto.user.UserDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; +import nl.dtls.fairdatapoint.entity.user.UserAccount; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -45,17 +47,22 @@ @DisplayName("GET /users") public class List_GET extends WebIntegrationTest { + @Autowired + private UserAccountRepository userAccountRepository; + private URI url() { return URI.create("/users"); } - @Autowired - private UserFixtures userFixtures; - @Test @DisplayName("HTTP 200") public void res200() { // GIVEN: + UserAccount userAdmin = userAccountRepository.findByUuid(KnownUUIDs.USER_ADMIN_UUID).get(); + UserAccount userAlbert = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); + UserAccount userNikola = userAccountRepository.findByUuid(KnownUUIDs.USER_NIKOLA_UUID).get(); + UserAccount userIsaac = userAccountRepository.findByUuid(KnownUUIDs.USER_ISAAC_UUID).get(); + RequestEntity request = RequestEntity .get(url()) .header(HttpHeaders.AUTHORIZATION, ALBERT_TOKEN) @@ -69,10 +76,11 @@ public void res200() { // THEN: assertThat(result.getStatusCode(), is(equalTo(HttpStatus.OK))); List body = result.getBody(); - assertThat(body.size(), is(equalTo(3))); - Common.compare(userFixtures.admin(), body.get(0)); - Common.compare(userFixtures.albert(), body.get(1)); - Common.compare(userFixtures.nikola(), body.get(2)); + assertThat(body.size(), is(equalTo(4))); + Common.compare(userAdmin, body.get(0)); + Common.compare(userAlbert, body.get(1)); + Common.compare(userNikola, body.get(2)); + Common.compare(userIsaac, body.get(3)); } @Test diff --git a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/List_POST.java b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/List_POST.java index ec32323be..ce1dfac4d 100644 --- a/src/test/java/nl/dtls/fairdatapoint/acceptance/user/List_POST.java +++ b/src/test/java/nl/dtls/fairdatapoint/acceptance/user/List_POST.java @@ -26,8 +26,9 @@ import nl.dtls.fairdatapoint.api.dto.error.ErrorDTO; import nl.dtls.fairdatapoint.api.dto.user.UserCreateDTO; import nl.dtls.fairdatapoint.api.dto.user.UserDTO; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; -import nl.dtls.fairdatapoint.entity.user.User; +import nl.dtls.fairdatapoint.database.db.repository.UserAccountRepository; +import nl.dtls.fairdatapoint.entity.user.UserAccount; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -47,26 +48,33 @@ public class List_POST extends WebIntegrationTest { @Autowired - private UserFixtures userFixtures; + private UserAccountRepository userAccountRepository; private URI url() { return URI.create("/users"); } private UserCreateDTO reqDto() { - User user = userFixtures.isaac(); - return new UserCreateDTO(user.getFirstName(), user.getLastName(), user.getEmail(), "password", user.getRole()); + UserAccount user = userAccountRepository.findByUuid(KnownUUIDs.USER_ISAAC_UUID).get(); + return UserCreateDTO.builder() + .firstName(user.getFirstName()) + .lastName(user.getLastName()) + .email("isaac2@example.com") + .password("password") + .role(user.getRole()) + .build(); } @Test @DisplayName("HTTP 200") public void res200() { // GIVEN: + final UserCreateDTO reqDto = reqDto(); RequestEntity request = RequestEntity .post(url()) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) .accept(MediaType.APPLICATION_JSON) - .body(reqDto()); + .body(reqDto); ParameterizedTypeReference responseType = new ParameterizedTypeReference<>() { }; @@ -75,16 +83,21 @@ public void res200() { // THEN: assertThat(result.getStatusCode(), is(equalTo(HttpStatus.OK))); - Common.compare(reqDto(), result.getBody()); + Common.compare(reqDto, result.getBody()); } @Test @DisplayName("HTTP 400: Email already exists") public void res400_emailAlreadyExists() { // GIVEN: - User user = userFixtures.albert(); - UserCreateDTO reqDto = new UserCreateDTO(user.getFirstName(), user.getLastName(), user.getEmail(), "password" - , user.getRole()); + UserAccount user = userAccountRepository.findByUuid(KnownUUIDs.USER_ALBERT_UUID).get(); + UserCreateDTO reqDto = UserCreateDTO.builder() + .firstName(user.getFirstName()) + .lastName(user.getLastName()) + .email(user.getEmail()) + .password("password") + .role(user.getRole()) + .build(); RequestEntity request = RequestEntity .post(url()) .header(HttpHeaders.AUTHORIZATION, ADMIN_TOKEN) diff --git a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/MetadataSchemaDraftRepository.java b/src/test/java/nl/dtls/fairdatapoint/config/DatabaseConfig.java similarity index 72% rename from src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/MetadataSchemaDraftRepository.java rename to src/test/java/nl/dtls/fairdatapoint/config/DatabaseConfig.java index e01fb6218..6fe4900d5 100644 --- a/src/main/java/nl/dtls/fairdatapoint/database/mongo/repository/MetadataSchemaDraftRepository.java +++ b/src/test/java/nl/dtls/fairdatapoint/config/DatabaseConfig.java @@ -20,16 +20,19 @@ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ -package nl.dtls.fairdatapoint.database.mongo.repository; +package nl.dtls.fairdatapoint.config; -import nl.dtls.fairdatapoint.entity.schema.MetadataSchemaDraft; -import org.springframework.data.mongodb.repository.MongoRepository; - -import java.util.Optional; - -public interface MetadataSchemaDraftRepository - extends MongoRepository { - - Optional findByUuid(String uuid); +import org.springframework.boot.autoconfigure.flyway.FlywayMigrationStrategy; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +@Configuration +public class DatabaseConfig { + @Bean + public FlywayMigrationStrategy clean() { + return flyway -> { + flyway.clean(); + flyway.migrate(); + }; + } } diff --git a/src/test/java/nl/dtls/fairdatapoint/database/rdf/repository/common/MetadataRepositoryTest.java b/src/test/java/nl/dtls/fairdatapoint/database/rdf/repository/common/MetadataRepositoryTest.java index 36634c833..cefe7695f 100644 --- a/src/test/java/nl/dtls/fairdatapoint/database/rdf/repository/common/MetadataRepositoryTest.java +++ b/src/test/java/nl/dtls/fairdatapoint/database/rdf/repository/common/MetadataRepositoryTest.java @@ -28,6 +28,7 @@ package nl.dtls.fairdatapoint.database.rdf.repository.common; import nl.dtls.fairdatapoint.WebIntegrationTest; +import nl.dtls.fairdatapoint.database.rdf.migration.development.metadata.RdfMetadataMigration; import nl.dtls.fairdatapoint.database.rdf.repository.RepositoryMode; import nl.dtls.fairdatapoint.database.rdf.repository.generic.GenericMetadataRepository; import nl.dtls.fairdatapoint.utils.TestRdfMetadataFixtures; @@ -35,6 +36,7 @@ import org.eclipse.rdf4j.model.Model; import org.eclipse.rdf4j.model.Statement; import org.eclipse.rdf4j.model.vocabulary.DCTERMS; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -56,6 +58,15 @@ public class MetadataRepositoryTest extends WebIntegrationTest { @Autowired private TestRdfMetadataFixtures testMetadataFixtures; + @Autowired + private RdfMetadataMigration rdfMetadataMigration; + + @BeforeEach + public void before() { + rdfMetadataMigration.clean(); + rdfMetadataMigration.runMigration(); + } + @Test public void findWorks() throws Exception { // GIVEN: diff --git a/src/test/java/nl/dtls/fairdatapoint/service/index/harvester/HarvesterServiceTest.java b/src/test/java/nl/dtls/fairdatapoint/service/index/harvester/HarvesterServiceTest.java index 385068032..88e2a7154 100644 --- a/src/test/java/nl/dtls/fairdatapoint/service/index/harvester/HarvesterServiceTest.java +++ b/src/test/java/nl/dtls/fairdatapoint/service/index/harvester/HarvesterServiceTest.java @@ -22,18 +22,12 @@ */ package nl.dtls.fairdatapoint.service.index.harvester; -import nl.dtls.fairdatapoint.database.mongo.migration.development.resource.data.ResourceDefinitionFixtures; import nl.dtls.fairdatapoint.database.rdf.migration.development.metadata.data.RdfMetadataFixtures; import nl.dtls.fairdatapoint.database.rdf.migration.development.metadata.factory.MetadataFactoryImpl; import nl.dtls.fairdatapoint.database.rdf.repository.RepositoryMode; import nl.dtls.fairdatapoint.database.rdf.repository.exception.MetadataRepositoryException; import nl.dtls.fairdatapoint.database.rdf.repository.generic.GenericMetadataRepository; -import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; -import nl.dtls.fairdatapoint.service.metadata.enhance.MetadataEnhancer; -import nl.dtls.fairdatapoint.service.profile.ProfileService; -import nl.dtls.fairdatapoint.service.resource.ResourceDefinitionCache; import nl.dtls.fairdatapoint.vocabulary.FDP; -import nl.dtls.fairdatapoint.vocabulary.R3D; import org.eclipse.rdf4j.model.Model; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -63,15 +57,9 @@ public class HarvesterServiceTest { @Mock private RestTemplate restTemplate; - @Mock - private ResourceDefinitionCache resourceDefinitionCache; - @Spy private GenericMetadataRepository genericMetadataRepository; - @InjectMocks - private static MetadataEnhancer metadataEnhancer; - @InjectMocks private HarvesterService harvesterService; @@ -84,16 +72,12 @@ public class HarvesterServiceTest { private Model catalog; @BeforeEach - private void setup() { - // Setup resource definition; - ResourceDefinitionFixtures resourceDefinitionFixtures = new ResourceDefinitionFixtures(); - + public void setup() { // Setup RDF fixtures RdfMetadataFixtures fixtures = new RdfMetadataFixtures(new MetadataFactoryImpl()); // Create repository repository = fixtures.fdpMetadata(repositoryUrl); - ResourceDefinition rdRepository = resourceDefinitionFixtures.fdpDefinition(); // Create catalog catalog = fixtures.catalog1(repositoryUrl, getUri(repository)); diff --git a/src/test/java/nl/dtls/fairdatapoint/service/metadata/generic/GenericMetadataServiceTest.java b/src/test/java/nl/dtls/fairdatapoint/service/metadata/generic/GenericMetadataServiceTest.java index cca77994e..8abd2a065 100644 --- a/src/test/java/nl/dtls/fairdatapoint/service/metadata/generic/GenericMetadataServiceTest.java +++ b/src/test/java/nl/dtls/fairdatapoint/service/metadata/generic/GenericMetadataServiceTest.java @@ -22,12 +22,13 @@ */ package nl.dtls.fairdatapoint.service.metadata.generic; -import nl.dtls.fairdatapoint.BaseIntegrationTest; -import nl.dtls.fairdatapoint.database.mongo.migration.development.resource.data.ResourceDefinitionFixtures; +import nl.dtls.fairdatapoint.WebIntegrationTest; +import nl.dtls.fairdatapoint.database.db.repository.ResourceDefinitionRepository; import nl.dtls.fairdatapoint.entity.exception.ResourceNotFoundException; import nl.dtls.fairdatapoint.entity.exception.ValidationException; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; import nl.dtls.fairdatapoint.service.metadata.common.MetadataService; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import nl.dtls.fairdatapoint.utils.AuthHelper; import nl.dtls.fairdatapoint.utils.TestRdfMetadataFixtures; import org.eclipse.rdf4j.model.IRI; @@ -48,7 +49,7 @@ import static org.hamcrest.core.IsEqual.equalTo; import static org.junit.jupiter.api.Assertions.*; -public class GenericMetadataServiceTest extends BaseIntegrationTest { +public class GenericMetadataServiceTest extends WebIntegrationTest { @Autowired private TestRdfMetadataFixtures testMetadataFixtures; @@ -65,7 +66,7 @@ public class GenericMetadataServiceTest extends BaseIntegrationTest { private AuthHelper authHelper; @Autowired - private ResourceDefinitionFixtures resourceDefinitionFixtures; + private ResourceDefinitionRepository resourceDefinitionRepository; @BeforeEach public void before() { @@ -91,7 +92,7 @@ public void retrieveNonExitingMetadataThrowsError() { @Test public void storeWorks() throws Exception { // GIVEN: - ResourceDefinition metadataRd = resourceDefinitionFixtures.distributionDefinition(); + ResourceDefinition metadataRd = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); Model metadata = testMetadataFixtures.c1_d1_distribution1(); // WHEN: @@ -105,7 +106,7 @@ public void storeWorks() throws Exception { @Test public void storeWithNoParentURIThrowsError() { // GIVEN: - ResourceDefinition metadataRd = resourceDefinitionFixtures.distributionDefinition(); + ResourceDefinition metadataRd = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); Model metadata = testMetadataFixtures.c1_d1_distribution1(); setParent(metadata, getUri(metadata), null); @@ -121,8 +122,9 @@ public void storeWithNoParentURIThrowsError() { @Test public void storeWithWrongParentURIThrowsError() { + authHelper.authenticateAsAdmin(); // GIVEN: - ResourceDefinition metadataRd = resourceDefinitionFixtures.distributionDefinition(); + ResourceDefinition metadataRd = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); Model repository = testMetadataFixtures.fdpMetadata(); Model metadata = testMetadataFixtures.c1_d1_distribution1(); setParent(metadata, getUri(metadata), getUri(repository)); @@ -140,7 +142,7 @@ public void storeWithWrongParentURIThrowsError() { @Test public void storeWithNoMetadataIdentifier() throws Exception { // GIVEN: - ResourceDefinition metadataRd = resourceDefinitionFixtures.distributionDefinition(); + ResourceDefinition metadataRd = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); Model metadata = testMetadataFixtures.c1_d1_distribution1(); setMetadataIdentifier(metadata, getUri(metadata), null); @@ -155,7 +157,7 @@ public void storeWithNoMetadataIdentifier() throws Exception { @Test public void storeWithNoLicense() throws Exception { // GIVEN: - ResourceDefinition metadataRd = resourceDefinitionFixtures.distributionDefinition(); + ResourceDefinition metadataRd = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); Model metadata = testMetadataFixtures.c1_d1_distribution1(); setLicence(metadata, getUri(metadata), null); @@ -170,7 +172,7 @@ public void storeWithNoLicense() throws Exception { @Test public void storeWithNoLanguage() throws Exception { // GIVEN: - ResourceDefinition metadataRd = resourceDefinitionFixtures.distributionDefinition(); + ResourceDefinition metadataRd = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); Model metadata = testMetadataFixtures.c1_d1_distribution1(); setLanguage(metadata, getUri(metadata), null); @@ -185,7 +187,7 @@ public void storeWithNoLanguage() throws Exception { @Test public void updateParent() throws Exception { // GIVEN: - ResourceDefinition metadataRd = resourceDefinitionFixtures.distributionDefinition(); + ResourceDefinition metadataRd = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); Model repository = testMetadataFixtures.fdpMetadata(); Model catalog = testMetadataFixtures.catalog1(); Model dataset = testMetadataFixtures.c1_dataset1(); diff --git a/src/test/java/nl/dtls/fairdatapoint/service/metadata/metric/MetricsMetadataServiceTest.java b/src/test/java/nl/dtls/fairdatapoint/service/metadata/metric/MetricsMetadataServiceTest.java index 8e1e5b8fa..bfc7ff258 100644 --- a/src/test/java/nl/dtls/fairdatapoint/service/metadata/metric/MetricsMetadataServiceTest.java +++ b/src/test/java/nl/dtls/fairdatapoint/service/metadata/metric/MetricsMetadataServiceTest.java @@ -28,9 +28,7 @@ package nl.dtls.fairdatapoint.service.metadata.metric; import nl.dtls.fairdatapoint.BaseIntegrationTest; -import nl.dtls.fairdatapoint.database.mongo.repository.SettingsRepository; import nl.dtls.fairdatapoint.entity.metadata.Metric; -import nl.dtls.fairdatapoint.service.settings.SettingsCache; import org.eclipse.rdf4j.model.IRI; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; diff --git a/src/test/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionCacheTest.java b/src/test/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionCacheTest.java index c505bd9b1..07cd6b4f6 100644 --- a/src/test/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionCacheTest.java +++ b/src/test/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionCacheTest.java @@ -23,16 +23,25 @@ package nl.dtls.fairdatapoint.service.resource; import nl.dtls.fairdatapoint.BaseIntegrationTest; -import nl.dtls.fairdatapoint.database.mongo.migration.development.resource.data.ResourceDefinitionFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.ResourceDefinitionRepository; +import nl.dtls.fairdatapoint.Profiles; +import nl.dtls.fairdatapoint.database.db.repository.ResourceDefinitionRepository; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; +import nl.dtls.fairdatapoint.util.KnownUUIDs; +import org.flywaydb.core.Flyway; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; +@ActiveProfiles(Profiles.TESTING) +@SpringBootTest( + webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT, + properties = {"spring.main.allow-bean-definition-overriding=true"}) public class ResourceDefinitionCacheTest extends BaseIntegrationTest { @Autowired @@ -42,16 +51,21 @@ public class ResourceDefinitionCacheTest extends BaseIntegrationTest { private ResourceDefinitionCache resourceDefinitionCache; @Autowired - private ResourceDefinitionFixtures resourceDefinitionFixtures; + protected Flyway flyway; + @BeforeEach + public void setup() { + flyway.clean(); + flyway.migrate(); + } @Test public void computeCacheWorks() { // GIVEN: Resource definitions - ResourceDefinition rdRepository = resourceDefinitionFixtures.fdpDefinition(); - ResourceDefinition rdCatalog = resourceDefinitionFixtures.catalogDefinition(); - ResourceDefinition rdDataset = resourceDefinitionFixtures.datasetDefinition(); - ResourceDefinition rdDistribution = resourceDefinitionFixtures.distributionDefinition(); + ResourceDefinition rdRepository = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_FDP_UUID).get(); + ResourceDefinition rdCatalog = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_CATALOG_UUID).get(); + ResourceDefinition rdDataset = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DATASET_UUID).get(); + ResourceDefinition rdDistribution = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); // WHEN: resourceDefinitionCache.computeCache(); diff --git a/src/test/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionValidatorTest.java b/src/test/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionValidatorTest.java index 18c21bbc3..f70262235 100644 --- a/src/test/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionValidatorTest.java +++ b/src/test/java/nl/dtls/fairdatapoint/service/resource/ResourceDefinitionValidatorTest.java @@ -22,20 +22,27 @@ */ package nl.dtls.fairdatapoint.service.resource; -import nl.dtls.fairdatapoint.database.mongo.migration.development.resource.data.ResourceDefinitionFixtures; -import nl.dtls.fairdatapoint.database.mongo.repository.ResourceDefinitionRepository; +import nl.dtls.fairdatapoint.api.dto.resource.ResourceDefinitionChangeDTO; +import nl.dtls.fairdatapoint.api.dto.resource.ResourceDefinitionChildDTO; +import nl.dtls.fairdatapoint.api.dto.resource.ResourceDefinitionChildListViewDTO; +import nl.dtls.fairdatapoint.database.db.repository.ResourceDefinitionRepository; import nl.dtls.fairdatapoint.entity.exception.ValidationException; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinitionChild; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import org.mockito.junit.jupiter.MockitoSettings; +import org.mockito.quality.Strictness; import org.springframework.validation.BindException; +import java.util.ArrayList; import java.util.List; import java.util.Optional; +import java.util.UUID; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; @@ -45,6 +52,7 @@ import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) +@MockitoSettings(strictness = Strictness.LENIENT) public class ResourceDefinitionValidatorTest { @Mock @@ -56,21 +64,53 @@ public class ResourceDefinitionValidatorTest { @InjectMocks private ResourceDefinitionValidator resourceDefinitionValidator; - @InjectMocks - private ResourceDefinitionFixtures resourceDefinitionFixtures; + private ResourceDefinition newResourceDefinition(UUID uuid, String name, String urlPrefix) { + return ResourceDefinition.builder() + .uuid(uuid) + .name(name) + .urlPrefix(urlPrefix) + .children(new ArrayList<>()) + .parents(new ArrayList<>()) + .externalLinks(List.of()) + .metadataSchemaUsages(List.of()) + .build(); + } + + private ResourceDefinitionChild newChild( + UUID uuid, ResourceDefinition source, ResourceDefinition target, + String relationUri + ) { + return ResourceDefinitionChild.builder() + .uuid(uuid) + .source(source) + .target(target) + .relationUri(relationUri) + .title("") + .tagsUri("") + .metadata(List.of()) + .orderPriority(1) + .build(); + } @Test public void nameUniqueness() throws BindException { // GIVEN: Prepare reqDto - ResourceDefinition reqDto = resourceDefinitionFixtures.fdpDefinition(); - reqDto.setChildren(List.of()); + ResourceDefinition rdCatalog = newResourceDefinition(KnownUUIDs.RD_CATALOG_UUID, "Catalog", "catalog"); + ResourceDefinitionChangeDTO reqDto = + ResourceDefinitionChangeDTO.builder() + .name("Catalog") + .urlPrefix("catalog2") + .children(List.of()) + .externalLinks(List.of()) + .metadataSchemaUuids(List.of()) + .build(); // AND: Prepare database when(resourceDefinitionRepository.findByName(reqDto.getName())) - .thenReturn(Optional.of(resourceDefinitionFixtures.fdpDefinition())); + .thenReturn(Optional.of(rdCatalog)); // WHEN: - resourceDefinitionValidator.validate(reqDto); + resourceDefinitionValidator.validate(KnownUUIDs.RD_CATALOG_UUID, reqDto); // THEN: // Nothing to check @@ -79,16 +119,24 @@ public void nameUniqueness() throws BindException { @Test public void nameUniquenessBreach() { // GIVEN: Prepare reqDto - ResourceDefinition reqDto = resourceDefinitionFixtures.ontologyDefinition(); + ResourceDefinition rdCatalog = newResourceDefinition(KnownUUIDs.RD_CATALOG_UUID, "Catalog", "catalog"); + ResourceDefinitionChangeDTO reqDto = + ResourceDefinitionChangeDTO.builder() + .name("Catalog") + .urlPrefix("catalog2") + .children(List.of()) + .externalLinks(List.of()) + .metadataSchemaUuids(List.of()) + .build(); // AND: Prepare database when(resourceDefinitionRepository.findByName(reqDto.getName())) - .thenReturn(Optional.of(resourceDefinitionFixtures.fdpDefinition())); + .thenReturn(Optional.of(rdCatalog)); // WHEN: BindException exception = assertThrows( BindException.class, - () -> resourceDefinitionValidator.validate(reqDto) + () -> resourceDefinitionValidator.validate(KnownUUIDs.NULL_UUID, reqDto) ); // THEN: @@ -98,17 +146,24 @@ public void nameUniquenessBreach() { @Test public void urlPrefixUniqueness() throws BindException { // GIVEN: Prepare reqDto - ResourceDefinition reqDto = resourceDefinitionFixtures.fdpDefinition(); - reqDto.setChildren(List.of()); + ResourceDefinition rdCatalog = newResourceDefinition(KnownUUIDs.RD_CATALOG_UUID, "Catalog", "catalog"); + ResourceDefinitionChangeDTO reqDto = + ResourceDefinitionChangeDTO.builder() + .name("Catalog 2") + .urlPrefix("catalog") + .children(List.of()) + .externalLinks(List.of()) + .metadataSchemaUuids(List.of()) + .build(); // AND: Prepare database when(resourceDefinitionRepository.findByName(reqDto.getName())) .thenReturn(Optional.empty()); when(resourceDefinitionRepository.findByUrlPrefix(reqDto.getUrlPrefix())) - .thenReturn(Optional.of(resourceDefinitionFixtures.fdpDefinition())); + .thenReturn(Optional.of(rdCatalog)); // WHEN: - resourceDefinitionValidator.validate(reqDto); + resourceDefinitionValidator.validate(KnownUUIDs.RD_CATALOG_UUID, reqDto); // THEN: // Nothing to check @@ -117,18 +172,26 @@ public void urlPrefixUniqueness() throws BindException { @Test public void urlPrefixUniquenessBreach() { // GIVEN: Prepare reqDto - ResourceDefinition reqDto = resourceDefinitionFixtures.ontologyDefinition(); + ResourceDefinition rdCatalog = newResourceDefinition(KnownUUIDs.RD_CATALOG_UUID, "Catalog", "catalog"); + ResourceDefinitionChangeDTO reqDto = + ResourceDefinitionChangeDTO.builder() + .name("Catalog 2") + .urlPrefix("catalog") + .children(List.of()) + .externalLinks(List.of()) + .metadataSchemaUuids(List.of()) + .build(); // AND: Prepare database when(resourceDefinitionRepository.findByName(reqDto.getName())) .thenReturn(Optional.empty()); when(resourceDefinitionRepository.findByUrlPrefix(reqDto.getUrlPrefix())) - .thenReturn(Optional.of(resourceDefinitionFixtures.fdpDefinition())); + .thenReturn(Optional.of(rdCatalog)); // WHEN: BindException exception = assertThrows( BindException.class, - () -> resourceDefinitionValidator.validate(reqDto) + () -> resourceDefinitionValidator.validate(KnownUUIDs.NULL_UUID, reqDto) ); // THEN: @@ -138,8 +201,25 @@ public void urlPrefixUniquenessBreach() { @Test public void nonExistingChild() { // GIVEN: Prepare reqDto - ResourceDefinition reqDto = resourceDefinitionFixtures.ontologyDefinition(); - ResourceDefinitionChild child = new ResourceDefinitionChild("nonExistingChild", "", null); + ResourceDefinitionChangeDTO reqDto = + ResourceDefinitionChangeDTO.builder() + .name("Catalog 2") + .urlPrefix("catalog2") + .children(List.of()) + .externalLinks(List.of()) + .metadataSchemaUuids(List.of()) + .build(); + ResourceDefinitionChildDTO child = ResourceDefinitionChildDTO.builder() + .resourceDefinitionUuid(KnownUUIDs.NULL_UUID) + .listView( + ResourceDefinitionChildListViewDTO.builder() + .title("") + .metadata(List.of()) + .tagsUri("") + .build() + ) + .relationUri("http://www.w3.org/ns/dcat#record") + .build(); reqDto.setChildren(List.of(child)); // AND: Prepare database @@ -147,13 +227,13 @@ public void nonExistingChild() { .thenReturn(Optional.empty()); when(resourceDefinitionRepository.findByUrlPrefix(reqDto.getUrlPrefix())) .thenReturn(Optional.empty()); - when(resourceDefinitionCache.getByUuid(child.getResourceDefinitionUuid())) + when(resourceDefinitionCache.getByUuid(null)) .thenReturn(null); // WHEN: ValidationException exception = assertThrows( ValidationException.class, - () -> resourceDefinitionValidator.validate(reqDto) + () -> resourceDefinitionValidator.validate(KnownUUIDs.USER_NIKOLA_UUID, reqDto) ); // THEN: @@ -163,27 +243,53 @@ public void nonExistingChild() { @Test public void existingDependencyCycle() { // GIVEN: Prepare reqDto and resource definitions - ResourceDefinition rdRepository = resourceDefinitionFixtures.fdpDefinition(); - ResourceDefinition reqDto = resourceDefinitionFixtures.catalogDefinition(); - ResourceDefinition rdDataset = resourceDefinitionFixtures.datasetDefinition(); - - ResourceDefinitionChild rdDatasetChild = new ResourceDefinitionChild(rdRepository.getUuid(), "", null); - rdDataset.setChildren(List.of(rdDatasetChild)); + ResourceDefinition rdFdp = newResourceDefinition(KnownUUIDs.RD_FDP_UUID, "FDP", ""); + ResourceDefinition rdCatalog = newResourceDefinition(KnownUUIDs.RD_CATALOG_UUID, "Catalog", "catalog"); + ResourceDefinition rdDataset = newResourceDefinition(KnownUUIDs.RD_DATASET_UUID, "Dataset", "dataset"); + ResourceDefinitionChild childFdpCatalog = newChild(KnownUUIDs.RD_CHILD_FDP_CATALOG_UUID, rdFdp, rdCatalog, "https://www.w3.org/ns/dcat#catalog"); + ResourceDefinitionChild childCatalogDataset = newChild(KnownUUIDs.RD_CHILD_CATALOG_DATASET_UUID, rdCatalog, rdDataset, "https://www.w3.org/ns/dcat#record"); + rdFdp.getChildren().add(childFdpCatalog); + rdCatalog.getChildren().add(childCatalogDataset); + rdCatalog.getParents().add(childFdpCatalog); + rdDataset.getParents().add(childCatalogDataset); + + ResourceDefinitionChangeDTO reqDto = + ResourceDefinitionChangeDTO.builder() + .name("Dataset") + .urlPrefix("dataset") + .children(List.of()) + .externalLinks(List.of()) + .metadataSchemaUuids(List.of()) + .build(); + ResourceDefinitionChildDTO childDatasetFdp = ResourceDefinitionChildDTO.builder() + .resourceDefinitionUuid(rdFdp.getUuid()) + .listView( + ResourceDefinitionChildListViewDTO.builder() + .title("") + .metadata(List.of()) + .tagsUri("") + .build() + ) + .relationUri("http://www.w3.org/ns/dcat#record") + .build(); + reqDto.setChildren(List.of(childDatasetFdp)); // AND: Prepare database when(resourceDefinitionRepository.findByName(reqDto.getName())) .thenReturn(Optional.empty()); when(resourceDefinitionRepository.findByUrlPrefix(reqDto.getUrlPrefix())) .thenReturn(Optional.empty()); - when(resourceDefinitionCache.getByUuid(rdRepository.getUuid())) - .thenReturn(rdRepository); + when(resourceDefinitionCache.getByUuid(rdFdp.getUuid())) + .thenReturn(rdFdp); + when(resourceDefinitionCache.getByUuid(rdCatalog.getUuid())) + .thenReturn(rdCatalog); when(resourceDefinitionCache.getByUuid(rdDataset.getUuid())) .thenReturn(rdDataset); // WHEN: ValidationException exception = assertThrows( ValidationException.class, - () -> resourceDefinitionValidator.validate(reqDto) + () -> resourceDefinitionValidator.validate(KnownUUIDs.RD_DATASET_UUID, reqDto) ); // THEN: diff --git a/src/test/java/nl/dtls/fairdatapoint/utils/AuthHelper.java b/src/test/java/nl/dtls/fairdatapoint/utils/AuthHelper.java index bb8fa8c8d..4bc3f85dd 100644 --- a/src/test/java/nl/dtls/fairdatapoint/utils/AuthHelper.java +++ b/src/test/java/nl/dtls/fairdatapoint/utils/AuthHelper.java @@ -22,32 +22,31 @@ */ package nl.dtls.fairdatapoint.utils; -import nl.dtls.fairdatapoint.database.mongo.migration.development.user.data.UserFixtures; -import nl.dtls.fairdatapoint.service.security.MongoAuthenticationService; +import nl.dtls.fairdatapoint.service.security.AuthenticationService; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.stereotype.Service; +import java.util.UUID; + @Service public class AuthHelper { @Autowired - private UserFixtures userFixtures; - - @Autowired - private MongoAuthenticationService mongoAuthenticationService; + private AuthenticationService authenticationService; public void authenticateAsAdmin() { - authenticate(userFixtures.admin().getUuid()); + authenticate(KnownUUIDs.USER_ADMIN_UUID); } public void authenticateAsAlbert() { - authenticate(userFixtures.albert().getUuid()); + authenticate(KnownUUIDs.USER_ALBERT_UUID); } - private void authenticate(String uuid) { - Authentication auth = mongoAuthenticationService.getAuthentication(uuid); + private void authenticate(UUID uuid) { + final Authentication auth = authenticationService.getAuthentication(uuid.toString()); SecurityContextHolder.getContext().setAuthentication(auth); } } diff --git a/src/test/java/nl/dtls/fairdatapoint/utils/TestIndexEntryFixtures.java b/src/test/java/nl/dtls/fairdatapoint/utils/TestIndexEntryFixtures.java index 1a69b3a04..86d9ffa1f 100644 --- a/src/test/java/nl/dtls/fairdatapoint/utils/TestIndexEntryFixtures.java +++ b/src/test/java/nl/dtls/fairdatapoint/utils/TestIndexEntryFixtures.java @@ -26,6 +26,7 @@ import nl.dtls.fairdatapoint.entity.index.entry.IndexEntryPermit; import nl.dtls.fairdatapoint.entity.index.entry.IndexEntryState; +import java.time.Duration; import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; @@ -34,18 +35,18 @@ public class TestIndexEntryFixtures { - private static IndexEntry newIndexEntry(String uuid, String clientUrl, Instant timestamp) { + private static IndexEntry newIndexEntry(UUID uuid, String clientUrl, Instant timestamp) { IndexEntry indexEntry = new IndexEntry(); indexEntry.setUuid(uuid); indexEntry.setClientUrl(clientUrl); - indexEntry.setModificationTime(timestamp); - indexEntry.setRegistrationTime(timestamp); - indexEntry.setState(IndexEntryState.Invalid); + indexEntry.setUpdatedAt(timestamp); + indexEntry.setCreatedAt(timestamp); + indexEntry.setState(IndexEntryState.INVALID); indexEntry.setPermit(IndexEntryPermit.ACCEPTED); return indexEntry; } - private static IndexEntry newIndexEntry(String uuid, String clientUrl, Instant timestamp, + private static IndexEntry newIndexEntry(UUID uuid, String clientUrl, Instant timestamp, IndexEntryPermit permit) { IndexEntry indexEntry = newIndexEntry(uuid, clientUrl, timestamp); indexEntry.setPermit(permit); @@ -53,24 +54,51 @@ private static IndexEntry newIndexEntry(String uuid, String clientUrl, Instant t } public static IndexEntry entryExample() { - return newIndexEntry("7663c0c2-2b9d-4787-968d-d284ff3fc5bd", "http://example.com", Instant.now()); + return newIndexEntry(UUID.fromString("7663c0c2-2b9d-4787-968d-d284ff3fc5bd"), "http://example.com", Instant.now()); + } + + public static List entriesDefault() { + final Instant ref = Instant.now(); + final IndexEntry entryActive1 = newIndexEntry(UUID.fromString("09200532-18b4-4721-86dd-fbfa13ec78c0"), "http://example.com/active1", ref.minus(Duration.ofMinutes(2))); + entryActive1.setState(IndexEntryState.VALID); + entryActive1.setLastRetrievalAt(ref.minus(Duration.ofMinutes(1))); + final IndexEntry entryInactive1 = newIndexEntry(UUID.fromString("09200532-18b4-4721-86dd-fbfa13ec78c1"), "http://example.com/inactive1", ref.minus(Duration.ofDays(20))); + entryInactive1.setState(IndexEntryState.VALID); + entryInactive1.setLastRetrievalAt(ref.minus(Duration.ofDays(20))); + final IndexEntry entryInactive2 = newIndexEntry(UUID.fromString("09200532-18b4-4721-86dd-fbfa13ec78c2"), "http://example.com/inactive2", ref.minus(Duration.ofDays(666))); + entryInactive2.setState(IndexEntryState.VALID); + entryInactive2.setLastRetrievalAt(ref.minus(Duration.ofDays(666))); + final IndexEntry entryUnknown1 = newIndexEntry(UUID.fromString("09200532-18b4-4721-86dd-fbfa13ec78c3"), "http://example.com/unknown1", ref); + entryUnknown1.setState(IndexEntryState.UNKNOWN); + final IndexEntry entryInvalid1 = newIndexEntry(UUID.fromString("09200532-18b4-4721-86dd-fbfa13ec78c4"), "http://example.com/invalid1", ref); + entryInvalid1.setState(IndexEntryState.INVALID); + final IndexEntry entryUnreachable1 = newIndexEntry(UUID.fromString("09200532-18b4-4721-86dd-fbfa13ec78c5"), "http://example.com/unreachable1", ref); + entryUnreachable1.setState(IndexEntryState.UNREACHABLE); + return Arrays.asList( + entryActive1, + entryInactive1, + entryInactive2, + entryUnknown1, + entryInvalid1, + entryUnreachable1 + ); } public static List entriesFew() { - Instant ref = Instant.now(); + final Instant ref = Instant.now(); return Arrays.asList( - newIndexEntry("09200532-18b4-4721-86dd-fbfa13ec78c3", "http://example.com", ref), - newIndexEntry("b6cfa934-dc67-4b88-b8f9-c63448c8272c", "http://test.com", ref.minusSeconds(1)), - newIndexEntry("da9ddfb8-6fdb-41b1-889e-387c8cbafc39", "http://localhost", ref.minusSeconds(2)) + newIndexEntry(UUID.fromString("09200532-18b4-4721-86dd-fbfa13ec78c3"), "http://example.com", ref), + newIndexEntry(UUID.fromString("b6cfa934-dc67-4b88-b8f9-c63448c8272c"), "http://test.com", ref.minusSeconds(1)), + newIndexEntry(UUID.fromString("da9ddfb8-6fdb-41b1-889e-387c8cbafc39"), "http://localhost", ref.minusSeconds(2)) ); } public static List entriesPermits() { Instant ref = Instant.now(); return Arrays.asList( - newIndexEntry("09200532-18b4-4721-86dd-fbfa13ec78c3", "http://example.com/accepted", ref, IndexEntryPermit.ACCEPTED), - newIndexEntry("b6cfa934-dc67-4b88-b8f9-c63448c8272c", "http://example.com/rejected", ref, IndexEntryPermit.REJECTED), - newIndexEntry("da9ddfb8-6fdb-41b1-889e-387c8cbafc39", "http://example.com/pending", ref, IndexEntryPermit.PENDING) + newIndexEntry(UUID.fromString("09200532-18b4-4721-86dd-fbfa13ec78c3"), "http://example.com/accepted", ref, IndexEntryPermit.ACCEPTED), + newIndexEntry(UUID.fromString("b6cfa934-dc67-4b88-b8f9-c63448c8272c"), "http://example.com/rejected", ref, IndexEntryPermit.REJECTED), + newIndexEntry(UUID.fromString("da9ddfb8-6fdb-41b1-889e-387c8cbafc39"), "http://example.com/pending", ref, IndexEntryPermit.PENDING) ); } @@ -79,10 +107,9 @@ public static List entriesN(long n) { Instant ref = Instant.now(); for (int i = 0; i < n; i++) { Instant entryTime = ref.minusSeconds(i); - entries.add(newIndexEntry(UUID.randomUUID().toString(), "http://example" + i + ".com", + entries.add(newIndexEntry(UUID.randomUUID(), "http://example" + i + ".com", entryTime)); } return entries; } - } diff --git a/src/test/java/nl/dtls/fairdatapoint/utils/TestRdfMetadataFixtures.java b/src/test/java/nl/dtls/fairdatapoint/utils/TestRdfMetadataFixtures.java index d2c783911..c666e7789 100644 --- a/src/test/java/nl/dtls/fairdatapoint/utils/TestRdfMetadataFixtures.java +++ b/src/test/java/nl/dtls/fairdatapoint/utils/TestRdfMetadataFixtures.java @@ -22,19 +22,20 @@ */ package nl.dtls.fairdatapoint.utils; -import nl.dtls.fairdatapoint.database.mongo.migration.development.resource.data.ResourceDefinitionFixtures; +import nl.dtls.fairdatapoint.database.db.repository.ResourceDefinitionRepository; import nl.dtls.fairdatapoint.database.rdf.migration.development.metadata.data.RdfMetadataFixtures; import nl.dtls.fairdatapoint.database.rdf.migration.development.metadata.factory.MetadataFactory; import nl.dtls.fairdatapoint.entity.resource.ResourceDefinition; import nl.dtls.fairdatapoint.service.metadata.enhance.MetadataEnhancer; +import nl.dtls.fairdatapoint.util.KnownUUIDs; import org.eclipse.rdf4j.model.Model; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Service; +import org.springframework.stereotype.Component; import static nl.dtls.fairdatapoint.entity.metadata.MetadataGetter.getUri; -@Service +@Component public class TestRdfMetadataFixtures extends RdfMetadataFixtures { public String alternativePersistentUrl = "https://lorentz.fair-dtls.surf-hosted.nl/fdp"; @@ -43,43 +44,42 @@ public class TestRdfMetadataFixtures extends RdfMetadataFixtures { private final MetadataEnhancer metadataEnhancer; - private final ResourceDefinitionFixtures resourceDefinitionFixtures; + @Autowired + private ResourceDefinitionRepository resourceDefinitionRepository; @Autowired public TestRdfMetadataFixtures(MetadataFactory metadataFactory, @Qualifier("persistentUrl") String persistentUrl, - MetadataEnhancer metadataEnhancer, - ResourceDefinitionFixtures resourceDefinitionFixtures) { + MetadataEnhancer metadataEnhancer) { super(metadataFactory); this.persistentUrl = persistentUrl; this.metadataEnhancer = metadataEnhancer; - this.resourceDefinitionFixtures = resourceDefinitionFixtures; } public Model fdpMetadata() { Model metadata = super.fdpMetadata(persistentUrl); - ResourceDefinition rd = resourceDefinitionFixtures.fdpDefinition(); + ResourceDefinition rd = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_FDP_UUID).get(); metadataEnhancer.enhance(metadata, getUri(metadata), rd); return metadata; } public Model catalog1() { Model metadata = super.catalog1(persistentUrl, getUri(fdpMetadata())); - ResourceDefinition rd = resourceDefinitionFixtures.catalogDefinition(); + ResourceDefinition rd = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_CATALOG_UUID).get(); metadataEnhancer.enhance(metadata, getUri(metadata), rd); return metadata; } public Model catalog2() { Model metadata = super.catalog2(persistentUrl, getUri(fdpMetadata())); - ResourceDefinition rd = resourceDefinitionFixtures.catalogDefinition(); + ResourceDefinition rd = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_CATALOG_UUID).get(); metadataEnhancer.enhance(metadata, getUri(metadata), rd); return metadata; } public Model catalog3() { Model metadata = super.catalog3(persistentUrl, getUri(fdpMetadata())); - ResourceDefinition rd = resourceDefinitionFixtures.catalogDefinition(); + ResourceDefinition rd = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_CATALOG_UUID).get(); metadataEnhancer.enhance(metadata, getUri(metadata), rd); return metadata; } @@ -87,49 +87,49 @@ public Model catalog3() { public Model alternative_catalog3() { Model metadata = super.catalog3(alternativePersistentUrl, getUri(super.fdpMetadata(alternativePersistentUrl))); - ResourceDefinition rd = resourceDefinitionFixtures.catalogDefinition(); + ResourceDefinition rd = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_CATALOG_UUID).get(); metadataEnhancer.enhance(metadata, getUri(metadata), rd); return metadata; } public Model c1_dataset1() { Model metadata = super.dataset1(persistentUrl, getUri(catalog1())); - ResourceDefinition rd = resourceDefinitionFixtures.datasetDefinition(); + ResourceDefinition rd = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DATASET_UUID).get(); metadataEnhancer.enhance(metadata, getUri(metadata), rd); return metadata; } public Model c1_dataset2() { Model metadata = super.dataset2(persistentUrl, getUri(catalog1())); - ResourceDefinition rd = resourceDefinitionFixtures.datasetDefinition(); + ResourceDefinition rd = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DATASET_UUID).get(); metadataEnhancer.enhance(metadata, getUri(metadata), rd); return metadata; } public Model c2_dataset3() { Model metadata = super.dataset3(persistentUrl, getUri(catalog2())); - ResourceDefinition rd = resourceDefinitionFixtures.datasetDefinition(); + ResourceDefinition rd = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DATASET_UUID).get(); metadataEnhancer.enhance(metadata, getUri(metadata), rd); return metadata; } public Model c1_d1_distribution1() { Model metadata = super.distribution1(persistentUrl, getUri(c1_dataset1())); - ResourceDefinition rd = resourceDefinitionFixtures.distributionDefinition(); + ResourceDefinition rd = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); metadataEnhancer.enhance(metadata, getUri(metadata), rd); return metadata; } public Model c1_d1_distribution2() { Model metadata = super.distribution2(persistentUrl, getUri(c1_dataset1())); - ResourceDefinition rd = resourceDefinitionFixtures.distributionDefinition(); + ResourceDefinition rd = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); metadataEnhancer.enhance(metadata, getUri(metadata), rd); return metadata; } public Model c1_d2_distribution3() { Model metadata = super.distribution3(persistentUrl, getUri(c1_dataset2())); - ResourceDefinition rd = resourceDefinitionFixtures.distributionDefinition(); + ResourceDefinition rd = resourceDefinitionRepository.findByUuid(KnownUUIDs.RD_DISTRIBUTION_UUID).get(); metadataEnhancer.enhance(metadata, getUri(metadata), rd); return metadata; } diff --git a/src/test/resources/application-testing.yml b/src/test/resources/application-testing.yml index fac55fdcc..5e9440e60 100644 --- a/src/test/resources/application-testing.yml +++ b/src/test/resources/application-testing.yml @@ -6,12 +6,20 @@ instance: server: port: 8088 -spring: - data: - mongodb: - uri: mongodb://localhost:27017/fdp-test - security: jwt: token: - expiration: 9999 + expiration: 1000000 + +spring: + datasource: + url: jdbc:postgresql://${FDP_POSTGRES_HOST:localhost}:${FDP_POSTGRES_PORT:54321}/${FDP_POSTGRES_DB:fdp_test}?preparedStatementCacheQueries=0 + username: ${FDP_POSTGRES_USERNAME:fdp} + password: ${FDP_POSTGRES_PASSWORD:fdp} + flyway: + locations: classpath:test/db/migration,classpath:db/migration + fail-on-missing-locations: true + clean-disabled: false + +ping: + enabled: false diff --git a/src/test/resources/log4j2.local.xml b/src/test/resources/log4j2.local.xml new file mode 100644 index 000000000..3646314be --- /dev/null +++ b/src/test/resources/log4j2.local.xml @@ -0,0 +1,17 @@ + + + + %d %-4relative [%thread] %-5level %logger{35} - %msg%n + + + + + + + + + + + + + diff --git a/src/test/resources/log4j2.xml b/src/test/resources/log4j2.xml index 5f482b7c9..347785fff 100644 --- a/src/test/resources/log4j2.xml +++ b/src/test/resources/log4j2.xml @@ -6,8 +6,8 @@ + - diff --git a/src/test/resources/test/db/migration/V0001.1__dev-data-users.sql b/src/test/resources/test/db/migration/V0001.1__dev-data-users.sql new file mode 100644 index 000000000..77dce5687 --- /dev/null +++ b/src/test/resources/test/db/migration/V0001.1__dev-data-users.sql @@ -0,0 +1,61 @@ +-- +-- The MIT License +-- Copyright © 2017 DTL +-- +-- Permission is hereby granted, free of charge, to any person obtaining a copy +-- of this software and associated documentation files (the "Software"), to deal +-- in the Software without restriction, including without limitation the rights +-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +-- copies of the Software, and to permit persons to whom the Software is +-- furnished to do so, subject to the following conditions: +-- +-- The above copyright notice and this permission notice shall be included in +-- all copies or substantial portions of the Software. +-- +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +-- THE SOFTWARE. +-- + +-- User Accounts +INSERT INTO public.user_account (uuid, first_name, last_name, email, password_hash, user_role, created_at, updated_at) +VALUES ('95589e50-d261-492b-8852-9324e9a66a42', 'Admin', 'von Universe', 'admin@example.com', '$2a$10$L.0OZ8QjV3yLhoCDvU04gu.WP1wGQih41MsBdvtQOshJJntaugBxe', 'ADMIN', NOW(), NOW()); + +INSERT INTO public.user_account (uuid, first_name, last_name, email, password_hash, user_role, created_at, updated_at) +VALUES ('7e64818d-6276-46fb-8bb1-732e6e09f7e9', 'Albert', 'Einstein', 'albert.einstein@example.com', '$2a$10$hZF1abbZ48Tf.3RndC9W6OlDt6gnBoD/2HbzJayTs6be7d.5DbpnW', 'USER', NOW(), NOW()); + +INSERT INTO public.user_account (uuid, first_name, last_name, email, password_hash, user_role, created_at, updated_at) +VALUES ('b5b92c69-5ed9-4054-954d-0121c29b6800', 'Nikola', 'Tesla', 'nikola.tesla@example.com', '$2a$10$tMbZUZg9AbYL514R.hZ0tuzvfZJR5NQhSVeJPTQhNwPf6gv/cvrna', 'USER', NOW(), NOW()); + +INSERT INTO public.user_account (uuid, first_name, last_name, email, password_hash, user_role, created_at, updated_at) +VALUES ('8d1a4c06-bb0e-4d03-a01f-14fa49bbc152', 'Isaac', 'Newton', 'isaac.newton@example.com', '$2a$10$DLkI7NAZDzWVaKG1lVtloeoPNLPoAgDDBqQKQiSAYDZXrf2QKkuHC', 'USER', NOW(), NOW()); + +-- API Keys +INSERT INTO public.api_key (uuid, token, user_account_id, created_at, updated_at) +VALUES ('a1c00673-24c5-4e0a-bdbe-22e961ee7548', 'a274793046e34a219fd0ea6362fcca61a001500b71724f4c973a017031653c20', '7e64818d-6276-46fb-8bb1-732e6e09f7e9', NOW(), NOW()); + +INSERT INTO public.api_key (uuid, token, user_account_id, created_at, updated_at) +VALUES ('62657760-21fe-488c-a0ea-f612a70493da', 'dd5dc3b53b6145cfa9f6c58b72ebad21cd2f860ace62451ba4e3c74a0e63540a', 'b5b92c69-5ed9-4054-954d-0121c29b6800', NOW(), NOW()); + +-- Saved Search Queries +INSERT INTO public.search_saved_query (uuid, name, description, type, var_prefixes, var_graph_pattern, var_ordering, user_account_id, created_at, updated_at) +VALUES ('d31e3da1-2cfa-4b55-a8cb-71d1acf01aef', 'All datasets', 'Quickly query all datasets (DCAT)', 'PUBLIC', + 'PREFIX dcat: ', '?entity rdf:type dcat:Dataset .', 'ASC(?title)', '7e64818d-6276-46fb-8bb1-732e6e09f7e9', + NOW(), NOW()); + +INSERT INTO public.search_saved_query (uuid, name, description, type, var_prefixes, var_graph_pattern, var_ordering, user_account_id, created_at, updated_at) +VALUES ('c7d0b6a0-5b0a-4b0e-9b0a-9b0a9b0a9b0a', 'All distributions', 'Quickly query all distributions (DCAT)', 'INTERNAL', + 'PREFIX dcat: ', '?entity rdf:type dcat:Distribution .', 'ASC(?title)', '7e64818d-6276-46fb-8bb1-732e6e09f7e9', + NOW(), NOW()); + +INSERT INTO public.search_saved_query (uuid, name, description, type, var_prefixes, var_graph_pattern, var_ordering, user_account_id, created_at, updated_at) +VALUES ('97da9119-834e-4687-8321-3df157547178', 'Things with data', 'This is private query of Nikola Tesla!', 'PRIVATE', + 'PREFIX dcat: ', +'?entity ?relationPredicate ?relationObject . +FILTER isLiteral(?relationObject) +FILTER CONTAINS(LCASE(str(?relationObject)), LCASE("data"))', + 'ASC(?title)', '7e64818d-6276-46fb-8bb1-732e6e09f7e9', NOW(), NOW()); diff --git a/src/test/resources/test/db/migration/V0001.2__dev-data-schemas.sql b/src/test/resources/test/db/migration/V0001.2__dev-data-schemas.sql new file mode 100644 index 000000000..b89fb1452 --- /dev/null +++ b/src/test/resources/test/db/migration/V0001.2__dev-data-schemas.sql @@ -0,0 +1,473 @@ +-- +-- The MIT License +-- Copyright © 2017 DTL +-- +-- Permission is hereby granted, free of charge, to any person obtaining a copy +-- of this software and associated documentation files (the "Software"), to deal +-- in the Software without restriction, including without limitation the rights +-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +-- copies of the Software, and to permit persons to whom the Software is +-- furnished to do so, subject to the following conditions: +-- +-- The above copyright notice and this permission notice shall be included in +-- all copies or substantial portions of the Software. +-- +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +-- THE SOFTWARE. +-- + +-- Resource +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('6a668323-3936-4b53-8380-a4fd2ed082ee', NOW(), NOW()); +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('71d77460-f919-4f72-b265-ed26567fe361', + '6a668323-3936-4b53-8380-a4fd2ed082ee', + NULL, + '1.0.0', + 'Resource', + '', + '@prefix : . + @prefix dash: . + @prefix dcat: . + @prefix dct: . + @prefix foaf: . + @prefix sh: . + @prefix xsd: . + + :ResourceShape a sh:NodeShape ; + sh:targetClass dcat:Resource ; + sh:property [ + sh:path dct:title ; + sh:nodeKind sh:Literal ; + sh:minCount 1 ; + sh:maxCount 1 ; + dash:editor dash:TextFieldEditor ; + ], [ + sh:path dct:description ; + sh:nodeKind sh:Literal ; + sh:maxCount 1 ; + dash:editor dash:TextAreaEditor ; + ], [ + sh:path dct:publisher ; + sh:node :AgentShape ; + sh:minCount 1 ; + sh:maxCount 1 ; + dash:editor dash:BlankNodeEditor ; + ], [ + sh:path dcat:version ; + sh:name "version" ; + sh:nodeKind sh:Literal ; + sh:minCount 1 ; + sh:maxCount 1 ; + dash:editor dash:TextFieldEditor ; + dash:viewer dash:LiteralViewer ; + ], [ + sh:path dct:language ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + dash:editor dash:URIEditor ; + dash:viewer dash:LabelViewer ; + ], [ + sh:path dct:license ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + dash:editor dash:URIEditor ; + dash:viewer dash:LabelViewer ; + ], [ + sh:path dct:rights ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + dash:editor dash:URIEditor ; + dash:viewer dash:LabelViewer ; + ] . + + :AgentShape a sh:NodeShape ; + sh:targetClass foaf:Agent ; + sh:property [ + sh:path foaf:name; + sh:nodeKind sh:Literal ; + sh:minCount 1 ; + sh:maxCount 1 ; + dash:editor dash:TextFieldEditor ; + ] . + ', + ARRAY ['http://www.w3.org/ns/dcat#Resource'], + 'INTERNAL', + NULL, + NULL, + 'LATEST', + FALSE, + TRUE, + NULL, + NULL, + NOW(), + NOW()); + +-- Data Service +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('89d94c1b-f6ff-4545-ba9b-120b2d1921d0', NOW(), NOW()); +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('9111d436-fe58-4bd5-97ae-e6f86bc2997a', + '89d94c1b-f6ff-4545-ba9b-120b2d1921d0', + NULL, + '1.0.0', + 'Data Service', + '', + '@prefix : . +@prefix dash: . +@prefix dcat: . +@prefix dct: . +@prefix sh: . +@prefix xsd: . + +:DataServiceShape a sh:NodeShape ; + sh:targetClass dcat:DataService ; + sh:property [ + sh:path dcat:endpointURL ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + ] , [ + sh:path dcat:endpointDescription ; + sh:nodeKind sh:Literal ; + sh:maxCount 1 ; + dash:editor dash:TextAreaEditor ; + dash:viewer dash:LiteralViewer ; +] . +', + ARRAY ['http://www.w3.org/ns/dcat#Resource', 'http://www.w3.org/ns/dcat#DataService'], + 'INTERNAL', + NULL, + NULL, + 'LATEST', + FALSE, + FALSE, + NULL, + NULL, + NOW(), + NOW()); +INSERT INTO metadata_schema_extension (uuid, metadata_schema_version_id, extended_metadata_schema_id, order_priority) +VALUES ('2efc8366-541d-493f-8661-69ad8f72dfa1', '9111d436-fe58-4bd5-97ae-e6f86bc2997a', '6a668323-3936-4b53-8380-a4fd2ed082ee', 0); + +-- Metadata Service +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('6f7a5a76-6185-4bd0-9fe9-62ecc90c9bad', NOW(), NOW()); +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('36b22b70-6203-4dd2-9fb6-b39a776bf467', + '6f7a5a76-6185-4bd0-9fe9-62ecc90c9bad', + NULL, + '1.0.0', + 'Metadata Service', + '', + '@prefix : . +@prefix fdp: . +@prefix sh: . + +:MetadataServiceShape a sh:NodeShape ; + sh:targetClass fdp:MetadataService . +', + ARRAY ['http://www.w3.org/ns/dcat#Resource', 'http://www.w3.org/ns/dcat#DataService', 'https://w3id.org/fdp/fdp-o#MetadataService'], + 'INTERNAL', + NULL, + NULL, + 'LATEST', + FALSE, + FALSE, + NULL, + NULL, + NOW(), + NOW()); +INSERT INTO metadata_schema_extension (uuid, metadata_schema_version_id, extended_metadata_schema_id, order_priority) +VALUES ('8742361b-cd00-4167-b859-e45fa36d0cb7', '36b22b70-6203-4dd2-9fb6-b39a776bf467', '89d94c1b-f6ff-4545-ba9b-120b2d1921d0', 0); + +-- FAIR Data Point +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('a92958ab-a414-47e6-8e17-68ba96ba3a2b', NOW(), NOW()); +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('4e64208d-f102-45a0-96e3-17b002e6213e', + 'a92958ab-a414-47e6-8e17-68ba96ba3a2b', + NULL, + '1.0.0', + 'FAIR Data Point', + '', + '@prefix : . +@prefix dash: . +@prefix dct: . +@prefix fdp: . +@prefix sh: . +@prefix xsd: . + +:FDPShape a sh:NodeShape ; + sh:targetClass fdp:FAIRDataPoint ; + sh:property [ + sh:path fdp:startDate ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:editor dash:DatePickerEditor ; + dash:viewer dash:LiteralViewer ; + ] , [ + sh:path fdp:endDate ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:editor dash:DatePickerEditor ; + dash:viewer dash:LiteralViewer ; + ] , [ + sh:path fdp:uiLanguage ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + sh:defaultValue ; + dash:editor dash:URIEditor ; + dash:viewer dash:LabelViewer ; + ] , [ + sh:path fdp:metadataIdentifier ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + dash:editor dash:URIEditor ; + dash:viewer dash:LabelViewer ; + ] , [ + sh:path fdp:metadataIssued ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:editor dash:DatePickerEditor ; + dash:viewer dash:LiteralViewer ; + ] , [ + sh:path fdp:metadataModified ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:editor dash:DatePickerEditor ; + dash:viewer dash:LiteralViewer ; + ] . + ', + ARRAY ['http://www.w3.org/ns/dcat#Resource', 'http://www.w3.org/ns/dcat#DataService', 'https://w3id.org/fdp/fdp-o#MetadataService', 'https://w3id.org/fdp/fdp-o#FAIRDataPoint'], + 'INTERNAL', + NULL, + NULL, + 'LATEST', + FALSE, + FALSE, + NULL, + NULL, + NOW(), + NOW()); +INSERT INTO metadata_schema_extension (uuid, metadata_schema_version_id, extended_metadata_schema_id, order_priority) +VALUES ('afebd441-8aa5-464d-bc3c-033f175449b4', '4e64208d-f102-45a0-96e3-17b002e6213e', '6f7a5a76-6185-4bd0-9fe9-62ecc90c9bad', 0); + +-- Catalog +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('2aa7ba63-d27a-4c0e-bfa6-3a4e250f4660', NOW(), NOW()); +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('c9640671-945d-4114-88fb-e81314cb7ab2', + '2aa7ba63-d27a-4c0e-bfa6-3a4e250f4660', + NULL, + '1.0.0', + 'Catalog', + '', + '@prefix : . +@prefix dash: . +@prefix dcat: . +@prefix dct: . +@prefix foaf: . +@prefix sh: . +@prefix xsd: . + +:CatalogShape a sh:NodeShape ; + sh:targetClass dcat:Catalog ; + sh:property [ + sh:path dct:issued ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:viewer dash:LiteralViewer ; + ], [ + sh:path dct:modified ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:viewer dash:LiteralViewer ; + ], [ + sh:path foaf:homePage ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + dash:editor dash:URIEditor ; + dash:viewer dash:LabelViewer ; + ], [ + sh:path dcat:themeTaxonomy ; + sh:nodeKind sh:IRI ; + dash:viewer dash:LabelViewer ; + ] . +', + ARRAY ['http://www.w3.org/ns/dcat#Resource', 'http://www.w3.org/ns/dcat#Catalog'], + 'INTERNAL', + NULL, + NULL, + 'LATEST', + FALSE, + FALSE, + NULL, + NULL, + NOW(), + NOW()); +INSERT INTO metadata_schema_extension (uuid, metadata_schema_version_id, extended_metadata_schema_id, order_priority) +VALUES ('e75cb601-318d-41ea-9a8b-32e0749c80a7', 'c9640671-945d-4114-88fb-e81314cb7ab2', '6a668323-3936-4b53-8380-a4fd2ed082ee', 0); + +-- Dataset +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('866d7fb8-5982-4215-9c7c-18d0ed1bd5f3', NOW(), NOW()); +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('9cc3c89a-76cf-4639-a71f-652627af51db', + '866d7fb8-5982-4215-9c7c-18d0ed1bd5f3', + NULL, + '1.0.0', + 'Dataset', + '', + '@prefix : . +@prefix dash: . +@prefix dcat: . +@prefix dct: . +@prefix sh: . +@prefix xsd: . + +:DatasetShape a sh:NodeShape ; + sh:targetClass dcat:Dataset ; + sh:property [ + sh:path dct:issued ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:editor dash:DatePickerEditor ; + dash:viewer dash:LiteralViewer ; + ], [ + sh:path dct:modified ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:editor dash:DatePickerEditor ; + dash:viewer dash:LiteralViewer ; + ], [ + sh:path dcat:theme ; + sh:nodeKind sh:IRI ; + sh:minCount 1 ; + dash:editor dash:URIEditor ; + dash:viewer dash:LabelViewer ; + ], [ + sh:path dcat:contactPoint ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + dash:editor dash:URIEditor ; + dash:viewer dash:LabelViewer ; + ], [ + sh:path dcat:keyword ; + sh:nodeKind sh:Literal ; + dash:editor dash:TextFieldEditor ; + dash:viewer dash:LiteralViewer ; + ], [ + sh:path dcat:landingPage ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + dash:editor dash:URIEditor ; + dash:viewer dash:LabelViewer ; + ] . +', + ARRAY ['http://www.w3.org/ns/dcat#Resource', 'http://www.w3.org/ns/dcat#Dataset'], + 'INTERNAL', + NULL, + NULL, + 'LATEST', + FALSE, + FALSE, + NULL, + NULL, + NOW(), + NOW()); +INSERT INTO metadata_schema_extension (uuid, metadata_schema_version_id, extended_metadata_schema_id, order_priority) +VALUES ('da13ba37-09f8-4937-9055-e3ee3aefc57c', '9cc3c89a-76cf-4639-a71f-652627af51db', '6a668323-3936-4b53-8380-a4fd2ed082ee', 0); + +-- Distribution +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('ebacbf83-cd4f-4113-8738-d73c0735b0ab', NOW(), NOW()); +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('3cda8cd3-b08b-4797-822d-d3f3e83c466a', + 'ebacbf83-cd4f-4113-8738-d73c0735b0ab', + NULL, + '1.0.0', + 'Distribution', + '', + '@prefix : . +@prefix dash: . +@prefix dcat: . +@prefix dct: . +@prefix sh: . +@prefix xsd: . + +:DistributionShape a sh:NodeShape ; + sh:targetClass dcat:Distribution ; + sh:property [ + sh:path dct:issued ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:editor dash:DatePickerEditor ; + dash:viewer dash:LiteralViewer ; + ] , [ + sh:path dct:modified ; + sh:datatype xsd:dateTime ; + sh:maxCount 1 ; + dash:editor dash:DatePickerEditor ; + dash:viewer dash:LiteralViewer ; + ] , [ + sh:path dcat:accessURL ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + dash:editor dash:URIEditor ; + ] , [ + sh:path dcat:downloadURL ; + sh:nodeKind sh:IRI ; + sh:maxCount 1 ; + dash:editor dash:URIEditor ; + ] , [ + sh:path dcat:mediaType ; + sh:nodeKind sh:Literal ; + sh:minCount 1 ; + sh:maxCount 1 ; + dash:editor dash:TextFieldEditor ; + dash:viewer dash:LiteralViewer ; + ] , [ + sh:path dcat:format ; + sh:nodeKind sh:Literal ; + sh:maxCount 1 ; + dash:editor dash:TextFieldEditor ; + dash:viewer dash:LiteralViewer ; + ] , [ + sh:path dcat:byteSize ; + sh:nodeKind sh:Literal ; + sh:maxCount 1 ; + dash:editor dash:TextFieldEditor ; + dash:viewer dash:LiteralViewer ; + ] . +', + ARRAY ['http://www.w3.org/ns/dcat#Resource', 'http://www.w3.org/ns/dcat#Distribution'], + 'INTERNAL', + NULL, + NULL, + 'LATEST', + FALSE, + FALSE, + NULL, + NULL, + NOW(), + NOW()); +INSERT INTO metadata_schema_extension (uuid, metadata_schema_version_id, extended_metadata_schema_id, order_priority) +VALUES ('a3b16a4e-cac7-4b71-a3de-94bb86714b5b', '3cda8cd3-b08b-4797-822d-d3f3e83c466a', '6a668323-3936-4b53-8380-a4fd2ed082ee', 0); diff --git a/src/test/resources/test/db/migration/V0001.3__dev-data-rds.sql b/src/test/resources/test/db/migration/V0001.3__dev-data-rds.sql new file mode 100644 index 000000000..29eb20aeb --- /dev/null +++ b/src/test/resources/test/db/migration/V0001.3__dev-data-rds.sql @@ -0,0 +1,68 @@ +-- +-- The MIT License +-- Copyright © 2017 DTL +-- +-- Permission is hereby granted, free of charge, to any person obtaining a copy +-- of this software and associated documentation files (the "Software"), to deal +-- in the Software without restriction, including without limitation the rights +-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +-- copies of the Software, and to permit persons to whom the Software is +-- furnished to do so, subject to the following conditions: +-- +-- The above copyright notice and this permission notice shall be included in +-- all copies or substantial portions of the Software. +-- +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +-- THE SOFTWARE. +-- + +-- Distribution +INSERT INTO resource_definition (uuid, name, url_prefix, created_at, updated_at) +VALUES ('02c649de-c579-43bb-b470-306abdc808c7', 'Distribution', 'distribution', now(), now()); + +INSERT INTO resource_definition_link (uuid, resource_definition_id, title, property_uri, order_priority, created_at, updated_at) +VALUES ('660a1821-a5d2-48d0-a26b-0c6d5bac3de4', '02c649de-c579-43bb-b470-306abdc808c7', 'Access online', 'http://www.w3.org/ns/dcat#accessURL', 1, now(), now()); + +INSERT INTO resource_definition_link (uuid, resource_definition_id, title, property_uri, order_priority, created_at, updated_at) +VALUES ('c2eaebb8-4d8d-469d-8736-269adeded996', '02c649de-c579-43bb-b470-306abdc808c7', 'Download', 'http://www.w3.org/ns/dcat#downloadURL', 2, now(), now()); + +INSERT INTO metadata_schema_usage (uuid, resource_definition_id, metadata_schema_id, order_priority) +VALUES ('bbf4ecb3-c529-4c02-955c-7160755debf5', '02c649de-c579-43bb-b470-306abdc808c7', 'ebacbf83-cd4f-4113-8738-d73c0735b0ab', 1); + +-- Dataset +INSERT INTO resource_definition (uuid, name, url_prefix, created_at, updated_at) +VALUES ('2f08228e-1789-40f8-84cd-28e3288c3604', 'Dataset', 'dataset', now(), now()); + +INSERT INTO resource_definition_child (uuid, source_resource_definition_id, target_resource_definition_id, relation_uri, title, tags_uri, order_priority, created_at, updated_at) +VALUES ('9f138a13-9d45-4371-b763-0a3b9e0ec912', '2f08228e-1789-40f8-84cd-28e3288c3604', '02c649de-c579-43bb-b470-306abdc808c7', 'http://www.w3.org/ns/dcat#distribution', 'Distributions', NULL, 1, now(), now()); + +INSERT INTO resource_definition_child_metadata (uuid, resource_definition_child_id, title, property_uri, order_priority, created_at, updated_at) +VALUES ('723e95d3-1696-45e2-9429-f6e98e3fb893', '9f138a13-9d45-4371-b763-0a3b9e0ec912', 'Media Type', 'http://www.w3.org/ns/dcat#mediaType', 1, now(), now()); + +INSERT INTO metadata_schema_usage (uuid, resource_definition_id, metadata_schema_id, order_priority) +VALUES ('b8a0ed37-42a1-487e-8842-09fe082c4cc6', '2f08228e-1789-40f8-84cd-28e3288c3604', '866d7fb8-5982-4215-9c7c-18d0ed1bd5f3', 1); + +-- Catalog +INSERT INTO resource_definition (uuid, name, url_prefix, created_at, updated_at) +VALUES ('a0949e72-4466-4d53-8900-9436d1049a4b', 'Catalog', 'catalog', now(), now()); + +INSERT INTO resource_definition_child (uuid, source_resource_definition_id, target_resource_definition_id, relation_uri, title, tags_uri, order_priority, created_at, updated_at) +VALUES ('e9f0f5d3-2a93-4aa3-9dd0-acb1d76f54fc', 'a0949e72-4466-4d53-8900-9436d1049a4b', '2f08228e-1789-40f8-84cd-28e3288c3604', 'http://www.w3.org/ns/dcat#dataset', 'Datasets', 'http://www.w3.org/ns/dcat#theme', 1, now(), now()); + +INSERT INTO metadata_schema_usage (uuid, resource_definition_id, metadata_schema_id, order_priority) +VALUES ('e4df9510-a3ad-4e3b-a1a9-5fc330d8b1f0', 'a0949e72-4466-4d53-8900-9436d1049a4b', '2aa7ba63-d27a-4c0e-bfa6-3a4e250f4660', 1); + +-- FAIR Data Point +INSERT INTO resource_definition (uuid, name, url_prefix, created_at, updated_at) +VALUES ('77aaad6a-0136-4c6e-88b9-07ffccd0ee4c', 'FAIR Data Point', '', now(), now()); + +INSERT INTO resource_definition_child (uuid, source_resource_definition_id, target_resource_definition_id, relation_uri, title, tags_uri, order_priority, created_at, updated_at) +VALUES ('b8648597-8fbd-4b89-9e30-5eab82675e42', '77aaad6a-0136-4c6e-88b9-07ffccd0ee4c', 'a0949e72-4466-4d53-8900-9436d1049a4b', 'https://w3id.org/fdp/fdp-o#metadataCatalog', 'Catalogs', 'http://www.w3.org/ns/dcat#themeTaxonomy', 1, now(), now()); + +INSERT INTO metadata_schema_usage (uuid, resource_definition_id, metadata_schema_id, order_priority) +VALUES ('9b3a32a8-a14c-4eb0-ba02-3aa8e13a8f11', '77aaad6a-0136-4c6e-88b9-07ffccd0ee4c', 'a92958ab-a414-47e6-8e17-68ba96ba3a2b', 1); diff --git a/src/test/resources/test/db/migration/V0001.4__dev-data-membership.sql b/src/test/resources/test/db/migration/V0001.4__dev-data-membership.sql new file mode 100644 index 000000000..9e699a971 --- /dev/null +++ b/src/test/resources/test/db/migration/V0001.4__dev-data-membership.sql @@ -0,0 +1,43 @@ +-- +-- The MIT License +-- Copyright © 2017 DTL +-- +-- Permission is hereby granted, free of charge, to any person obtaining a copy +-- of this software and associated documentation files (the "Software"), to deal +-- in the Software without restriction, including without limitation the rights +-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +-- copies of the Software, and to permit persons to whom the Software is +-- furnished to do so, subject to the following conditions: +-- +-- The above copyright notice and this permission notice shall be included in +-- all copies or substantial portions of the Software. +-- +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +-- THE SOFTWARE. +-- + +INSERT INTO membership (uuid, name, allowed_entities, created_at, updated_at) +VALUES ('49f2bcfd-ef0a-4a3a-a1a3-0fc72a6892a8', 'Owner', ARRAY ['a0949e72-4466-4d53-8900-9436d1049a4b', '2f08228e-1789-40f8-84cd-28e3288c3604', '02c649de-c579-43bb-b470-306abdc808c7'], NOW(), NOW()); + +INSERT INTO membership (uuid, name, allowed_entities, created_at, updated_at) +VALUES ('87a2d984-7db2-43f6-805c-6b0040afead5', 'Data Provider', ARRAY ['a0949e72-4466-4d53-8900-9436d1049a4b'], NOW(), NOW()); + +INSERT INTO membership_permission (uuid, membership_id, mask, code, created_at, updated_at) +VALUES ('e0d9f853-637b-4c50-9ad9-07b6349bf76f', '49f2bcfd-ef0a-4a3a-a1a3-0fc72a6892a8', 2, 'W', NOW(), NOW()); + +INSERT INTO membership_permission (uuid, membership_id, mask, code, created_at, updated_at) +VALUES ('de4e4f85-f11d-475b-b6f0-33bdfe5f923a', '49f2bcfd-ef0a-4a3a-a1a3-0fc72a6892a8', 4, 'C', NOW(), NOW()); + +INSERT INTO membership_permission (uuid, membership_id, mask, code, created_at, updated_at) +VALUES ('60bebbf0-210d-4b05-af85-ca1b58546261', '49f2bcfd-ef0a-4a3a-a1a3-0fc72a6892a8', 8, 'D', NOW(), NOW()); + +INSERT INTO membership_permission (uuid, membership_id, mask, code, created_at, updated_at) +VALUES ('36c3b6e9-f2e3-48b7-bae1-4dc3196a3657', '49f2bcfd-ef0a-4a3a-a1a3-0fc72a6892a8', 16, 'A', NOW(), NOW()); + +INSERT INTO membership_permission (uuid, membership_id, mask, code, created_at, updated_at) +VALUES ('589d09d3-1c29-4c6f-97fc-6ea4e007fb85', '87a2d984-7db2-43f6-805c-6b0040afead5', 4, 'C', NOW(), NOW()); diff --git a/src/test/resources/test/db/migration/V0001.5__dev-settings.sql b/src/test/resources/test/db/migration/V0001.5__dev-settings.sql new file mode 100644 index 000000000..f6df63825 --- /dev/null +++ b/src/test/resources/test/db/migration/V0001.5__dev-settings.sql @@ -0,0 +1,73 @@ +-- +-- The MIT License +-- Copyright © 2017 DTL +-- +-- Permission is hereby granted, free of charge, to any person obtaining a copy +-- of this software and associated documentation files (the "Software"), to deal +-- in the Software without restriction, including without limitation the rights +-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +-- copies of the Software, and to permit persons to whom the Software is +-- furnished to do so, subject to the following conditions: +-- +-- The above copyright notice and this permission notice shall be included in +-- all copies or substantial portions of the Software. +-- +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +-- THE SOFTWARE. +-- + +-- Settings +INSERT INTO settings (uuid, app_title, app_subtitle, ping_enabled, ping_endpoints, autocomplete_search_ns, created_at, updated_at) +VALUES ('00000000-0000-0000-0000-000000000000', 'FAIR Data Point', 'FDP Development Instance', False, ARRAY ['https://home.fairdatapoint.org'], True, now(), now()); + +-- Autocomplete Sources +INSERT INTO settings_autocomplete_source (uuid, settings_id, rdf_type, sparql_endpoint, sparql_query, order_priority, created_at, updated_at) +VALUES ('d4045a98-dd25-493e-a0b1-d704921c0930', '00000000-0000-0000-0000-000000000000', 'http://www.w3.org/2000/01/rdf-schema#Class', 'http://localhost:3030/ds/query', +'SELECT DISTINCT ?uri ?label +WHERE { ?uri a . +?uri ?label . +FILTER regex(?label, ".*%s.*", "i") } +ORDER BY ?label', + 1, now(), now()); + +-- Search Filters: Type +INSERT INTO settings_search_filter (uuid, settings_id, type, label, predicate, query_records, order_priority, created_at, updated_at) +VALUES ('57a98728-ce8c-4e7f-b0f8-94e2668b44d3', '00000000-0000-0000-0000-000000000000', 'IRI', 'Type', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type', False, 1, now(), now()); + +INSERT INTO settings_search_filter_item (uuid, filter_id, label, value, order_priority, created_at, updated_at) +VALUES ('b48c2c7f-d7fb-47ae-a72c-b1b360e16f6e', '57a98728-ce8c-4e7f-b0f8-94e2668b44d3', 'Catalog', 'http://www.w3.org/ns/dcat#Catalog', 1, now(), now()); + +INSERT INTO settings_search_filter_item (uuid, filter_id, label, value, order_priority, created_at, updated_at) +VALUES ('3e1598ac-9d29-47f0-8e7b-3c26ca0134a0', '57a98728-ce8c-4e7f-b0f8-94e2668b44d3', 'Dataset', 'http://www.w3.org/ns/dcat#Dataset', 2, now(), now()); + +INSERT INTO settings_search_filter_item (uuid, filter_id, label, value, order_priority, created_at, updated_at) +VALUES ('5697d8d9-f09d-4ebe-b834-b37eb0624c3f', '57a98728-ce8c-4e7f-b0f8-94e2668b44d3', 'Distribution', 'http://www.w3.org/ns/dcat#Distribution', 3, now(), now()); + +INSERT INTO settings_search_filter_item (uuid, filter_id, label, value, order_priority, created_at, updated_at) +VALUES ('022c3bc6-0598-408c-8d2e-b486dafb73dd', '57a98728-ce8c-4e7f-b0f8-94e2668b44d3', 'Data Service', 'http://www.w3.org/ns/dcat#DataService', 4, now(), now()); + +INSERT INTO settings_search_filter_item (uuid, filter_id, label, value, order_priority, created_at, updated_at) +VALUES ('7cee5591-8620-4fea-b883-a94285012b8d', '57a98728-ce8c-4e7f-b0f8-94e2668b44d3', 'Metadata Service', 'https://w3id.org/fdp/fdp-o#MetadataService', 5, now(), now()); + +INSERT INTO settings_search_filter_item (uuid, filter_id, label, value, order_priority, created_at, updated_at) +VALUES ('9d661dca-8017-4dba-b930-cd2834ea59e8', '57a98728-ce8c-4e7f-b0f8-94e2668b44d3', 'FAIR Data Point', 'https://w3id.org/fdp/fdp-o#FAIRDataPoint', 6, now(), now()); + +-- Search Filters: License +INSERT INTO settings_search_filter (uuid, settings_id, type, label, predicate, query_records, order_priority, created_at, updated_at) +VALUES ('26913eb3-67dd-45c9-b8ff-4c97e8162a9b', '00000000-0000-0000-0000-000000000000', 'IRI', 'License', 'http://purl.org/dc/terms/license', True, 2, now(), now()); + +-- Search Filters: License +INSERT INTO settings_search_filter (uuid, settings_id, type, label, predicate, query_records, order_priority, created_at, updated_at) +VALUES ('cb25afb4-6169-42f8-bde5-181c803773a8', '00000000-0000-0000-0000-000000000000', 'IRI', 'Version', 'http://www.w3.org/ns/dcat#version', True, 3, now(), now()); + +-- Metrics +INSERT INTO settings_metric (uuid, settings_id, metric_uri, resource_uri, order_priority, created_at, updated_at) +VALUES ('8435491b-c16c-4457-ae94-e0f4128603d5', '00000000-0000-0000-0000-000000000000', 'https://purl.org/fair-metrics/FM_F1A', 'https://www.ietf.org/rfc/rfc3986.txt', 1, now(), now()); + +INSERT INTO settings_metric (uuid, settings_id, metric_uri, resource_uri, order_priority, created_at, updated_at) +VALUES ('af93d36a-0af0-4054-8c00-2675d460b231', '00000000-0000-0000-0000-000000000000', 'https://purl.org/fair-metrics/FM_A1.1', 'https://www.wikidata.org/wiki/Q8777', 2, now(), now()); diff --git a/src/test/resources/test/db/migration/V0001.6__test-schemas.sql b/src/test/resources/test/db/migration/V0001.6__test-schemas.sql new file mode 100644 index 000000000..ba9e075c5 --- /dev/null +++ b/src/test/resources/test/db/migration/V0001.6__test-schemas.sql @@ -0,0 +1,161 @@ +-- +-- The MIT License +-- Copyright © 2017 DTL +-- +-- Permission is hereby granted, free of charge, to any person obtaining a copy +-- of this software and associated documentation files (the "Software"), to deal +-- in the Software without restriction, including without limitation the rights +-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +-- copies of the Software, and to permit persons to whom the Software is +-- furnished to do so, subject to the following conditions: +-- +-- The above copyright notice and this permission notice shall be included in +-- all copies or substantial portions of the Software. +-- +-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +-- THE SOFTWARE. +-- + +-- Custom with one version +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('e8b34158-3858-45c7-8e3e-d1e671dd9929', NOW(), NOW()); + +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('53619e58-2bb0-4baf-afd8-00c5d01ff8a8', 'e8b34158-3858-45c7-8e3e-d1e671dd9929', NULL, '0.1.0', 'Custom schema', + 'Custom schema V1', + '', ARRAY ['http://www.w3.org/2000/01/rdf-schema#Class'], 'CUSTOM', NULL, NULL, 'LATEST', TRUE, FALSE, NULL, + NULL, NOW(), NOW()); + +-- Custom with one draft +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('bfa79edf-00b7-4a04-b5a6-a5144f1a77b7', NOW(), NOW()); + +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('cb9f6cd7-97af-45d0-b23d-d0aab23607d8', 'bfa79edf-00b7-4a04-b5a6-a5144f1a77b7', NULL, '0.1.0', 'Custom schema', + 'Custom schema V1', + '', ARRAY ['http://www.w3.org/2000/01/rdf-schema#Class'], 'CUSTOM', NULL, NULL, 'DRAFT', FALSE, FALSE, NULL, + NULL, NOW(), NOW()); + + +-- Custom with one version INTERNAL +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('fe98adbb-6a2c-4c7a-b2b2-a72db5140c61', NOW(), NOW()); + +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('f0a4b358-69a3-44e6-9436-c68a56a9f2f2', 'fe98adbb-6a2c-4c7a-b2b2-a72db5140c61', NULL, '0.1.0', 'Custom schema', + 'Custom schema V1', + '', ARRAY ['http://www.w3.org/2000/01/rdf-schema#Class'], 'INTERNAL', NULL, NULL, 'LATEST', TRUE, FALSE, NULL, + NULL, NOW(), NOW()); + +-- Custom with multiple versions +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('978e5c1c-268d-4822-b60b-07d3eccc6896', NOW(), NOW()); + +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('d7acec53-5ac9-4502-9bfa-92d1e9f79a24', '978e5c1c-268d-4822-b60b-07d3eccc6896', NULL, '0.1.0', 'Custom schema', + 'Custom schema V1', + '', ARRAY ['http://www.w3.org/2000/01/rdf-schema#Class'], 'CUSTOM', NULL, NULL, 'LEGACY', FALSE, FALSE, NULL, + NULL, NOW(), NOW()); + +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('67896adc-b431-431d-8296-f0b80d8de412', '978e5c1c-268d-4822-b60b-07d3eccc6896', 'd7acec53-5ac9-4502-9bfa-92d1e9f79a24', '0.2.0', 'Custom schema', + 'Custom schema V2', + '', ARRAY ['http://www.w3.org/2000/01/rdf-schema#Class'], 'CUSTOM', NULL, NULL, 'LEGACY', FALSE, FALSE, NULL, + NULL, NOW(), NOW()); + +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('c62d4a97-baac-40b8-b6ea-e43b06ec78bd', '978e5c1c-268d-4822-b60b-07d3eccc6896', '67896adc-b431-431d-8296-f0b80d8de412', '0.3.0', 'Custom schema', + 'Custom schema V3', + '', ARRAY ['http://www.w3.org/2000/01/rdf-schema#Class'], 'CUSTOM', NULL, NULL, 'LATEST', FALSE, FALSE, NULL, + NULL, NOW(), NOW()); + +-- Custom with draft +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('e7078309-cb4c-47b9-9ef8-057487b3da58', NOW(), NOW()); + +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('a17c25ad-e8d3-4338-bb3e-eda76d2fc32c', 'e7078309-cb4c-47b9-9ef8-057487b3da58', NULL, '0.0.0', 'Custom schema', + 'Custom schema draft', + '', ARRAY ['http://www.w3.org/2000/01/rdf-schema#Class'], 'CUSTOM', NULL, NULL, 'DRAFT', FALSE, FALSE, NULL, + NULL, NOW(), NOW()); + +-- Custom with multiple versions and draft +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('123e48d2-9995-4b44-8b2c-9c81bdbf2dd2', NOW(), NOW()); + +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('fb24f92b-187f-4d53-b744-73024b537f30', '123e48d2-9995-4b44-8b2c-9c81bdbf2dd2', NULL, '0.1.0', 'Custom schema', + 'Custom schema V1', + '', ARRAY ['http://www.w3.org/2000/01/rdf-schema#Class'], 'CUSTOM', NULL, NULL, 'LEGACY', FALSE, FALSE, NULL, + NULL, NOW(), NOW()); + +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('6011adfa-f8da-478d-86ea-84bb644b458b', '123e48d2-9995-4b44-8b2c-9c81bdbf2dd2', 'fb24f92b-187f-4d53-b744-73024b537f30', '0.2.0', 'Custom schema', + 'Custom schema V2', + '', ARRAY ['http://www.w3.org/2000/01/rdf-schema#Class'], 'CUSTOM', NULL, NULL, 'LATEST', FALSE, FALSE, NULL, + NULL, NOW(), NOW()); + +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('6b84ec86-2096-48db-bfc7-23506b8c080c', '123e48d2-9995-4b44-8b2c-9c81bdbf2dd2', '6011adfa-f8da-478d-86ea-84bb644b458b', '0.0.0', 'Custom schema', + 'Custom schema draft', + '', ARRAY ['http://www.w3.org/2000/01/rdf-schema#Class'], 'CUSTOM', NULL, NULL, 'DRAFT', FALSE, FALSE, NULL, + NULL, NOW(), NOW()); + +-- Custom with multiple versions and draft and extends +INSERT INTO metadata_schema (uuid, created_at, updated_at) +VALUES ('7c8b8699-ca9f-4d14-86e2-2299b27c5711', NOW(), NOW()); + +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('4e44fb19-b9e0-46e9-957a-e7aa3adac7bf', '7c8b8699-ca9f-4d14-86e2-2299b27c5711', NULL, '0.1.0', 'Custom schema', + 'Custom schema V1', + '', ARRAY ['http://www.w3.org/2000/01/rdf-schema#Class'], 'CUSTOM', NULL, NULL, 'LEGACY', FALSE, FALSE, NULL, + NULL, NOW(), NOW()); + +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('abcf3a21-6f9a-45dc-a71a-4dde4440c81a', '7c8b8699-ca9f-4d14-86e2-2299b27c5711', '4e44fb19-b9e0-46e9-957a-e7aa3adac7bf', '0.2.0', 'Custom schema', + 'Custom schema V2', + '', ARRAY ['http://www.w3.org/2000/01/rdf-schema#Class'], 'CUSTOM', NULL, NULL, 'LATEST', FALSE, FALSE, NULL, + NULL, NOW(), NOW()); +INSERT INTO metadata_schema_extension (uuid, metadata_schema_version_id, extended_metadata_schema_id, order_priority) +VALUES ('1bdca611-c96e-4304-b1f3-030d282ef529', 'abcf3a21-6f9a-45dc-a71a-4dde4440c81a', '6a668323-3936-4b53-8380-a4fd2ed082ee', 0); +INSERT INTO metadata_schema_extension (uuid, metadata_schema_version_id, extended_metadata_schema_id, order_priority) +VALUES ('1bdca611-c96e-4304-b1f3-030d282ef530', 'abcf3a21-6f9a-45dc-a71a-4dde4440c81a', '123e48d2-9995-4b44-8b2c-9c81bdbf2dd2', 1); + +INSERT INTO metadata_schema_version (uuid, metadata_schema_id, previous_version_id, version, name, description, + definition, target_classes, type, origin, imported_from, state, published, + abstract, suggested_resource_name, suggested_url_prefix, created_at, updated_at) +VALUES ('a6d609ff-905f-4edd-bdb1-2dce000c9a45', '7c8b8699-ca9f-4d14-86e2-2299b27c5711', 'abcf3a21-6f9a-45dc-a71a-4dde4440c81a', '0.0.0', 'Custom schema', + 'Custom schema draft', + '', ARRAY ['http://www.w3.org/2000/01/rdf-schema#Class'], 'CUSTOM', NULL, NULL, 'DRAFT', FALSE, FALSE, NULL, + NULL, NOW(), NOW()); +INSERT INTO metadata_schema_extension (uuid, metadata_schema_version_id, extended_metadata_schema_id, order_priority) +VALUES ('53e3db46-8fe4-47ce-873e-ed7db94e73b3', 'a6d609ff-905f-4edd-bdb1-2dce000c9a45', '6a668323-3936-4b53-8380-a4fd2ed082ee', 0);