From 75f594ec189952f4108968ec7e9a1882df14d998 Mon Sep 17 00:00:00 2001 From: Gabriel Roldan Date: Wed, 23 Oct 2024 11:59:42 -0300 Subject: [PATCH 1/2] Switch to spotless maven plugin with palantir formatting --- .github/workflows/pull-request.yaml | 6 +++-- .gitignore | 2 ++ Makefile | 22 +++++++++++++--- pom.xml | 41 ++++++++++++++++++----------- 4 files changed, 49 insertions(+), 22 deletions(-) diff --git a/.github/workflows/pull-request.yaml b/.github/workflows/pull-request.yaml index 86b422239..da9b98e4d 100644 --- a/.github/workflows/pull-request.yaml +++ b/.github/workflows/pull-request.yaml @@ -38,9 +38,11 @@ jobs: java-version: '21' cache: 'maven' + - name: Validate pom formatting + run: make lint-pom + - name: Validate source code formatting - run: | - make lint + run: make lint-java - name: Test run: | diff --git a/.gitignore b/.gitignore index 6305175bd..16027c07f 100644 --- a/.gitignore +++ b/.gitignore @@ -43,3 +43,5 @@ docker-compose_datadir* .env.yjp hs_err_pid*.log + +.spotless-index diff --git a/Makefile b/Makefile index e507a40a3..1cc7e5b7e 100644 --- a/Makefile +++ b/Makefile @@ -13,12 +13,26 @@ clean: ./mvnw clean .PHONY: lint -lint: - ./mvnw fmt:check sortpom:verify -Dsort.verifyFailOn=strict -Dsort.verifyFail=stop -ntp -T1C +lint: lint-pom lint-java + +.PHONY: lint-pom +lint-pom: + ./mvnw sortpom:verify -Dsort.verifyFailOn=strict -Dsort.verifyFail=stop -ntp -T1C + +.PHONY: lint-java +lint-java: + ./mvnw spotless:check -ntp -T1C .PHONY: format -format: - ./mvnw sortpom:sort fmt:format -ntp -T1C +format: format-pom format-java + +.PHONY: format-pom +format-pom: + ./mvnw sortpom:sort -ntp -T1C + +.PHONY: format-java +format-java: + ./mvnw spotless:apply -ntp -T1C .PHONY: install install: diff --git a/pom.xml b/pom.xml index 1af25852a..962ed20fa 100644 --- a/pom.xml +++ b/pom.xml @@ -12,8 +12,11 @@ 1.9-SNAPSHOT - format false + apply + ${fmt.skip} + sort + ${fmt.skip} UTF-8 https://sonarcloud.io @@ -215,9 +218,9 @@ - com.spotify.fmt - fmt-maven-plugin - 2.21.1 + com.diffplug.spotless + spotless-maven-plugin + 2.43.0 com.github.ekryd.sortpom @@ -242,37 +245,43 @@ sortpom-maven-plugin UTF-8 + true + false false \n - 2 stop strict - ${fmt.skip} + ${pom.fmt.skip} - sort - sort + ${pom.fmt.action} - validate + verify - com.spotify.fmt - fmt-maven-plugin + com.diffplug.spotless + spotless-maven-plugin - false - .*\.java - ${fmt.skip} - + + + 2.50.0 + + + + true + ${project.basedir}/.spotless-index + - ${fmt.action} + ${spotless.action} + validate From fdc2dcc335e40c1564d7d598a77f208902753729 Mon Sep 17 00:00:00 2001 From: Gabriel Roldan Date: Fri, 29 Nov 2024 13:30:26 -0300 Subject: [PATCH 2/2] Apply palantir java formatting run `make format` at the root directory. --- .../cloud/gwc/app/GeoWebCacheApplication.java | 3 +- .../GeoWebCacheApplicationConfiguration.java | 27 +- .../gwc/app/GeoWebCacheApplicationTest.java | 10 +- .../restconfig/RestConfigApplication.java | 3 +- .../RestConfigApplicationConfiguration.java | 24 +- .../restconfig/RestConfigApplicationTest.java | 6 +- .../geoserver/cloud/wcs/WCSController.java | 18 +- .../cloud/wcs/WcsApplicationTest.java | 33 +- .../CloudNativeUIAutoConfiguration.java | 4 +- .../core/AbstractWebUIAutoConfiguration.java | 3 +- .../web/core/WebCoreConfiguration.java | 3 +- .../web/core/WebUIContextInitializer.java | 8 +- .../web/core/WebUIInitializer.java | 5 +- .../web/demo/LayerPreviewConfiguration.java | 9 +- .../ReprojectionConsoleConfiguration.java | 3 +- .../demo/WcsRequestBuilderConfiguration.java | 3 +- .../demo/WpsRequestBuilderConfiguration.java | 3 +- .../ExtensionsAutoConfiguration.java | 3 +- .../web/security/SecurityConfiguration.java | 18 +- .../ReprojectionConsoleConfiguration.java | 3 +- .../cloud/web/service/ServiceInstance.java | 3 +- .../web/service/ServiceInstanceRegistry.java | 11 +- ...GeoServerCloudHomePageContentProvider.java | 1 - .../cloud/web/ui/ServiceProvider.java | 6 +- .../cloud/web/app/AclIntegrationTest.java | 7 +- .../cloud/web/app/WebUIApplicationTest.java | 12 +- .../cloud/wfs/app/WFSController.java | 21 +- .../app/WfsApplicationDataDirectoryIT.java | 7 +- .../wfs/app/WfsApplicationPgconfigIT.java | 7 +- .../cloud/wfs/app/WfsApplicationTest.java | 19 +- .../wms/KMLAutoConfiguration.java | 9 +- .../wms/WmsApplicationAutoConfiguration.java | 9 +- .../controller/GetMapReflectorController.java | 9 +- .../cloud/wms/controller/WMSController.java | 24 +- .../controller/kml/KMLIconsController.java | 11 +- .../kml/KMLReflectorController.java | 9 +- .../app/WmsApplicationDataDirectoryTest.java | 13 +- .../cloud/wms/app/WmsApplicationTest.java | 4 +- .../geoserver/cloud/wps/WPSController.java | 18 +- .../cloud/wps/WpsApplicationTest.java | 17 +- .../SpringBootAdminServerApplication.java | 1 - .../cloud/config/ConfigApplicationTest.java | 10 +- .../GatewaySharedAuthAutoConfiguration.java | 4 +- .../cloud/gateway/filter/GlobalUriFilter.java | 7 +- .../RouteProfileGatewayFilterFactory.java | 15 +- .../StripBasePathGatewayFilterFactory.java | 8 +- .../RegExpQueryRoutePredicateFactory.java | 20 +- ...GatewaySharedAuthenticationPostFilter.java | 52 +- .../GatewaySharedAuthenticationPreFilter.java | 90 ++-- .../SharedAuthConfigurationProperties.java | 1 - ...tewayApplicationAutoconfigurationTest.java | 18 +- ...atewaySharedAuthAutoConfigurationTest.java | 30 +- .../GatewaySharedAuthenticationTest.java | 94 ++-- .../GeoServerBackendAutoConfiguration.java | 3 +- .../core/LifecycleEventAutoConfiguration.java | 3 +- ...streamServiceLoadersAutoConfiguration.java | 1 - .../GeoToolsHttpClientAutoConfiguration.java | 24 +- ...ttpClientProxyConfigurationProperties.java | 17 +- .../GeoToolsStaticContextInitializer.java | 15 +- ...ingEnvironmentAwareGeoToolsHttpClient.java | 95 ++-- ...ronmentAwareGeoToolsHttpClientFactory.java | 4 +- .../metrics/catalog/CatalogMetrics.java | 30 +- .../CatalogMetricsAutoConfiguration.java | 5 +- .../ConditionalOnGeoServerMetricsEnabled.java | 8 +- .../GeoSeverMetricsConfigProperties.java | 1 - .../catalog/MetricsCatalogListener.java | 43 +- ...onditionalOnGeoServerSecurityDisabled.java | 9 +- ...ConditionalOnGeoServerSecurityEnabled.java | 9 +- .../GeoServerSecurityAutoConfiguration.java | 9 +- .../backend/core/CatalogProperties.java | 1 - .../core/CoreBackendConfiguration.java | 23 +- .../lifecycle/LifecycleEventProcessor.java | 1 - .../RemoteEventResourcePoolProcessor.java | 18 +- .../CloudGeoServerSecurityManager.java | 32 +- ...nvironmentAdminAuthenticationProvider.java | 18 +- .../GeoServerSecurityConfiguration.java | 17 +- .../GsCloudLayerGroupContainmentCache.java | 41 +- .../LifecycleEventAutoConfigurationTest.java | 17 +- ...rcePoolCleanupUpAutoConfigurationTest.java | 21 +- ...oToolsHttpClientAutoConfigurationTest.java | 53 +- ...onmentAdminAuthenticationProviderTest.java | 185 +++---- ...eoServerSecurityAutoConfigurationTest.java | 50 +- ...GsCloudLayerGroupContainmentCacheTest.java | 67 +-- .../ConditionalOnDataDirectoryEnabled.java | 3 +- .../datadir/EventualConsistencyEnforcer.java | 84 ++- .../EventuallyConsistentCatalogFacade.java | 34 +- .../DataDirectoryBackendConfiguration.java | 25 +- .../DataDirectoryGeoServerLoader.java | 12 +- .../DataDirectoryLoaderSupport.java | 48 +- .../DataDirectoryProperties.java | 9 +- .../DataDirectoryUpdateSequence.java | 25 +- ...vletContextDataDirectoryResourceStore.java | 15 +- .../NoServletContextFileLockProvider.java | 7 +- .../ParallelDataDirectoryGeoServerLoader.java | 41 +- .../RemoteEventDataDirectoryProcessor.java | 37 +- .../DataDirectoryAutoConfigurationTest.java | 160 +++--- ...EventuallyConsistentCatalogFacadeTest.java | 3 +- ...RemoteEventDataDirectoryProcessorTest.java | 19 +- .../ConditionalOnJdbcConfigEnabled.java | 9 +- .../ConditionalOnJdbcConfigWebUIEnabled.java | 5 +- ...emoteEventJdbcConfigAutoConfiguration.java | 3 +- .../jdbcconfig/CloudJdbcConfigDatabase.java | 3 +- .../jdbcconfig/CloudJdbcConfigProperties.java | 16 +- .../jdbcconfig/CloudJdbcGeoServerLoader.java | 11 +- .../jdbcconfig/CloudJdbcGeoserverFacade.java | 24 +- .../jdbcconfig/CloudJdbcStoreProperties.java | 14 +- .../JDBCConfigBackendConfigurer.java | 59 +-- .../JdbcConfigConfigurationProperties.java | 4 +- .../jdbcconfig/JdbcConfigUpdateSequence.java | 19 +- .../RemoteEventJdbcConfigProcessor.java | 24 +- .../JDBCConfigAutoConfigurationTest.java | 6 +- ...onfigAutoConfigurationWebDisabledTest.java | 9 +- ...ConfigAutoConfigurationWebEnabledTest.java | 9 +- .../backend/jdbcconfig/JDBCConfigTest.java | 7 +- .../jdbcconfig/JdbcConfigDataSourceTest.java | 7 +- .../ConditionalOnPgconfigBackendEnabled.java | 3 +- ...igTransactionManagerAutoConfiguration.java | 6 +- .../pgconfig/PgconfigBackendBuilder.java | 4 +- .../catalog/PgconfigCatalogFacade.java | 14 +- .../filter/CatalogInfoLiteralAdaptor.java | 17 +- .../filter/PgconfigCatalogFilterSplitter.java | 7 +- .../filter/PgconfigFilterCapabilities.java | 1 - .../catalog/filter/PgconfigFilterToSQL.java | 58 +- .../catalog/filter/PgconfigQueryBuilder.java | 9 +- .../ToPgsqlCompatibleFilterDuplicator.java | 38 +- .../repository/CatalogInfoRowMapper.java | 48 +- .../catalog/repository/LoggingTemplate.java | 117 ++--- .../PgconfigCatalogInfoRepository.java | 88 ++-- .../PgconfigLayerGroupRepository.java | 9 +- .../repository/PgconfigLayerRepository.java | 22 +- .../PgconfigNamespaceRepository.java | 15 +- .../repository/PgconfigObjectMapper.java | 2 - .../PgconfigResourceRepository.java | 21 +- .../repository/PgconfigStoreRepository.java | 16 +- .../repository/PgconfigStyleRepository.java | 12 +- .../PgconfigWorkspaceRepository.java | 4 +- .../config/PgconfigConfigRepository.java | 99 +--- .../config/PgconfigGeoServerFacade.java | 1 - .../config/PgconfigUpdateSequence.java | 16 +- .../FileSystemResourceStoreCache.java | 19 +- .../resource/PgconfigLockProvider.java | 4 +- .../pgconfig/resource/PgconfigResource.java | 20 +- .../resource/PgconfigResourceRowMapper.java | 6 +- .../resource/PgconfigResourceStore.java | 99 ++-- .../DatabaseMigrationConfiguration.java | 18 +- .../pgconfig/GeoServerConfigInitializer.java | 10 +- .../PconfigDataSourceConfiguration.java | 5 +- .../PgconfigBackendConfiguration.java | 16 +- .../pgconfig/PgconfigBackendProperties.java | 1 - .../PgconfigCatalogResourcesSynchronizer.java | 1 - .../pgconfig/PgconfigDatabaseMigrations.java | 4 +- .../pgconfig/PgconfigGeoServerLoader.java | 53 +- .../PgconfigGeoServerResourceLoader.java | 4 +- .../PgconfigBackendAutoConfigurationTest.java | 53 +- ...configDataSourceAutoConfigurationTest.java | 63 +-- ...gconfigMigrationAutoConfigurationTest.java | 113 ++-- ...PgconfigCatalogBackendConformanceTest.java | 23 +- .../PgconfigWorkspaceRepositoryTest.java | 6 +- ...configConfigRepositoryConformanceTest.java | 10 +- .../config/PgconfigUpdateSequenceTest.java | 3 +- .../resource/PgconfigResourceTest.java | 56 +- .../support/PgConfigTestContainer.java | 57 +- .../ConditionalOnBackendCacheEnabled.java | 12 +- .../catalog/cache/CachedReferenceCleaner.java | 48 +- .../catalog/cache/CachingCatalogFacade.java | 30 +- ...achingCatalogFacadeContainmentSupport.java | 26 +- .../cache/CachingFacadesLifeCycleHandler.java | 1 - .../catalog/cache/CachingGeoServerFacade.java | 16 +- .../GeoServerBackendCacheConfiguration.java | 6 +- .../cloud/catalog/cache/InfoIdKey.java | 4 +- .../cloud/catalog/cache/InfoNameKey.java | 12 +- .../cloud/catalog/cache/ServiceInfoKey.java | 3 +- ...ngCatalogFacadeContainmentSupportTest.java | 49 +- .../cache/CachingCatalogFacadeTest.java | 67 +-- .../cache/CachingGeoServerFacadeTest.java | 9 +- ...eoServerBackendCacheConfigurationTest.java | 40 +- ...tionalOnGeoServerRemoteEventsDisabled.java | 9 +- ...itionalOnGeoServerRemoteEventsEnabled.java | 5 +- ...ServerBusIntegrationAutoConfiguration.java | 8 +- .../cloud/event/bus/InfoEventResolver.java | 27 +- .../cloud/event/bus/RemoteGeoServerEvent.java | 11 +- .../event/bus/RemoteGeoServerEventBridge.java | 20 +- .../event/bus/RemoteGeoServerEventMapper.java | 10 +- .../RemoteGeoServerEventsConfiguration.java | 13 +- ...erBusIntegrationAutoConfigurationTest.java | 49 +- .../event/bus/BusAmqpIntegrationTests.java | 49 +- .../cloud/event/bus/BusEventCollector.java | 68 +-- .../bus/CatalogRemoteApplicationEventsIT.java | 147 +++--- .../bus/ConfigRemoteApplicationEventsIT.java | 75 ++- .../LifecycleRemoteApplicationEventsIT.java | 30 +- ...emoteGeoServerEventsConfigurationTest.java | 33 +- .../event/ConditionalOnCatalogEvents.java | 8 +- .../event/UpdateSequenceController.java | 4 +- .../CatalogApplicationEventPublisher.java | 54 +- ...CatalogApplicationEventsConfiguration.java | 8 +- .../GeoServerLifecycleEventPublisher.java | 4 +- .../geoserver/cloud/event/GeoServerEvent.java | 18 +- .../cloud/event/UpdateSequenceEvent.java | 10 +- .../cloud/event/catalog/CatalogInfoAdded.java | 8 +- .../event/catalog/CatalogInfoModified.java | 24 +- .../event/catalog/CatalogInfoRemoved.java | 7 +- .../event/catalog/DefaultDataStoreSet.java | 28 +- .../event/catalog/DefaultNamespaceSet.java | 8 +- .../event/catalog/DefaultWorkspaceSet.java | 5 +- .../cloud/event/config/ConfigInfoAdded.java | 11 +- .../event/config/ConfigInfoModified.java | 5 +- .../cloud/event/config/ConfigInfoRemoved.java | 10 +- .../event/config/GeoServerInfoModified.java | 8 +- .../cloud/event/config/GeoServerInfoSet.java | 1 - .../event/config/LoggingInfoModified.java | 5 +- .../cloud/event/config/LoggingInfoSet.java | 1 - .../cloud/event/config/ServiceAdded.java | 2 - .../cloud/event/config/ServiceModified.java | 13 +- .../cloud/event/config/ServiceRemoved.java | 5 +- .../cloud/event/config/SettingsAdded.java | 2 - .../cloud/event/config/SettingsModified.java | 7 +- .../cloud/event/config/SettingsRemoved.java | 5 +- .../cloud/event/info/ConfigInfoType.java | 1 - .../geoserver/cloud/event/info/InfoAdded.java | 2 - .../geoserver/cloud/event/info/InfoEvent.java | 8 +- .../cloud/event/info/InfoModified.java | 9 +- .../cloud/event/info/InfoRemoved.java | 7 +- .../cloud/event/lifecycle/LifecycleEvent.java | 6 +- .../event/security/SecurityConfigChanged.java | 2 - ...logApplicationEventsConfigurationTest.java | 50 +- .../catalog/CatalogInfoDeserializer.java | 4 +- .../catalog/CatalogInfoSerializer.java | 13 +- .../catalog/GeoServerCatalogModule.java | 81 +-- .../databind/catalog/dto/AttributeType.java | 3 +- .../databind/catalog/dto/CatalogInfoDto.java | 4 +- .../databind/catalog/dto/Coverage.java | 6 +- .../catalog/dto/CoverageDimension.java | 4 +- .../databind/catalog/dto/CoverageStore.java | 1 - .../databind/catalog/dto/DataStore.java | 1 - .../databind/catalog/dto/Dimension.java | 4 +- .../databind/catalog/dto/FeatureType.java | 4 +- .../databind/catalog/dto/GridGeometryDto.java | 1 - .../databind/catalog/dto/HTTPStore.java | 6 +- .../jackson/databind/catalog/dto/InfoDto.java | 7 +- .../databind/catalog/dto/InfoReference.java | 1 - .../jackson/databind/catalog/dto/Layer.java | 4 +- .../databind/catalog/dto/LayerGroup.java | 7 +- .../databind/catalog/dto/LayerGroupStyle.java | 3 +- .../jackson/databind/catalog/dto/Map.java | 4 +- .../databind/catalog/dto/MetadataMapDto.java | 4 +- .../databind/catalog/dto/Namespace.java | 1 - .../databind/catalog/dto/PatchDto.java | 7 +- .../databind/catalog/dto/Published.java | 9 +- .../databind/catalog/dto/QueryDto.java | 6 +- .../databind/catalog/dto/Resource.java | 7 +- .../jackson/databind/catalog/dto/Store.java | 6 +- .../jackson/databind/catalog/dto/Style.java | 2 - .../databind/catalog/dto/VirtualTableDto.java | 1 - .../databind/catalog/dto/WMSLayer.java | 4 +- .../databind/catalog/dto/WMSStore.java | 1 - .../databind/catalog/dto/WMTSLayer.java | 1 - .../databind/catalog/dto/WMTSStore.java | 1 - .../databind/catalog/dto/Workspace.java | 1 - .../catalog/mapper/CatalogInfoMapper.java | 1 - .../mapper/GeoServerValueObjectsMapper.java | 41 +- .../databind/catalog/mapper/MapMapper.java | 1 - .../catalog/mapper/NamespaceMapper.java | 1 - .../catalog/mapper/ObjectFacotries.java | 33 +- .../catalog/mapper/PublishedMapper.java | 1 - .../catalog/mapper/ResourceMapper.java | 1 - .../databind/catalog/mapper/StoreMapper.java | 1 - .../databind/catalog/mapper/StyleMapper.java | 1 - .../catalog/mapper/WorkspaceMapper.java | 1 - .../config/ConfigInfoDeserializer.java | 7 +- .../databind/config/ConfigInfoSerializer.java | 3 +- .../config/GeoServerConfigModule.java | 36 +- .../databind/config/dto/CogSettingsDto.java | 1 - .../config/dto/CogSettingsStoreDto.java | 1 - .../databind/config/dto/ConfigInfoDto.java | 1 - .../jackson/databind/config/dto/Contact.java | 4 +- .../databind/config/dto/CoverageAccess.java | 1 - .../databind/config/dto/GeoServer.java | 2 - .../jackson/databind/config/dto/JaiDto.java | 4 +- .../jackson/databind/config/dto/Logging.java | 2 - .../jackson/databind/config/dto/Service.java | 13 +- .../jackson/databind/config/dto/Settings.java | 5 +- .../dto/mapper/GeoServerConfigMapper.java | 10 +- .../config/dto/mapper/ObjectFacotries.java | 3 +- .../databind/config/dto/mapper/WPSMapper.java | 1 - .../databind/mapper/InfoReferenceMapper.java | 12 +- .../jackson/databind/mapper/PatchMapper.java | 13 +- .../catalog/GeoServerCatalogModuleTest.java | 116 ++-- .../GeoServerCatalogModule_JsonTest.java | 1 - .../GeoServerCatalogModule_YamlTest.java | 1 - .../catalog/PatchSerializationTest.java | 105 ++-- .../catalog/PatchSerialization_JsonTest.java | 1 - .../catalog/PatchSerialization_YamlTest.java | 1 - .../config/GeoServerConfigModuleTest.java | 15 +- .../GeoSeververConfigModule_JsonTest.java | 1 - .../GeoSeververConfigModule_YamlTest.java | 1 - .../jackson/databind/dto/NumberRangeDto.java | 1 - .../databind/filter/GeoToolsFilterModule.java | 68 +-- .../databind/filter/dto/Expression.java | 8 +- .../jackson/databind/filter/dto/Filter.java | 36 +- .../jackson/databind/filter/dto/Literal.java | 8 +- .../filter/dto/LiteralDeserializer.java | 27 +- .../filter/dto/LiteralSerializer.java | 65 +-- .../filter/mapper/DtoToFilterMapper.java | 63 +-- .../filter/mapper/ExpressionFactory.java | 3 +- .../filter/mapper/ExpressionMapper.java | 114 ++-- .../databind/filter/mapper/FilterMapper.java | 25 +- .../filter/mapper/FilterMapperConfig.java | 7 +- .../filter/mapper/FilterToDtoMapper.java | 7 +- .../filter/mapper/GeoToolsValueMappers.java | 26 +- .../filter/mapper/MappingFilterVisitor.java | 1 - .../geojson/GeoToolsGeoJsonModule.java | 2 - .../geometry/GeometryDeserializer.java | 67 +-- .../geojson/geometry/GeometrySerializer.java | 65 +-- .../databind/util/MapperDeserializer.java | 6 +- .../databind/util/MapperSerializer.java | 13 +- .../databind/util/ObjectMapperUtil.java | 15 +- .../filter/ExpressionRoundtripTest.java | 105 ++-- .../databind/filter/FilterRoundtripTest.java | 96 ++-- .../GeoToolsFilterModuleExpressionsTest.java | 11 +- ...ToolsFilterModuleExpressions_JsonTest.java | 1 - ...ToolsFilterModuleExpressions_YamlTest.java | 1 - .../GeoToolsFilterModuleFiltersTest.java | 5 +- .../GeoToolsFilterModuleFilters_JsonTest.java | 1 - .../GeoToolsFilterModuleFilters_YamlTest.java | 1 - .../dto/ExpressionSerializationTest.java | 4 +- .../filter/dto/FilterSerializationTest.java | 2 - .../geojson/GeoToolsGeoJsonModuleTest.java | 14 +- .../GeoToolsGeoJsonModule_JsonTest.java | 1 - .../GeoToolsGeoJsonModule_YamlTest.java | 1 - ...erverJacksonBindingsAutoConfiguration.java | 1 - ...ToolsJacksonBindingsAutoConfiguration.java | 1 - ...rJacksonBindingsAutoConfigurationTest.java | 30 +- ...sJacksonBindingsAutoConfigurationTest.java | 39 +- .../plugin/CatalogFacadeExtensionAdapter.java | 36 +- .../catalog/plugin/CatalogInfoLookup.java | 170 +++--- .../catalog/plugin/CatalogInfoRepository.java | 21 +- .../CatalogInfoRepositoryHolderImpl.java | 6 +- .../plugin/CatalogInfoTypeRegistry.java | 57 +- .../catalog/plugin/CatalogPlugin.java | 77 ++- .../CatalogPluginStyleResourcePersister.java | 1 - .../plugin/DefaultMemoryCatalogFacade.java | 20 +- .../catalog/plugin/ExtendedCatalogFacade.java | 43 +- .../catalog/plugin/IsolatedCatalogFacade.java | 54 +- .../org/geoserver/catalog/plugin/Patch.java | 33 +- .../catalog/plugin/PropertyDiff.java | 117 ++--- .../org/geoserver/catalog/plugin/Query.java | 27 +- .../plugin/RepositoryCatalogFacade.java | 3 +- .../plugin/RepositoryCatalogFacadeImpl.java | 88 ++-- .../plugin/forwarding/ForwardingCatalog.java | 48 +- .../forwarding/ForwardingCatalogFacade.java | 21 +- .../ForwardingCatalogRepository.java | 9 +- .../ForwardingExtendedCatalogFacade.java | 7 +- .../ForwardingLayerGroupRepository.java | 9 +- .../forwarding/ForwardingLayerRepository.java | 9 +- .../ForwardingNamespaceRepository.java | 8 +- .../ForwardingResourceRepository.java | 12 +- .../forwarding/ForwardingStoreRepository.java | 13 +- .../forwarding/ForwardingStyleRepository.java | 9 +- .../ForwardingWorkspaceRepository.java | 6 +- .../ResolvingCatalogFacadeDecorator.java | 38 +- .../plugin/locking/ConfigInfoType.java | 1 - ...ockProviderGeoServerConfigurationLock.java | 4 +- .../plugin/locking/LockingCatalog.java | 33 +- .../plugin/locking/LockingGeoServer.java | 28 +- .../plugin/locking/LockingSupport.java | 16 +- .../resolving/CatalogPropertyResolver.java | 10 +- .../CollectionPropertiesInitializer.java | 6 +- .../resolving/ModificationProxyDecorator.java | 4 +- .../catalog/plugin/resolving/ProxyUtils.java | 62 +-- .../resolving/ResolvingCatalogFacade.java | 6 +- .../ResolvingCatalogInfoRepository.java | 3 +- .../plugin/resolving/ResolvingFacade.java | 5 +- .../resolving/ResolvingFacadeSupport.java | 1 - .../resolving/ResolvingProxyResolver.java | 68 +-- .../plugin/rules/CatalogBusinessRules.java | 19 +- .../plugin/rules/CatalogOpContext.java | 18 +- .../rules/DefaultNamespaceInfoRules.java | 9 +- .../plugin/rules/DefaultStoreInfoRules.java | 6 +- .../plugin/rules/DefaultStyleInfoRules.java | 52 +- .../rules/DefaultWorkspaceInfoRules.java | 6 +- .../validation/BeforeRemoveValidator.java | 65 +-- .../validation/CatalogValidationRules.java | 14 +- .../validation/CatalogValidatorVisitor.java | 1 - .../validation/DefaultCatalogValidator.java | 83 ++- .../DefaultPropertyValuesResolver.java | 5 +- .../config/plugin/ConfigRepository.java | 8 +- .../config/plugin/GeoServerImpl.java | 97 +--- .../config/plugin/MemoryConfigRepository.java | 37 +- .../plugin/RepositoryGeoServerFacadeImpl.java | 44 +- .../forwarding/ForwardingGeoServerFacade.java | 12 +- .../config/DefaultUpdateSequence.java | 27 +- .../geoserver/catalog/CatalogTestData.java | 83 +-- .../geoserver/catalog/faker/CatalogFaker.java | 69 +-- .../plugin/AbstractCatalogVisitorTest.java | 23 +- .../plugin/CatalogConformanceTest.java | 496 ++++++------------ .../CatalogFacadeExtensionAdapterTest.java | 20 +- .../plugin/CatalogPluginConformanceTest.java | 3 +- .../plugin/NamespaceInfoLookupTest.java | 3 +- .../catalog/plugin/PropertyDiffTest.java | 151 +++--- .../catalog/plugin/XmlCatalogInfoLookup.java | 184 +++---- .../XmlCatalogInfoLookupConformanceTest.java | 16 +- ...roviderGeoServerConfigurationLockTest.java | 46 +- .../LockingCatalogDataDirectoryTest.java | 6 +- .../plugin/locking/LockingCatalogTest.java | 78 ++- .../ApplicationEventCapturingListener.java | 10 +- .../GeoServerConfigConformanceTest.java | 27 +- .../impl/CatalogImplConformanceTest.java | 3 +- .../plugin/XmlSerializedConfigRepository.java | 28 +- .../config/UpdateSequenceConformanceTest.java | 3 +- .../ConditionalOnAzureBlobstoreEnabled.java | 11 +- ...ditionalOnDirectWMSIntegrationEnabled.java | 5 +- .../gwc/ConditionalOnDiskQuotaEnabled.java | 9 +- .../ConditionalOnGeoServerWebUIEnabled.java | 7 +- .../gwc/ConditionalOnGeoWebCacheEnabled.java | 9 +- ...itionalOnGeoWebCacheRestConfigEnabled.java | 7 +- .../gwc/ConditionalOnS3BlobstoreEnabled.java | 11 +- .../ConditionalOnWMTSIntegrationEnabled.java | 5 +- .../gwc/ConditionalOnWebUIEnabled.java | 5 +- .../GoServerWebUIConfigurationProperties.java | 1 - ...aultTileLayerCatalogAutoConfiguration.java | 4 +- .../gwc/backend/PgconfigGwcInitializer.java | 1 - ...nfigTileLayerCatalogAutoConfiguration.java | 19 +- .../AzureBlobstoreAutoConfiguration.java | 4 +- .../S3BlobstoreAutoConfiguration.java | 4 +- ...SeedingWebMapServiceAutoConfiguration.java | 4 +- ...GeoServerIntegrationAutoConfiguration.java | 4 +- .../GeoWebCacheCoreAutoConfiguration.java | 4 +- ...WebCacheRemoteEventsAutoConfiguration.java | 4 +- .../WMSIntegrationAutoConfiguration.java | 25 +- .../WMTSIntegrationAutoConfiguration.java | 4 +- .../service/GoogleMapsAutoConfiguration.java | 4 +- .../gwc/service/KMLAutoConfiguration.java | 4 +- .../gwc/service/MGMapsAutoConfiguration.java | 4 +- .../service/RESTConfigAutoConfiguration.java | 4 +- .../TileMapServiceAutoConfiguration.java | 4 +- .../WebMapServiceAutoConfiguration.java | 4 +- .../WebMapTileServiceAutoConfiguration.java | 4 +- .../CloudGWCServiceDescriptionProvider.java | 15 +- .../gwc/GeoServerWebUIAutoConfiguration.java | 4 +- .../gwc/GeoWebCacheUIAutoConfiguration.java | 4 +- .../gwc/GeoWebCacheContextRunner.java | 18 +- .../backend/GwcCoreAutoConfigurationTest.java | 94 ++-- ...TileLayerCatalogAutoConfigurationTest.java | 136 ++--- .../AzureBlobstoreAutoConfigurationTest.java | 59 +-- .../S3BlobstoreAutoConfigurationTest.java | 56 +- .../core/GwcCoreAutoConfigurationTest.java | 111 ++-- .../WMSIntegrationAutoConfigurationTest.java | 89 ++-- .../RESTConfigAutoConfigurationTest.java | 47 +- .../CachingTileLayerInfoRepository.java | 27 +- .../GeoServerTileLayerInfoMapper.java | 7 +- .../pgconfig/ParameterFilterMapper.java | 1 - .../pgconfig/PgconfigTileLayerCatalog.java | 35 +- .../PgconfigTileLayerInfoRepository.java | 36 +- .../PgconfigTileLayerInfoRowMapper.java | 12 +- .../gwc/backend/pgconfig/TileLayerInfo.java | 14 +- .../pgconfig/TileLayerInfoRepository.java | 3 +- .../GeoServerTileLayerInfoMapperTest.java | 26 +- .../pgconfig/PgconfigTileLayerCatalogIT.java | 49 +- .../PgconfigTileLayerCatalogTest.java | 36 +- .../backend/pgconfig/TileLayerMocking.java | 16 +- .../config/blobstore/AzureBlobStoreTest.java | 19 +- .../AzureBlobStoreXmlConfigurationTest.java | 22 +- .../config/blobstore/AzuriteContainer.java | 1 - .../DefaultTileLayerCatalogConfiguration.java | 9 +- .../config/core/DiskQuotaConfiguration.java | 7 +- .../GeoServerIntegrationConfiguration.java | 8 +- .../GeoWebCacheConfigurationProperties.java | 4 +- .../core/GeoWebCacheCoreConfiguration.java | 62 +-- ...ebMapServiceCacheSeedingConfiguration.java | 6 +- .../WebMapServiceMinimalConfiguration.java | 6 +- .../cloud/gwc/event/BlobStoreEvent.java | 3 +- .../cloud/gwc/event/GeoWebCacheEvent.java | 8 +- .../cloud/gwc/event/TileLayerEvent.java | 25 +- .../repository/CachingTileLayerCatalog.java | 23 +- .../repository/CloudCatalogConfiguration.java | 20 +- .../repository/CloudDefaultStorageFinder.java | 16 +- .../repository/CloudGwcXmlConfiguration.java | 36 +- .../repository/CloudXMLResourceProvider.java | 43 +- .../ForwardingTileLayerCatalog.java | 6 +- .../ForwardingTileLayerConfiguration.java | 6 +- .../GeoServerTileLayerConfiguration.java | 12 +- .../ResourceStoreTileLayerCatalog.java | 69 +-- .../gwc/config/AbstractGwcInitializer.java | 85 ++- .../gwc/config/CloudGwcConfigPersister.java | 23 +- .../gwc/config/DefaultGwcInitializer.java | 1 - .../CachingTileLayerCatalogTest.java | 72 ++- .../CloudGwcXmlConfigurationTest.java | 28 +- .../ResourceStoreTileLayerCatalogTest.java | 58 +- .../bus/GeoWebCacheRemoteEventsBroker.java | 8 +- .../cloud/gwc/bus/RemoteBlobStoreEvent.java | 5 +- .../gwc/bus/RemoteConfigChangeEvent.java | 1 - .../cloud/gwc/bus/RemoteEventMapper.java | 38 +- .../cloud/gwc/bus/RemoteGeoWebCacheEvent.java | 4 +- .../cloud/gwc/bus/RemoteGridsetEvent.java | 5 +- .../cloud/gwc/bus/RemoteTileLayerEvent.java | 1 - .../GeoWebCacheRemoteEventsConfiguration.java | 7 +- .../gwc/config/services/KMLConfiguration.java | 3 +- .../config/services/MGMapsConfiguration.java | 3 +- .../gwc/web/gmaps/GoogleMapsController.java | 9 +- .../java/org/gwc/web/kml/KMLController.java | 15 +- .../org/gwc/web/mgmaps/MGMapsController.java | 9 +- .../gwc/web/rest/GeoWebCacheController.java | 9 +- .../java/org/gwc/web/tms/TMSController.java | 15 +- .../java/org/gwc/web/wms/WMSController.java | 15 +- .../java/org/gwc/web/wmts/WMTSController.java | 14 +- .../SimpleJNDIStaticContextInitializer.java | 9 +- ...NDIDataSourcesConfigurationProperties.java | 6 +- .../config/jndi/JNDIDatasourceConfig.java | 1 - .../cloud/config/jndi/JNDIInitializer.java | 46 +- .../cloud/jndi/SimpleNameClassPair.java | 3 +- .../cloud/jndi/SimpleNamingContext.java | 33 +- .../jndi/SimpleNamingContextBuilder.java | 7 +- .../jndi/SimpleNamingContextFactory.java | 1 - .../JNDIDataSourceAutoConfigurationTest.java | 24 +- ...impleJNDIStaticContextInitializerTest.java | 40 +- .../jndi/SimpleNamingContextBuilderTest.java | 11 +- .../cloud/jndi/SimpleNamingContextTest.java | 17 +- .../FilteringXmlBeanDefinitionReader.java | 105 ++-- .../FilteringXmlBeanDefinitionReaderTest.java | 36 +- .../GeoNodeOAuth2AutoConfiguration.java | 1 - .../LoggingMDCAutoConfiguration.java | 10 +- .../logging/config/MDCConfigProperties.java | 1 - .../logging/ows/MDCDispatcherCallback.java | 4 +- .../HttpRequestMdcConfigProperties.java | 4 +- .../logging/servlet/HttpRequestMdcFilter.java | 31 +- .../servlet/MDCAuthenticationFilter.java | 17 +- .../logging/servlet/MDCCleaningFilter.java | 9 +- .../SpringEnvironmentMdcConfigProperties.java | 7 +- .../servlet/SpringEnvironmentMdcFilter.java | 31 +- .../LoggingMDCAutoConfigurationTest.java | 67 +-- .../cog/COGAutoConfiguration.java | 7 +- .../cog/COGWebUIAutoConfiguration.java | 8 +- .../PostgisRasterWebUIAutoConfiguration.java | 6 +- .../cog/COGAutoConfigurationTest.java | 49 +- ...stgisRasterWebUIAutoConfigurationTest.java | 43 +- .../authzn/AuthKeyAutoConfiguration.java | 20 +- .../authzn/ConditionalOnAuthKeyEnabled.java | 11 +- ...onditionalOnGatewaySharedAuthDisabled.java | 5 +- ...ConditionalOnGatewaySharedAuthEnabled.java | 5 +- ...wayPreAuthenticationAutoConfiguration.java | 5 +- .../GatewaySharedAuthConfigProperties.java | 1 - ...SharedAuthenticationAutoConfiguration.java | 10 +- .../authzn/PrioritizableLoginFormInfo.java | 1 - .../jdbc/JDBCSecurityAutoConfiguration.java | 5 +- .../jdbc/JDBCSecurityConfigProperties.java | 1 - .../JDBCSecurityWebUIAutoConfiguration.java | 5 +- .../ldap/LDAPSecurityAutoConfiguration.java | 5 +- .../ldap/LDAPSecurityConfigProperties.java | 1 - .../LDAPSecurityWebUIAutoConfiguration.java | 5 +- .../GatewayPreAuthenticationFilter.java | 19 +- .../GatewayPreAuthenticationProvider.java | 3 +- .../GatewaySharedAuthenticationFilter.java | 44 +- ...atewaySharedAuthenticationInitializer.java | 49 +- .../GatewaySharedAuthenticationProvider.java | 6 +- .../sharedauth/ServerConfiguration.java | 3 +- .../authzn/AuthKeyAutoConfigurationTest.java | 72 +-- .../JDBCSecurityAutoConfigurationTest.java | 32 +- ...DBCSecurityWebUIAutoConfigurationTest.java | 60 +-- .../LDAPSecurityAutoConfigurationTest.java | 32 +- ...DAPSecurityWebUIAutoConfigurationTest.java | 60 +-- ...itOnApplicationEventAutoConfiguration.java | 4 +- .../app/ServiceIdFilterAutoConfiguration.java | 19 +- .../geoserver/cloud/app/StartupLogger.java | 1 - .../ServiceIdFilterAutoConfigurationTest.java | 45 +- .../context/GeoServerContextInitializer.java | 30 +- ...ServerServletContextAutoConfiguration.java | 13 +- .../GeoServerMainModuleConfiguration.java | 6 +- .../GeoServerServletContextConfiguration.java | 3 +- .../servlet/GeoServerServletInitializer.java | 1 - .../VirtualServiceVerifier.java | 11 +- .../ServletContextConditionalFiltersTest.java | 7 +- .../ServletContextDisabledSmokeTest.java | 32 +- .../ServletContextEnabledSmokeTest.java | 4 +- .../extensions/CssStylingConfiguration.java | 13 +- .../MapBoxStylingConfiguration.java | 16 +- .../extensions/VectorTilesConfiguration.java | 21 +- .../WmsExtensionsAutoConfiguration.java | 11 +- .../WmsExtensionsConfigProperties.java | 4 +- .../CssStylingConfigurationTest.java | 38 +- .../MapBoxStylingConfigurationTest.java | 25 +- .../VectorTilesConfigurationTest.java | 64 +-- 581 files changed, 4637 insertions(+), 8089 deletions(-) diff --git a/src/apps/geoserver/gwc/src/main/java/org/geoserver/cloud/gwc/app/GeoWebCacheApplication.java b/src/apps/geoserver/gwc/src/main/java/org/geoserver/cloud/gwc/app/GeoWebCacheApplication.java index 33356ceab..0196993a5 100644 --- a/src/apps/geoserver/gwc/src/main/java/org/geoserver/cloud/gwc/app/GeoWebCacheApplication.java +++ b/src/apps/geoserver/gwc/src/main/java/org/geoserver/cloud/gwc/app/GeoWebCacheApplication.java @@ -18,8 +18,7 @@ public static void main(String[] args) { SpringApplication.run(GeoWebCacheApplication.class, args); } catch (RuntimeException e) { try { - LoggerFactory.getLogger(GeoWebCacheApplication.class) - .error("Application run failed", e); + LoggerFactory.getLogger(GeoWebCacheApplication.class).error("Application run failed", e); } finally { System.exit(-1); } diff --git a/src/apps/geoserver/gwc/src/main/java/org/geoserver/cloud/gwc/app/GeoWebCacheApplicationConfiguration.java b/src/apps/geoserver/gwc/src/main/java/org/geoserver/cloud/gwc/app/GeoWebCacheApplicationConfiguration.java index 00900ec44..32af418dc 100644 --- a/src/apps/geoserver/gwc/src/main/java/org/geoserver/cloud/gwc/app/GeoWebCacheApplicationConfiguration.java +++ b/src/apps/geoserver/gwc/src/main/java/org/geoserver/cloud/gwc/app/GeoWebCacheApplicationConfiguration.java @@ -4,6 +4,14 @@ */ package org.geoserver.cloud.gwc.app; +import java.io.IOException; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; import org.geoserver.catalog.Catalog; import org.geoserver.cloud.gwc.config.core.WebMapServiceMinimalConfiguration; import org.geoserver.gwc.layer.GeoServerTileLayer; @@ -22,16 +30,6 @@ import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import org.springframework.web.servlet.resource.ResourceUrlProvider; -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; - @Configuration public class GeoWebCacheApplicationConfiguration extends RestConfiguration { @@ -44,8 +42,7 @@ public class GeoWebCacheApplicationConfiguration extends RestConfiguration { */ @Bean @ConditionalOnMissingBean - LegendSample legendSample( - @Qualifier("rawCatalog") Catalog catalog, GeoServerResourceLoader loader) { + LegendSample legendSample(@Qualifier("rawCatalog") Catalog catalog, GeoServerResourceLoader loader) { return new LegendSampleImpl(catalog, loader); } @@ -64,14 +61,12 @@ public void configureContentNegotiation(ContentNegotiationConfigurer configurer) @Bean @Override public RequestMappingHandlerMapping requestMappingHandlerMapping( - @Qualifier("mvcContentNegotiationManager") - ContentNegotiationManager contentNegotiationManager, + @Qualifier("mvcContentNegotiationManager") ContentNegotiationManager contentNegotiationManager, @Qualifier("mvcConversionService") FormattingConversionService conversionService, @Qualifier("mvcResourceUrlProvider") ResourceUrlProvider resourceUrlProvider) { RequestMappingHandlerMapping handlerMapping = - super.requestMappingHandlerMapping( - contentNegotiationManager, conversionService, resourceUrlProvider); + super.requestMappingHandlerMapping(contentNegotiationManager, conversionService, resourceUrlProvider); handlerMapping.setUseSuffixPatternMatch(true); handlerMapping.setUseRegisteredSuffixPatternMatch(true); diff --git a/src/apps/geoserver/gwc/src/test/java/org/geoserver/cloud/gwc/app/GeoWebCacheApplicationTest.java b/src/apps/geoserver/gwc/src/test/java/org/geoserver/cloud/gwc/app/GeoWebCacheApplicationTest.java index 0039127cd..7fcffb432 100644 --- a/src/apps/geoserver/gwc/src/test/java/org/geoserver/cloud/gwc/app/GeoWebCacheApplicationTest.java +++ b/src/apps/geoserver/gwc/src/test/java/org/geoserver/cloud/gwc/app/GeoWebCacheApplicationTest.java @@ -10,7 +10,6 @@ import com.google.gson.JsonElement; import com.google.gson.JsonParser; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; @@ -26,7 +25,8 @@ @ActiveProfiles("test") class GeoWebCacheApplicationTest { - @Autowired private TestRestTemplate restTemplate; + @Autowired + private TestRestTemplate restTemplate; @BeforeEach void before() { @@ -37,16 +37,14 @@ void before() { @Test void testRESTDefaultContentType() { - ResponseEntity response = - testGetRequestContentType("/gwc/rest/layers", APPLICATION_JSON); + ResponseEntity response = testGetRequestContentType("/gwc/rest/layers", APPLICATION_JSON); JsonElement parsed = JsonParser.parseString(response.getBody()); assertThat(parsed.isJsonArray()).isTrue(); } @Test void testRESTPathExtensionContentNegotiation() { - ResponseEntity response = - testGetRequestContentType("/gwc/rest/layers.json", APPLICATION_JSON); + ResponseEntity response = testGetRequestContentType("/gwc/rest/layers.json", APPLICATION_JSON); JsonElement parsed = JsonParser.parseString(response.getBody()); assertThat(parsed.isJsonArray()).isTrue(); diff --git a/src/apps/geoserver/restconfig/src/main/java/org/geoserver/cloud/restconfig/RestConfigApplication.java b/src/apps/geoserver/restconfig/src/main/java/org/geoserver/cloud/restconfig/RestConfigApplication.java index 921cf39e8..db92c1053 100644 --- a/src/apps/geoserver/restconfig/src/main/java/org/geoserver/cloud/restconfig/RestConfigApplication.java +++ b/src/apps/geoserver/restconfig/src/main/java/org/geoserver/cloud/restconfig/RestConfigApplication.java @@ -18,8 +18,7 @@ public static void main(String[] args) { SpringApplication.run(RestConfigApplication.class, args); } catch (RuntimeException e) { try { - LoggerFactory.getLogger(RestConfigApplication.class) - .error("Application run failed", e); + LoggerFactory.getLogger(RestConfigApplication.class).error("Application run failed", e); } finally { System.exit(-1); } diff --git a/src/apps/geoserver/restconfig/src/main/java/org/geoserver/cloud/restconfig/RestConfigApplicationConfiguration.java b/src/apps/geoserver/restconfig/src/main/java/org/geoserver/cloud/restconfig/RestConfigApplicationConfiguration.java index 4fedbe307..47a396ed0 100644 --- a/src/apps/geoserver/restconfig/src/main/java/org/geoserver/cloud/restconfig/RestConfigApplicationConfiguration.java +++ b/src/apps/geoserver/restconfig/src/main/java/org/geoserver/cloud/restconfig/RestConfigApplicationConfiguration.java @@ -4,6 +4,14 @@ */ package org.geoserver.cloud.restconfig; +import java.io.IOException; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; import org.geoserver.rest.RequestInfo; import org.geoserver.rest.RestConfiguration; import org.geoserver.rest.catalog.AdminRequestCallback; @@ -19,16 +27,6 @@ import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import org.springframework.web.servlet.resource.ResourceUrlProvider; -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; - @Configuration @ComponentScan(basePackageClasses = org.geoserver.rest.AbstractGeoServerController.class) @SuppressWarnings("deprecation") @@ -53,14 +51,12 @@ AdminRequestCallback adminRequestCallback() { @Bean @Override public RequestMappingHandlerMapping requestMappingHandlerMapping( - @Qualifier("mvcContentNegotiationManager") - ContentNegotiationManager contentNegotiationManager, + @Qualifier("mvcContentNegotiationManager") ContentNegotiationManager contentNegotiationManager, @Qualifier("mvcConversionService") FormattingConversionService conversionService, @Qualifier("mvcResourceUrlProvider") ResourceUrlProvider resourceUrlProvider) { RequestMappingHandlerMapping handlerMapping = - super.requestMappingHandlerMapping( - contentNegotiationManager, conversionService, resourceUrlProvider); + super.requestMappingHandlerMapping(contentNegotiationManager, conversionService, resourceUrlProvider); handlerMapping.setUseSuffixPatternMatch(true); handlerMapping.setUseRegisteredSuffixPatternMatch(true); diff --git a/src/apps/geoserver/restconfig/src/test/java/org/geoserver/cloud/restconfig/RestConfigApplicationTest.java b/src/apps/geoserver/restconfig/src/test/java/org/geoserver/cloud/restconfig/RestConfigApplicationTest.java index f9b8c677c..d903821a7 100644 --- a/src/apps/geoserver/restconfig/src/test/java/org/geoserver/cloud/restconfig/RestConfigApplicationTest.java +++ b/src/apps/geoserver/restconfig/src/test/java/org/geoserver/cloud/restconfig/RestConfigApplicationTest.java @@ -25,7 +25,8 @@ @ActiveProfiles("test") class RestConfigApplicationTest { - @Autowired private TestRestTemplate restTemplate; + @Autowired + private TestRestTemplate restTemplate; @BeforeEach void before() { @@ -45,8 +46,7 @@ void testPathExtensionContentNegotiation() { testPathExtensionContentType("/rest/styles/line.json", APPLICATION_JSON); testPathExtensionContentType("/rest/styles/line.xml", APPLICATION_XML); testPathExtensionContentType("/rest/styles/line.html", TEXT_HTML); - testPathExtensionContentType( - "/rest/styles/line.sld", MediaType.valueOf(SLDHandler.MIMETYPE_10)); + testPathExtensionContentType("/rest/styles/line.sld", MediaType.valueOf(SLDHandler.MIMETYPE_10)); testPathExtensionContentType("/rest/workspaces.html", TEXT_HTML); testPathExtensionContentType("/rest/workspaces.xml", APPLICATION_XML); diff --git a/src/apps/geoserver/wcs/src/main/java/org/geoserver/cloud/wcs/WCSController.java b/src/apps/geoserver/wcs/src/main/java/org/geoserver/cloud/wcs/WCSController.java index 1aba1b550..0a0be0b6a 100644 --- a/src/apps/geoserver/wcs/src/main/java/org/geoserver/cloud/wcs/WCSController.java +++ b/src/apps/geoserver/wcs/src/main/java/org/geoserver/cloud/wcs/WCSController.java @@ -4,9 +4,10 @@ */ package org.geoserver.cloud.wcs; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.cloud.virtualservice.VirtualServiceVerifier; import org.geoserver.ows.Dispatcher; import org.springframework.stereotype.Controller; @@ -15,9 +16,6 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.view.RedirectView; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - @RequiredArgsConstructor public @Controller class WCSController { @@ -34,20 +32,17 @@ public RedirectView redirectRootToGetCapabilities() { /** Serve only WCS schemas from classpath (e.g. {@code /schemas/wcs/1.1.1/wcsAll.xsd}) */ @GetMapping(path = "/schemas/wcs/**") - public void getSchema(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void getSchema(HttpServletRequest request, HttpServletResponse response) throws Exception { classPathPublisher.handleRequest(request, response); } @GetMapping(path = {"/wcs", "/ows"}) - public void handleGet(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void handleGet(HttpServletRequest request, HttpServletResponse response) throws Exception { dispatch(request, response); } @PostMapping(path = {"/wcs", "/ows"}) - public void handlePost(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void handlePost(HttpServletRequest request, HttpServletResponse response) throws Exception { dispatch(request, response); } @@ -97,8 +92,7 @@ public void handleVirtualServiceLayerPost( dispatch(request, response); } - private void dispatch(HttpServletRequest request, HttpServletResponse response) - throws Exception { + private void dispatch(HttpServletRequest request, HttpServletResponse response) throws Exception { geoserverDispatcher.handleRequest(request, response); } } diff --git a/src/apps/geoserver/wcs/src/test/java/org/geoserver/cloud/wcs/WcsApplicationTest.java b/src/apps/geoserver/wcs/src/test/java/org/geoserver/cloud/wcs/WcsApplicationTest.java index 656a9568a..6984dd438 100644 --- a/src/apps/geoserver/wcs/src/test/java/org/geoserver/cloud/wcs/WcsApplicationTest.java +++ b/src/apps/geoserver/wcs/src/test/java/org/geoserver/cloud/wcs/WcsApplicationTest.java @@ -6,14 +6,13 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.test.context.ActiveProfiles; -import java.util.stream.Stream; - @SpringBootTest @ActiveProfiles("test") class WcsApplicationTest { @@ -27,18 +26,11 @@ void testWcsCoreBeans() { expectBean("wcsURLMapping", org.geoserver.ows.OWSHandlerMapping.class); expectBean("wcsLocalWorkspaceURLManger", org.geoserver.ows.LocalWorkspaceURLMangler.class); expectBean("cqlKvpParser", org.geoserver.ows.kvp.CQLFilterKvpParser.class); + expectBean("coverageResponseDelegateFactory", org.geoserver.wcs.responses.CoverageResponseDelegateFinder.class); expectBean( - "coverageResponseDelegateFactory", - org.geoserver.wcs.responses.CoverageResponseDelegateFinder.class); - expectBean( - "geotiffCoverageResponseDelegate", - org.geoserver.wcs.responses.GeoTIFFCoverageResponseDelegate.class); - expectBean( - "imgCoverageResponseDelegate", - org.geoserver.wcs.responses.IMGCoverageResponseDelegate.class); - expectBean( - "debugCoverageResponseDelegate", - org.geoserver.wcs.responses.DebugCoverageResponseDelegate.class); + "geotiffCoverageResponseDelegate", org.geoserver.wcs.responses.GeoTIFFCoverageResponseDelegate.class); + expectBean("imgCoverageResponseDelegate", org.geoserver.wcs.responses.IMGCoverageResponseDelegate.class); + expectBean("debugCoverageResponseDelegate", org.geoserver.wcs.responses.DebugCoverageResponseDelegate.class); expectBean("coverageCleaner", org.geoserver.wcs.CoverageCleanerCallback.class); expectBean("wcsResourceVoter", org.geoserver.wcs.WCSResourceVoter.class); expectBean("legacyWcsLoader", org.geoserver.wcs.WCSLoader.class); @@ -47,18 +39,11 @@ void testWcsCoreBeans() { expectBean("wcsURLMapping", org.geoserver.ows.OWSHandlerMapping.class); expectBean("wcsLocalWorkspaceURLManger", org.geoserver.ows.LocalWorkspaceURLMangler.class); expectBean("cqlKvpParser", org.geoserver.ows.kvp.CQLFilterKvpParser.class); + expectBean("coverageResponseDelegateFactory", org.geoserver.wcs.responses.CoverageResponseDelegateFinder.class); expectBean( - "coverageResponseDelegateFactory", - org.geoserver.wcs.responses.CoverageResponseDelegateFinder.class); - expectBean( - "geotiffCoverageResponseDelegate", - org.geoserver.wcs.responses.GeoTIFFCoverageResponseDelegate.class); - expectBean( - "imgCoverageResponseDelegate", - org.geoserver.wcs.responses.IMGCoverageResponseDelegate.class); - expectBean( - "debugCoverageResponseDelegate", - org.geoserver.wcs.responses.DebugCoverageResponseDelegate.class); + "geotiffCoverageResponseDelegate", org.geoserver.wcs.responses.GeoTIFFCoverageResponseDelegate.class); + expectBean("imgCoverageResponseDelegate", org.geoserver.wcs.responses.IMGCoverageResponseDelegate.class); + expectBean("debugCoverageResponseDelegate", org.geoserver.wcs.responses.DebugCoverageResponseDelegate.class); expectBean("coverageCleaner", org.geoserver.wcs.CoverageCleanerCallback.class); expectBean("wcsResourceVoter", org.geoserver.wcs.WCSResourceVoter.class); } diff --git a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/cloudnative/CloudNativeUIAutoConfiguration.java b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/cloudnative/CloudNativeUIAutoConfiguration.java index 2a0e8908b..ab4f0e561 100644 --- a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/cloudnative/CloudNativeUIAutoConfiguration.java +++ b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/cloudnative/CloudNativeUIAutoConfiguration.java @@ -4,14 +4,12 @@ */ package org.geoserver.cloud.autoconfigure.web.cloudnative; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.web.service.WebUiCloudServicesConfiguration; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import javax.annotation.PostConstruct; - /** * @since 1.0 */ diff --git a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/core/AbstractWebUIAutoConfiguration.java b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/core/AbstractWebUIAutoConfiguration.java index efb4d5d27..2b6614ea2 100644 --- a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/core/AbstractWebUIAutoConfiguration.java +++ b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/core/AbstractWebUIAutoConfiguration.java @@ -4,9 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.web.core; -import lombok.extern.slf4j.Slf4j; - import javax.annotation.PostConstruct; +import lombok.extern.slf4j.Slf4j; @Slf4j(topic = "org.geoserver.cloud.autoconfigure.web") public abstract class AbstractWebUIAutoConfiguration { diff --git a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/core/WebCoreConfiguration.java b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/core/WebCoreConfiguration.java index 2c942bb78..6058b10ad 100644 --- a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/core/WebCoreConfiguration.java +++ b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/core/WebCoreConfiguration.java @@ -18,8 +18,7 @@ @ImportResource( // reader = FilteringXmlBeanDefinitionReader.class, // locations = { // - "jar:gs-web-core-.*!/applicationContext.xml#name=" - + WebCoreConfiguration.EXCLUDED_BEANS_PATTERN, // + "jar:gs-web-core-.*!/applicationContext.xml#name=" + WebCoreConfiguration.EXCLUDED_BEANS_PATTERN, // "jar:gs-web-rest-.*!/applicationContext.xml" // }) public class WebCoreConfiguration { diff --git a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/core/WebUIContextInitializer.java b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/core/WebUIContextInitializer.java index 34346ad8c..0278886ba 100644 --- a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/core/WebUIContextInitializer.java +++ b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/core/WebUIContextInitializer.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.autoconfigure.web.core; import lombok.extern.slf4j.Slf4j; - import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.util.StringUtils; @@ -15,8 +14,7 @@ * @since 1.8.2 */ @Slf4j -public class WebUIContextInitializer - implements ApplicationContextInitializer { +public class WebUIContextInitializer implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext applicationContext) { @@ -31,9 +29,7 @@ private void setHomePageSelectionMode() { String systemProp = System.getProperty("GeoServerHomePage.selectionMode"); if (StringUtils.hasText(systemProp)) { - log.info( - "GeoServerHomePage.selectionMode set to '{}' through system property", - systemProp); + log.info("GeoServerHomePage.selectionMode set to '{}' through system property", systemProp); } else { String selectionMode = "TEXT"; log.info("GeoServerHomePage.selectionMode set to '{}' as default value", selectionMode); diff --git a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/core/WebUIInitializer.java b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/core/WebUIInitializer.java index 95b9c8bfd..e235f508b 100644 --- a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/core/WebUIInitializer.java +++ b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/core/WebUIInitializer.java @@ -7,7 +7,6 @@ import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; - import org.geoserver.config.GeoServer; import org.geoserver.config.GeoServerInfo; import org.geoserver.config.GeoServerInfo.WebUIMode; @@ -30,9 +29,7 @@ public void initialize(GeoServer geoServer) throws Exception { geoServer.save(global); } - Boolean hidefs = - environment.getProperty( - "geoserver.web-ui.file-browser.hide-file-system", Boolean.class); + Boolean hidefs = environment.getProperty("geoserver.web-ui.file-browser.hide-file-system", Boolean.class); if (Boolean.TRUE.equals(hidefs)) { log.info("Setting GEOSERVER_FILEBROWSER_HIDEFS=true System Property"); System.setProperty("GEOSERVER_FILEBROWSER_HIDEFS", "true"); diff --git a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/demo/LayerPreviewConfiguration.java b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/demo/LayerPreviewConfiguration.java index 3bff28e92..9590cfb45 100644 --- a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/demo/LayerPreviewConfiguration.java +++ b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/demo/LayerPreviewConfiguration.java @@ -51,8 +51,7 @@ public String getConfigPrefix() { locations = {"jar:gs-web-demo-.*!/applicationContext.xml#name=openLayersPreview"}) public class OpenLayersCommonFormatsConfiguration extends AbstractWebUIAutoConfiguration { - static final String CONFIG_PREFIX = - LayerPreviewConfiguration.COMMON_FORMATS_PREFIX + ".open-layers"; + static final String CONFIG_PREFIX = LayerPreviewConfiguration.COMMON_FORMATS_PREFIX + ".open-layers"; @Override public String getConfigPrefix() { @@ -71,8 +70,7 @@ public String getConfigPrefix() { locations = {"jar:gs-web-demo-.*!/applicationContext.xml#name=gMLPreview"}) public class GmlCommonFormatsConfiguration extends AbstractWebUIAutoConfiguration { - static final String CONFIG_PREFIX = - LayerPreviewConfiguration.COMMON_FORMATS_PREFIX + ".gml"; + static final String CONFIG_PREFIX = LayerPreviewConfiguration.COMMON_FORMATS_PREFIX + ".gml"; @Override public String getConfigPrefix() { @@ -91,8 +89,7 @@ public String getConfigPrefix() { locations = {"jar:gs-web-demo-.*!/applicationContext.xml#name=kMLPreview"}) public class KmlCommonFormatsConfiguration extends AbstractWebUIAutoConfiguration { - static final String CONFIG_PREFIX = - LayerPreviewConfiguration.COMMON_FORMATS_PREFIX + ".kml"; + static final String CONFIG_PREFIX = LayerPreviewConfiguration.COMMON_FORMATS_PREFIX + ".kml"; @Override public String getConfigPrefix() { diff --git a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/demo/ReprojectionConsoleConfiguration.java b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/demo/ReprojectionConsoleConfiguration.java index ae58e622c..f108ba8f5 100644 --- a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/demo/ReprojectionConsoleConfiguration.java +++ b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/demo/ReprojectionConsoleConfiguration.java @@ -23,8 +23,7 @@ locations = {"jar:gs-web-demo-.*!/applicationContext.xml#name=reprojectionConsole"}) public class ReprojectionConsoleConfiguration extends AbstractWebUIAutoConfiguration { - static final String CONFIG_PREFIX = - DemosAutoConfiguration.CONFIG_PREFIX + ".reprojection-console"; + static final String CONFIG_PREFIX = DemosAutoConfiguration.CONFIG_PREFIX + ".reprojection-console"; @Override public String getConfigPrefix() { diff --git a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/demo/WcsRequestBuilderConfiguration.java b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/demo/WcsRequestBuilderConfiguration.java index 0d0c4dde4..588d9506c 100644 --- a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/demo/WcsRequestBuilderConfiguration.java +++ b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/demo/WcsRequestBuilderConfiguration.java @@ -26,8 +26,7 @@ ) public class WcsRequestBuilderConfiguration extends AbstractWebUIAutoConfiguration { - static final String CONFIG_PREFIX = - DemosAutoConfiguration.CONFIG_PREFIX + ".wcs-request-builder"; + static final String CONFIG_PREFIX = DemosAutoConfiguration.CONFIG_PREFIX + ".wcs-request-builder"; @Override public String getConfigPrefix() { diff --git a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/demo/WpsRequestBuilderConfiguration.java b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/demo/WpsRequestBuilderConfiguration.java index d919ef0eb..9dc257c2a 100644 --- a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/demo/WpsRequestBuilderConfiguration.java +++ b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/demo/WpsRequestBuilderConfiguration.java @@ -23,8 +23,7 @@ locations = "jar:gs-web-wps-.*!/applicationContext.xml#name=wpsRequestBuilder") public class WpsRequestBuilderConfiguration extends AbstractWebUIAutoConfiguration { - static final String CONFIG_PREFIX = - DemosAutoConfiguration.CONFIG_PREFIX + ".wps-request-builder"; + static final String CONFIG_PREFIX = DemosAutoConfiguration.CONFIG_PREFIX + ".wps-request-builder"; @Override public String getConfigPrefix() { diff --git a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/extension/ExtensionsAutoConfiguration.java b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/extension/ExtensionsAutoConfiguration.java index ef2bd3dab..d54c41474 100644 --- a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/extension/ExtensionsAutoConfiguration.java +++ b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/extension/ExtensionsAutoConfiguration.java @@ -9,7 +9,6 @@ import org.springframework.context.annotation.Import; @Configuration -@Import({ - ImporterAutoConfiguration.class // +@Import({ImporterAutoConfiguration.class // }) public class ExtensionsAutoConfiguration {} diff --git a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/security/SecurityConfiguration.java b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/security/SecurityConfiguration.java index 94f2c61c2..486c8957c 100644 --- a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/security/SecurityConfiguration.java +++ b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/security/SecurityConfiguration.java @@ -4,9 +4,14 @@ */ package org.geoserver.cloud.autoconfigure.web.security; +import java.io.IOException; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.cloud.config.factory.FilteringXmlBeanDefinitionReader; import org.geoserver.security.filter.GeoServerLogoutFilter; import org.springframework.beans.factory.annotation.Value; @@ -16,14 +21,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; -import java.io.IOException; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; - @Configuration(proxyBeanMethods = true) @ImportResource( // reader = FilteringXmlBeanDefinitionReader.class, // @@ -42,8 +39,7 @@ FilterRegistrationBean configurableLogoutUrlFilterR ConfigurableLogoutUrlFilter filter = new ConfigurableLogoutUrlFilter(logoutUrl); - FilterRegistrationBean registration = - new FilterRegistrationBean<>(); + FilterRegistrationBean registration = new FilterRegistrationBean<>(); registration.setFilter(filter); registration.setOrder(1); return registration; diff --git a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/tools/ReprojectionConsoleConfiguration.java b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/tools/ReprojectionConsoleConfiguration.java index 719526ae6..6db3ef087 100644 --- a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/tools/ReprojectionConsoleConfiguration.java +++ b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/autoconfigure/web/tools/ReprojectionConsoleConfiguration.java @@ -23,8 +23,7 @@ locations = {"jar:gs-web-demo-.*!/applicationContext.xml#name=reprojectionConsole"}) public class ReprojectionConsoleConfiguration extends AbstractWebUIAutoConfiguration { - static final String CONFIG_PREFIX = - ToolsAutoConfiguration.CONFIG_PREFIX + ".reprojection-console"; + static final String CONFIG_PREFIX = ToolsAutoConfiguration.CONFIG_PREFIX + ".reprojection-console"; @Override public String getConfigPrefix() { diff --git a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/web/service/ServiceInstance.java b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/web/service/ServiceInstance.java index 860500fe6..25f0c7721 100644 --- a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/web/service/ServiceInstance.java +++ b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/web/service/ServiceInstance.java @@ -4,9 +4,8 @@ */ package org.geoserver.cloud.web.service; -import lombok.Data; - import java.io.Serializable; +import lombok.Data; /** * @since 1.0 diff --git a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/web/service/ServiceInstanceRegistry.java b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/web/service/ServiceInstanceRegistry.java index 2be97864f..5cd540542 100644 --- a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/web/service/ServiceInstanceRegistry.java +++ b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/web/service/ServiceInstanceRegistry.java @@ -6,17 +6,14 @@ import com.netflix.appinfo.InstanceInfo; import com.netflix.appinfo.InstanceInfo.InstanceStatus; - -import lombok.NonNull; -import lombok.RequiredArgsConstructor; - -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.netflix.eureka.EurekaServiceInstance; - import java.net.URI; import java.util.List; import java.util.function.Function; import java.util.stream.Stream; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.cloud.netflix.eureka.EurekaServiceInstance; /** * @since 1.0 diff --git a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/web/ui/GeoServerCloudHomePageContentProvider.java b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/web/ui/GeoServerCloudHomePageContentProvider.java index 22b9c0410..ba0f0e286 100644 --- a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/web/ui/GeoServerCloudHomePageContentProvider.java +++ b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/web/ui/GeoServerCloudHomePageContentProvider.java @@ -6,7 +6,6 @@ import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.apache.wicket.Component; import org.apache.wicket.markup.html.WebMarkupContainer; import org.geoserver.security.GeoServerSecurityManager; diff --git a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/web/ui/ServiceProvider.java b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/web/ui/ServiceProvider.java index 71bff507b..970d93865 100644 --- a/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/web/ui/ServiceProvider.java +++ b/src/apps/geoserver/webui/src/main/java/org/geoserver/cloud/web/ui/ServiceProvider.java @@ -4,13 +4,12 @@ */ package org.geoserver.cloud.web.ui; +import java.util.List; import org.geoserver.cloud.web.service.ServiceInstance; import org.geoserver.cloud.web.service.ServiceInstanceRegistry; import org.geoserver.web.GeoServerApplication; import org.geoserver.web.wicket.GeoServerDataProvider; -import java.util.List; - /** * @since 1.0 */ @@ -18,8 +17,7 @@ class ServiceProvider extends GeoServerDataProvider { private static final long serialVersionUID = 1L; public static final Property NAME = new BeanProperty<>("name", "name"); - public static final Property INSTANCEID = - new BeanProperty<>("instanceId", "instanceId"); + public static final Property INSTANCEID = new BeanProperty<>("instanceId", "instanceId"); public static final Property STATUS = new BeanProperty<>("status", "status"); public static final Property URI = new BeanProperty<>("uri", "uri"); diff --git a/src/apps/geoserver/webui/src/test/java/org/geoserver/cloud/web/app/AclIntegrationTest.java b/src/apps/geoserver/webui/src/test/java/org/geoserver/cloud/web/app/AclIntegrationTest.java index 58cd0248b..7882b32cf 100644 --- a/src/apps/geoserver/webui/src/test/java/org/geoserver/cloud/web/app/AclIntegrationTest.java +++ b/src/apps/geoserver/webui/src/test/java/org/geoserver/cloud/web/app/AclIntegrationTest.java @@ -6,6 +6,9 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; import org.apache.wicket.util.tester.WicketTester; import org.geoserver.web.GeoServerApplication; import org.geoserver.web.GeoServerHomePage; @@ -22,10 +25,6 @@ import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.test.context.ActiveProfiles; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - @SpringBootTest( properties = { "geoserver.acl.enabled: true", diff --git a/src/apps/geoserver/webui/src/test/java/org/geoserver/cloud/web/app/WebUIApplicationTest.java b/src/apps/geoserver/webui/src/test/java/org/geoserver/cloud/web/app/WebUIApplicationTest.java index a67d4a62e..ccb0e2803 100644 --- a/src/apps/geoserver/webui/src/test/java/org/geoserver/cloud/web/app/WebUIApplicationTest.java +++ b/src/apps/geoserver/webui/src/test/java/org/geoserver/cloud/web/app/WebUIApplicationTest.java @@ -8,6 +8,9 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; import org.apache.wicket.Component; import org.apache.wicket.markup.html.link.BookmarkablePageLink; import org.apache.wicket.markup.html.list.ListItem; @@ -33,10 +36,6 @@ import org.springframework.security.core.context.SecurityContextImpl; import org.springframework.test.context.ActiveProfiles; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - @SpringBootTest( properties = { "spring.cloud.bus.enabled: false", @@ -161,9 +160,8 @@ void GeoServerHomePage_smoke_test_service_links() { protected void assertHidden(String id) { TagTester tag = tester.getTagById(id); - String msg = - "expected custom 'unused' css class to hide the %s form inputs in custom GlobalSettingsPage.html" - .formatted(id); + String msg = "expected custom 'unused' css class to hide the %s form inputs in custom GlobalSettingsPage.html" + .formatted(id); assertEquals("unused", tag.getAttribute("class"), msg); } diff --git a/src/apps/geoserver/wfs/src/main/java/org/geoserver/cloud/wfs/app/WFSController.java b/src/apps/geoserver/wfs/src/main/java/org/geoserver/cloud/wfs/app/WFSController.java index 3ec7ecb19..66fdfb6f1 100644 --- a/src/apps/geoserver/wfs/src/main/java/org/geoserver/cloud/wfs/app/WFSController.java +++ b/src/apps/geoserver/wfs/src/main/java/org/geoserver/cloud/wfs/app/WFSController.java @@ -4,9 +4,10 @@ */ package org.geoserver.cloud.wfs.app; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.cloud.virtualservice.VirtualServiceVerifier; import org.geoserver.ows.Dispatcher; import org.springframework.stereotype.Controller; @@ -15,9 +16,6 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.view.RedirectView; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - @Controller @RequiredArgsConstructor public class WFSController { @@ -35,8 +33,7 @@ public RedirectView redirectRootToGetCapabilities() { /** Serve only WFS schemas from classpath (e.g. {@code /schemas/wfs/2.0/wfs.xsd}) */ @GetMapping(path = "/schemas/wfs/**") - public void getSchema(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void getSchema(HttpServletRequest request, HttpServletResponse response) throws Exception { classPathPublisher.handleRequest(request, response); } @@ -50,20 +47,17 @@ public void getSchema(HttpServletRequest request, HttpServletResponse response) * */ @GetMapping(path = {"/webresources/wfs/**"}) - public void getStaticResource(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void getStaticResource(HttpServletRequest request, HttpServletResponse response) throws Exception { classPathPublisher.handleRequest(request, response); } @GetMapping(path = {"/wfs", "/ows"}) - public void handleGet(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void handleGet(HttpServletRequest request, HttpServletResponse response) throws Exception { dispatch(request, response); } @PostMapping(path = {"/wfs", "/ows"}) - public void handlePost(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void handlePost(HttpServletRequest request, HttpServletResponse response) throws Exception { dispatch(request, response); } @@ -113,8 +107,7 @@ public void handleVirtualServiceLayerPost( dispatch(request, response); } - private void dispatch(HttpServletRequest request, HttpServletResponse response) - throws Exception { + private void dispatch(HttpServletRequest request, HttpServletResponse response) throws Exception { geoserverDispatcher.handleRequest(request, response); } } diff --git a/src/apps/geoserver/wfs/src/test/java/org/geoserver/cloud/wfs/app/WfsApplicationDataDirectoryIT.java b/src/apps/geoserver/wfs/src/test/java/org/geoserver/cloud/wfs/app/WfsApplicationDataDirectoryIT.java index ea25f6583..9876d65c6 100644 --- a/src/apps/geoserver/wfs/src/test/java/org/geoserver/cloud/wfs/app/WfsApplicationDataDirectoryIT.java +++ b/src/apps/geoserver/wfs/src/test/java/org/geoserver/cloud/wfs/app/WfsApplicationDataDirectoryIT.java @@ -4,6 +4,9 @@ */ package org.geoserver.cloud.wfs.app; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; @@ -11,10 +14,6 @@ import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; - @SpringBootTest(classes = WfsApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) @ActiveProfiles("datadir") class WfsApplicationDataDirectoryIT extends WfsApplicationTest { diff --git a/src/apps/geoserver/wfs/src/test/java/org/geoserver/cloud/wfs/app/WfsApplicationPgconfigIT.java b/src/apps/geoserver/wfs/src/test/java/org/geoserver/cloud/wfs/app/WfsApplicationPgconfigIT.java index ac03f68e5..2481e265f 100644 --- a/src/apps/geoserver/wfs/src/test/java/org/geoserver/cloud/wfs/app/WfsApplicationPgconfigIT.java +++ b/src/apps/geoserver/wfs/src/test/java/org/geoserver/cloud/wfs/app/WfsApplicationPgconfigIT.java @@ -18,7 +18,8 @@ @Testcontainers(disabledWithoutDocker = true) class WfsApplicationPgconfigIT extends WfsApplicationTest { - @Container static PostgreSQLContainer container = new PostgreSQLContainer<>("postgres:15"); + @Container + static PostgreSQLContainer container = new PostgreSQLContainer<>("postgres:15"); /** * Contribute the following properties defined in the {@literal pgconfigjndi} spring profile @@ -35,9 +36,7 @@ class WfsApplicationPgconfigIT extends WfsApplicationTest { @DynamicPropertySource static void setUpDataDir(DynamicPropertyRegistry registry) { registry.add("pgconfig.host", container::getHost); - registry.add( - "pgconfig.port", - () -> container.getMappedPort(PostgreSQLContainer.POSTGRESQL_PORT)); + registry.add("pgconfig.port", () -> container.getMappedPort(PostgreSQLContainer.POSTGRESQL_PORT)); registry.add("pgconfig.database", container::getDatabaseName); registry.add("pgconfig.schema", () -> "pgconfigtestschema"); registry.add("pgconfig.username", container::getUsername); diff --git a/src/apps/geoserver/wfs/src/test/java/org/geoserver/cloud/wfs/app/WfsApplicationTest.java b/src/apps/geoserver/wfs/src/test/java/org/geoserver/cloud/wfs/app/WfsApplicationTest.java index ac2c1166d..591835683 100644 --- a/src/apps/geoserver/wfs/src/test/java/org/geoserver/cloud/wfs/app/WfsApplicationTest.java +++ b/src/apps/geoserver/wfs/src/test/java/org/geoserver/cloud/wfs/app/WfsApplicationTest.java @@ -4,6 +4,7 @@ */ package org.geoserver.cloud.wfs.app; +import java.util.Map; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; @@ -11,8 +12,6 @@ import org.springframework.boot.test.web.server.LocalServerPort; import org.xmlunit.assertj3.XmlAssert; -import java.util.Map; - @SpringBootTest(classes = WfsApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) abstract class WfsApplicationTest { @@ -20,25 +19,17 @@ abstract class WfsApplicationTest { @Test void owsGetCapabilitiesSmokeTest(@LocalServerPort int servicePort) { - String url = - "http://localhost:%d/ows?SERVICE=WFS&REQUEST=GETCAPABILITIES&VERSION=1.1.0" - .formatted(servicePort); + String url = "http://localhost:%d/ows?SERVICE=WFS&REQUEST=GETCAPABILITIES&VERSION=1.1.0".formatted(servicePort); String caps = restTemplate.getForObject(url, String.class); Map nscontext = Map.of("wfs", "http://www.opengis.net/wfs"); - XmlAssert.assertThat(caps) - .withNamespaceContext(nscontext) - .hasXPath("/wfs:WFS_Capabilities"); + XmlAssert.assertThat(caps).withNamespaceContext(nscontext).hasXPath("/wfs:WFS_Capabilities"); } @Test void wfsGetCapabilitiesSmokeTest(@LocalServerPort int servicePort) { - String url = - "http://localhost:%d/wfs?SERVICE=WFS&REQUEST=GETCAPABILITIES&VERSION=1.1.0" - .formatted(servicePort); + String url = "http://localhost:%d/wfs?SERVICE=WFS&REQUEST=GETCAPABILITIES&VERSION=1.1.0".formatted(servicePort); String caps = restTemplate.getForObject(url, String.class); Map nscontext = Map.of("wfs", "http://www.opengis.net/wfs"); - XmlAssert.assertThat(caps) - .withNamespaceContext(nscontext) - .hasXPath("/wfs:WFS_Capabilities"); + XmlAssert.assertThat(caps).withNamespaceContext(nscontext).hasXPath("/wfs:WFS_Capabilities"); } } diff --git a/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/autoconfigure/wms/KMLAutoConfiguration.java b/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/autoconfigure/wms/KMLAutoConfiguration.java index 462ffdf21..be11ca671 100644 --- a/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/autoconfigure/wms/KMLAutoConfiguration.java +++ b/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/autoconfigure/wms/KMLAutoConfiguration.java @@ -21,16 +21,11 @@ * @since 1.0 */ @Configuration(proxyBeanMethods = false) -@ConditionalOnProperty( - name = "geoserver.wms.kml.enabled", - havingValue = "true", - matchIfMissing = true) +@ConditionalOnProperty(name = "geoserver.wms.kml.enabled", havingValue = "true", matchIfMissing = true) @ConditionalOnClass(MBStyleHandler.class) @ImportResource( // reader = FilteringXmlBeanDefinitionReader.class, // - locations = { - "jar:gs-kml-.*!/applicationContext.xml#name=^(?!WFSKMLOutputFormat|kmlURLMapping).*$" - }) + locations = {"jar:gs-kml-.*!/applicationContext.xml#name=^(?!WFSKMLOutputFormat|kmlURLMapping).*$"}) public class KMLAutoConfiguration { @Bean diff --git a/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/autoconfigure/wms/WmsApplicationAutoConfiguration.java b/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/autoconfigure/wms/WmsApplicationAutoConfiguration.java index 13d6bb885..e3fc09391 100644 --- a/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/autoconfigure/wms/WmsApplicationAutoConfiguration.java +++ b/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/autoconfigure/wms/WmsApplicationAutoConfiguration.java @@ -31,10 +31,8 @@ @ImportResource( // reader = FilteringXmlBeanDefinitionReader.class, // locations = { // - "jar:gs-wms-.*!/applicationContext.xml#name=" - + WmsApplicationAutoConfiguration.WMS_BEANS_BLACKLIST, // - "jar:gs-wfs-.*!/applicationContext.xml#name=" - + WmsApplicationAutoConfiguration.WFS_BEANS_WHITELIST // + "jar:gs-wms-.*!/applicationContext.xml#name=" + WmsApplicationAutoConfiguration.WMS_BEANS_BLACKLIST, // + "jar:gs-wfs-.*!/applicationContext.xml#name=" + WmsApplicationAutoConfiguration.WFS_BEANS_WHITELIST // }) public class WmsApplicationAutoConfiguration { @@ -70,8 +68,7 @@ public class WmsApplicationAutoConfiguration { * workspace and secured catalog decorators */ @Bean - LegendSample legendSample( - @Qualifier("rawCatalog") Catalog catalog, GeoServerResourceLoader loader) { + LegendSample legendSample(@Qualifier("rawCatalog") Catalog catalog, GeoServerResourceLoader loader) { return new LegendSampleImpl(catalog, loader); } diff --git a/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/wms/controller/GetMapReflectorController.java b/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/wms/controller/GetMapReflectorController.java index 66e83486a..8b28ecab6 100644 --- a/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/wms/controller/GetMapReflectorController.java +++ b/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/wms/controller/GetMapReflectorController.java @@ -4,16 +4,14 @@ */ package org.geoserver.cloud.wms.controller; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.ows.Dispatcher; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - @Controller @RequiredArgsConstructor public class GetMapReflectorController { @@ -21,8 +19,7 @@ public class GetMapReflectorController { private final @NonNull Dispatcher geoserverDispatcher; @GetMapping(path = {"/wms/reflect", "/{workspace}/wms/reflect"}) - public void getMapReflect(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void getMapReflect(HttpServletRequest request, HttpServletResponse response) throws Exception { geoserverDispatcher.handleRequest(request, response); } } diff --git a/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/wms/controller/WMSController.java b/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/wms/controller/WMSController.java index 71eb20779..00eb4f34a 100644 --- a/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/wms/controller/WMSController.java +++ b/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/wms/controller/WMSController.java @@ -4,9 +4,10 @@ */ package org.geoserver.cloud.wms.controller; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.cloud.virtualservice.VirtualServiceVerifier; import org.geoserver.ows.Dispatcher; import org.springframework.stereotype.Controller; @@ -15,9 +16,6 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.view.RedirectView; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - @Controller @RequiredArgsConstructor public class WMSController { @@ -44,8 +42,7 @@ public RedirectView redirectRootToGetCapabilities() { * */ @GetMapping(path = {"/schemas/wms/**"}) - public void getWmsSchema(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void getWmsSchema(HttpServletRequest request, HttpServletResponse response) throws Exception { classPathPublisher.handleRequest(request, response); } @@ -61,22 +58,18 @@ public void getWmsSchema(HttpServletRequest request, HttpServletResponse respons *
  • {@code /options.png} * */ - @GetMapping( - path = {"/openlayers/**", "/openlayers3/**", "/webresources/wms/**", "/options.png"}) - public void getStaticResource(HttpServletRequest request, HttpServletResponse response) - throws Exception { + @GetMapping(path = {"/openlayers/**", "/openlayers3/**", "/webresources/wms/**", "/options.png"}) + public void getStaticResource(HttpServletRequest request, HttpServletResponse response) throws Exception { classPathPublisher.handleRequest(request, response); } @GetMapping(path = {"/wms", "/ows"}) - public void handleGet(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void handleGet(HttpServletRequest request, HttpServletResponse response) throws Exception { dispatch(request, response); } @PostMapping(path = {"/wms", "/ows"}) - public void handlePost(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void handlePost(HttpServletRequest request, HttpServletResponse response) throws Exception { dispatch(request, response); } @@ -126,8 +119,7 @@ public void handleVirtualServiceLayerPost( dispatch(request, response); } - private void dispatch(HttpServletRequest request, HttpServletResponse response) - throws Exception { + private void dispatch(HttpServletRequest request, HttpServletResponse response) throws Exception { geoserverDispatcher.handleRequest(request, response); } } diff --git a/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/wms/controller/kml/KMLIconsController.java b/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/wms/controller/kml/KMLIconsController.java index 09790ea77..abce3e72b 100644 --- a/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/wms/controller/kml/KMLIconsController.java +++ b/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/wms/controller/kml/KMLIconsController.java @@ -4,18 +4,16 @@ */ package org.geoserver.cloud.wms.controller.kml; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; +import javax.servlet.http.HttpServletResponse; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.kml.KMLReflector; import org.geoserver.wms.icons.IconService; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; -import javax.servlet.http.HttpServletResponse; - /** * Controller for KML icons at {@literal /kml/icon/**}. * @@ -44,8 +42,7 @@ public class KMLIconsController { private final @NonNull IconService kmlIconService; @GetMapping(path = "/kml/icon/**") - public void getKmlIcon(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void getKmlIcon(HttpServletRequest request, HttpServletResponse response) throws Exception { kmlIconService.handleRequest(adaptRequest(request), response); } diff --git a/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/wms/controller/kml/KMLReflectorController.java b/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/wms/controller/kml/KMLReflectorController.java index e99806b1e..6b7772395 100644 --- a/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/wms/controller/kml/KMLReflectorController.java +++ b/src/apps/geoserver/wms/src/main/java/org/geoserver/cloud/wms/controller/kml/KMLReflectorController.java @@ -4,17 +4,15 @@ */ package org.geoserver.cloud.wms.controller.kml; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.kml.KMLReflector; import org.geoserver.ows.Dispatcher; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - /** * Controller for {@link KMLReflector} at {@literal /wms/kml?}/{@literal /{workspace}/wms/kml?} * @@ -31,8 +29,7 @@ public class KMLReflectorController { private final @NonNull Dispatcher geoserverDispatcher; @GetMapping(path = {"/wms/kml", "/{workspace}/wms/kml"}) - public void kmlReflect(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void kmlReflect(HttpServletRequest request, HttpServletResponse response) throws Exception { geoserverDispatcher.handleRequest(request, response); } diff --git a/src/apps/geoserver/wms/src/test/java/org/geoserver/cloud/wms/app/WmsApplicationDataDirectoryTest.java b/src/apps/geoserver/wms/src/test/java/org/geoserver/cloud/wms/app/WmsApplicationDataDirectoryTest.java index 6a61d32ac..abf6a104d 100644 --- a/src/apps/geoserver/wms/src/test/java/org/geoserver/cloud/wms/app/WmsApplicationDataDirectoryTest.java +++ b/src/apps/geoserver/wms/src/test/java/org/geoserver/cloud/wms/app/WmsApplicationDataDirectoryTest.java @@ -4,6 +4,10 @@ */ package org.geoserver.cloud.wms.app; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; @@ -16,11 +20,6 @@ import org.springframework.test.context.DynamicPropertySource; import org.xmlunit.assertj3.XmlAssert; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Map; - @SpringBootTest( classes = WmsApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT, @@ -51,8 +50,6 @@ void getCapabilitiesSmokeTest() { String url = baseURL + "?SERVICE=WMS&REQUEST=GETCAPABILITIES&VERSION=1.3.0"; String caps = restTemplate.getForObject(url, String.class); Map nscontext = Map.of("wms", "http://www.opengis.net/wms"); - XmlAssert.assertThat(caps) - .withNamespaceContext(nscontext) - .hasXPath("/wms:WMS_Capabilities"); + XmlAssert.assertThat(caps).withNamespaceContext(nscontext).hasXPath("/wms:WMS_Capabilities"); } } diff --git a/src/apps/geoserver/wms/src/test/java/org/geoserver/cloud/wms/app/WmsApplicationTest.java b/src/apps/geoserver/wms/src/test/java/org/geoserver/cloud/wms/app/WmsApplicationTest.java index b707f63e6..2c5f9f6c9 100644 --- a/src/apps/geoserver/wms/src/test/java/org/geoserver/cloud/wms/app/WmsApplicationTest.java +++ b/src/apps/geoserver/wms/src/test/java/org/geoserver/cloud/wms/app/WmsApplicationTest.java @@ -34,9 +34,7 @@ void testExpectedBeansFromWmsApplicationAutoConfiguration() { expectBean("webMapServiceController", WMSController.class); expectBean("virtualServiceVerifier", VirtualServiceVerifier.class); expectBean("getMapReflectorController", GetMapReflectorController.class); - expectBean( - "wms_1_1_1_GetCapabilitiesResponse", - org.geoserver.wms.capabilities.GetCapabilitiesResponse.class); + expectBean("wms_1_1_1_GetCapabilitiesResponse", org.geoserver.wms.capabilities.GetCapabilitiesResponse.class); } @Test diff --git a/src/apps/geoserver/wps/src/main/java/org/geoserver/cloud/wps/WPSController.java b/src/apps/geoserver/wps/src/main/java/org/geoserver/cloud/wps/WPSController.java index 554a83037..693d1dd17 100644 --- a/src/apps/geoserver/wps/src/main/java/org/geoserver/cloud/wps/WPSController.java +++ b/src/apps/geoserver/wps/src/main/java/org/geoserver/cloud/wps/WPSController.java @@ -4,9 +4,10 @@ */ package org.geoserver.cloud.wps; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.cloud.virtualservice.VirtualServiceVerifier; import org.geoserver.ows.Dispatcher; import org.springframework.stereotype.Controller; @@ -15,9 +16,6 @@ import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.servlet.view.RedirectView; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - @Controller @RequiredArgsConstructor public class WPSController { @@ -35,20 +33,17 @@ public RedirectView redirectRootToGetCapabilities() { /** Serve only WPS schemas from classpath (e.g. {@code /schemas/wps/1.0.0/wpsAll.xsd}) */ @GetMapping(path = "/schemas/wps/**") - public void getSchema(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void getSchema(HttpServletRequest request, HttpServletResponse response) throws Exception { classPathPublisher.handleRequest(request, response); } @GetMapping(path = {"/wps", "/ows"}) - public void handleGet(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void handleGet(HttpServletRequest request, HttpServletResponse response) throws Exception { dispatch(request, response); } @PostMapping(path = {"/wps", "/ows"}) - public void handlePost(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void handlePost(HttpServletRequest request, HttpServletResponse response) throws Exception { dispatch(request, response); } @@ -98,8 +93,7 @@ public void handleVirtualServiceLayerPost( dispatch(request, response); } - private void dispatch(HttpServletRequest request, HttpServletResponse response) - throws Exception { + private void dispatch(HttpServletRequest request, HttpServletResponse response) throws Exception { geoserverDispatcher.handleRequest(request, response); } } diff --git a/src/apps/geoserver/wps/src/test/java/org/geoserver/cloud/wps/WpsApplicationTest.java b/src/apps/geoserver/wps/src/test/java/org/geoserver/cloud/wps/WpsApplicationTest.java index ff5ba25a5..556952071 100644 --- a/src/apps/geoserver/wps/src/test/java/org/geoserver/cloud/wps/WpsApplicationTest.java +++ b/src/apps/geoserver/wps/src/test/java/org/geoserver/cloud/wps/WpsApplicationTest.java @@ -4,6 +4,10 @@ */ package org.geoserver.cloud.wps; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Map; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.springframework.boot.test.context.SpringBootTest; @@ -15,11 +19,6 @@ import org.springframework.test.context.DynamicPropertySource; import org.xmlunit.assertj3.XmlAssert; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Map; - @SpringBootTest(classes = WpsApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT) @ActiveProfiles("test") class WpsApplicationTest { @@ -38,9 +37,7 @@ static void setUpDataDir(DynamicPropertyRegistry registry) throws IOException { @Test void owsGetCapabilitiesSmokeTest(@LocalServerPort int servicePort) { - String url = - "http://localhost:%d/ows?SERVICE=WPS&REQUEST=GETCAPABILITIES&VERSION=1.0.0" - .formatted(servicePort); + String url = "http://localhost:%d/ows?SERVICE=WPS&REQUEST=GETCAPABILITIES&VERSION=1.0.0".formatted(servicePort); String caps = restTemplate.getForObject(url, String.class); Map nscontext = Map.of("wps", "http://www.opengis.net/wps/1.0.0"); XmlAssert.assertThat(caps).withNamespaceContext(nscontext).hasXPath("/wps:Capabilities"); @@ -48,9 +45,7 @@ void owsGetCapabilitiesSmokeTest(@LocalServerPort int servicePort) { @Test void wpsGetCapabilitiesSmokeTest(@LocalServerPort int servicePort) { - String url = - "http://localhost:%d/wps?SERVICE=WPS&REQUEST=GETCAPABILITIES&VERSION=1.0.0" - .formatted(servicePort); + String url = "http://localhost:%d/wps?SERVICE=WPS&REQUEST=GETCAPABILITIES&VERSION=1.0.0".formatted(servicePort); String caps = restTemplate.getForObject(url, String.class); Map nscontext = Map.of("wps", "http://www.opengis.net/wps/1.0.0"); XmlAssert.assertThat(caps).withNamespaceContext(nscontext).hasXPath("/wps:Capabilities"); diff --git a/src/apps/infrastructure/admin/src/main/java/org/geoserver/cloud/adminserver/SpringBootAdminServerApplication.java b/src/apps/infrastructure/admin/src/main/java/org/geoserver/cloud/adminserver/SpringBootAdminServerApplication.java index 62c159799..bf18615be 100644 --- a/src/apps/infrastructure/admin/src/main/java/org/geoserver/cloud/adminserver/SpringBootAdminServerApplication.java +++ b/src/apps/infrastructure/admin/src/main/java/org/geoserver/cloud/adminserver/SpringBootAdminServerApplication.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.adminserver; import de.codecentric.boot.admin.server.config.EnableAdminServer; - import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; diff --git a/src/apps/infrastructure/config/src/test/java/org/geoserver/cloud/config/ConfigApplicationTest.java b/src/apps/infrastructure/config/src/test/java/org/geoserver/cloud/config/ConfigApplicationTest.java index e3a52d06a..1203ebba2 100644 --- a/src/apps/infrastructure/config/src/test/java/org/geoserver/cloud/config/ConfigApplicationTest.java +++ b/src/apps/infrastructure/config/src/test/java/org/geoserver/cloud/config/ConfigApplicationTest.java @@ -8,7 +8,6 @@ import static org.hamcrest.Matchers.equalTo; import lombok.extern.slf4j.Slf4j; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.skyscreamer.jsonassert.JSONAssert; @@ -27,9 +26,11 @@ @ActiveProfiles({"native", "test"}) class ConfigApplicationTest { - @LocalServerPort private int port; + @LocalServerPort + private int port; - @Autowired private TestRestTemplate restTemplate; + @Autowired + private TestRestTemplate restTemplate; private String baseUri; @@ -41,8 +42,7 @@ void setup() { @Test void testNoProfile() throws Exception { assertThat( - this.restTemplate.getForEntity(baseUri, String.class).getStatusCode(), - equalTo(HttpStatus.NOT_FOUND)); + this.restTemplate.getForEntity(baseUri, String.class).getStatusCode(), equalTo(HttpStatus.NOT_FOUND)); } @Test diff --git a/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/autoconfigure/gateway/GatewaySharedAuthAutoConfiguration.java b/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/autoconfigure/gateway/GatewaySharedAuthAutoConfiguration.java index 332c7d523..0c07675f4 100644 --- a/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/autoconfigure/gateway/GatewaySharedAuthAutoConfiguration.java +++ b/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/autoconfigure/gateway/GatewaySharedAuthAutoConfiguration.java @@ -4,16 +4,14 @@ */ package org.geoserver.cloud.autoconfigure.gateway; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.security.gateway.sharedauth.GatewaySharedAuthenticationPostFilter; import org.geoserver.cloud.security.gateway.sharedauth.GatewaySharedAuthenticationPreFilter; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Bean; -import javax.annotation.PostConstruct; - @AutoConfiguration @ConditionalOnProperty( name = "geoserver.security.gateway-shared-auth.enabled", diff --git a/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/gateway/filter/GlobalUriFilter.java b/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/gateway/filter/GlobalUriFilter.java index 5da45c9b5..4fde6bcdd 100644 --- a/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/gateway/filter/GlobalUriFilter.java +++ b/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/gateway/filter/GlobalUriFilter.java @@ -7,6 +7,7 @@ import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_REQUEST_URL_ATTR; import static org.springframework.cloud.gateway.support.ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR; +import java.net.URI; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; import org.springframework.cloud.gateway.filter.ReactiveLoadBalancerClientFilter; @@ -14,11 +15,8 @@ import org.springframework.core.Ordered; import org.springframework.stereotype.Component; import org.springframework.web.server.ServerWebExchange; - import reactor.core.publisher.Mono; -import java.net.URI; - /** * See gateway's issue #2065 "Double Encoded @@ -54,8 +52,7 @@ private URI createUri(URI incomingUri, URI balanceUrl) { final var port = balanceUrl.getPort() != -1 ? ":" + balanceUrl.getPort() : ""; final var rawPath = balanceUrl.getRawPath() != null ? balanceUrl.getRawPath() : ""; final var query = incomingUri.getRawQuery() != null ? "?" + incomingUri.getRawQuery() : ""; - return URI.create( - balanceUrl.getScheme() + "://" + balanceUrl.getHost() + port + rawPath + query); + return URI.create(balanceUrl.getScheme() + "://" + balanceUrl.getHost() + port + rawPath + query); } private static boolean isUriEncoded(URI uri) { diff --git a/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/gateway/filter/RouteProfileGatewayFilterFactory.java b/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/gateway/filter/RouteProfileGatewayFilterFactory.java index 858a740fe..965fb1469 100644 --- a/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/gateway/filter/RouteProfileGatewayFilterFactory.java +++ b/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/gateway/filter/RouteProfileGatewayFilterFactory.java @@ -6,11 +6,14 @@ import static org.springframework.cloud.gateway.support.GatewayToStringStyler.filterToStringCreator; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import javax.validation.constraints.NotEmpty; import lombok.Data; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.experimental.Accessors; - import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; @@ -19,15 +22,8 @@ import org.springframework.util.StringUtils; import org.springframework.validation.annotation.Validated; import org.springframework.web.server.ServerWebExchange; - import reactor.core.publisher.Mono; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import javax.validation.constraints.NotEmpty; - /** Allows to enable routes only if a given spring profile is enabled */ public class RouteProfileGatewayFilterFactory extends AbstractGatewayFilterFactory { @@ -104,7 +100,8 @@ public static class Config { */ public static final String HTTPSTATUS_KEY = "statusCode"; - @NotEmpty private String profile; + @NotEmpty + private String profile; private int statusCode = HttpStatus.NOT_FOUND.value(); } diff --git a/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/gateway/filter/StripBasePathGatewayFilterFactory.java b/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/gateway/filter/StripBasePathGatewayFilterFactory.java index 175fb33c7..f43c8c5bc 100644 --- a/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/gateway/filter/StripBasePathGatewayFilterFactory.java +++ b/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/gateway/filter/StripBasePathGatewayFilterFactory.java @@ -6,8 +6,8 @@ import static com.google.common.base.Preconditions.checkArgument; +import java.util.List; import lombok.Data; - import org.springframework.cloud.gateway.filter.GatewayFilter; import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory; import org.springframework.cloud.gateway.filter.factory.StripPrefixGatewayFilterFactory; @@ -15,8 +15,6 @@ import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.util.StringUtils; -import java.util.List; - /** * See gateway's issue #1759 "Webflux base @@ -77,9 +75,7 @@ public void checkPreconditions() { if (prefix != null) { checkArgument(prefix.startsWith("/"), "StripBasePath prefix must start with /"); - checkArgument( - "/".equals(prefix) || !prefix.endsWith("/"), - "StripBasePath prefix must not end with /"); + checkArgument("/".equals(prefix) || !prefix.endsWith("/"), "StripBasePath prefix must not end with /"); } } } diff --git a/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/gateway/predicate/RegExpQueryRoutePredicateFactory.java b/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/gateway/predicate/RegExpQueryRoutePredicateFactory.java index 91a34cf37..1be270472 100644 --- a/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/gateway/predicate/RegExpQueryRoutePredicateFactory.java +++ b/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/gateway/predicate/RegExpQueryRoutePredicateFactory.java @@ -4,11 +4,17 @@ */ package org.geoserver.cloud.gateway.predicate; +import java.util.Arrays; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.function.Predicate; +import java.util.regex.Pattern; +import javax.validation.constraints.NotEmpty; import lombok.Data; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.experimental.Accessors; - import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory; import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate; import org.springframework.cloud.gateway.handler.predicate.QueryRoutePredicateFactory; @@ -16,15 +22,6 @@ import org.springframework.validation.annotation.Validated; import org.springframework.web.server.ServerWebExchange; -import java.util.Arrays; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.function.Predicate; -import java.util.regex.Pattern; - -import javax.validation.constraints.NotEmpty; - /** * Gateway predicate factory that allows matching by HTTP request query string parameters using * {@link Pattern Java regular expressions} for both parameter name and value. @@ -119,7 +116,8 @@ static boolean paramValueMatches( @Validated public static class Config { - @NotEmpty private String paramRegexp; + @NotEmpty + private String paramRegexp; private String valueRegexp; } diff --git a/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationPostFilter.java b/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationPostFilter.java index 45d0516fd..05cb173b4 100644 --- a/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationPostFilter.java +++ b/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationPostFilter.java @@ -7,8 +7,11 @@ import static org.geoserver.cloud.security.gateway.sharedauth.SharedAuthConfigurationProperties.X_GSCLOUD_ROLES; import static org.geoserver.cloud.security.gateway.sharedauth.SharedAuthConfigurationProperties.X_GSCLOUD_USERNAME; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; - import org.springframework.boot.autoconfigure.neo4j.Neo4jProperties.Authentication; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; @@ -18,14 +21,8 @@ import org.springframework.util.StringUtils; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebSession; - import reactor.core.publisher.Mono; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.stream.Collectors; - /** * {@link GlobalFilter} working in tandem with {@link GatewaySharedAuthenticationPreFilter} to * enable sharing the webui form-based authentication object with the other services. @@ -69,9 +66,7 @@ public int getOrder() { @Override public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { - return chain.filter(exchange) - .then(updateHeadersInSession(exchange)) - .then(removeResponseHeaders(exchange)); + return chain.filter(exchange).then(updateHeadersInSession(exchange)).then(removeResponseHeaders(exchange)); } /** @@ -88,16 +83,11 @@ public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { private Mono updateHeadersInSession(ServerWebExchange exchange) { return exchange.getSession() - .flatMap( - session -> - updateSession( - exchange.getRequest(), - exchange.getResponse().getHeaders(), - session)); + .flatMap(session -> updateSession( + exchange.getRequest(), exchange.getResponse().getHeaders(), session)); } - private Mono updateSession( - ServerHttpRequest req, HttpHeaders responseHeaders, WebSession session) { + private Mono updateSession(ServerHttpRequest req, HttpHeaders responseHeaders, WebSession session) { final var responseUser = responseHeaders.getFirst(X_GSCLOUD_USERNAME); if (null == responseUser) { return Mono.empty(); @@ -111,8 +101,7 @@ private Mono updateSession( return Mono.fromRunnable(() -> loggedIn(session, responseUser, roles, req)); } - private void loggedIn( - WebSession session, String user, List roles, ServerHttpRequest req) { + private void loggedIn(WebSession session, String user, List roles, ServerHttpRequest req) { var attributes = session.getAttributes(); var currUser = attributes.get(X_GSCLOUD_USERNAME); var currRoles = attributes.get(X_GSCLOUD_ROLES); @@ -155,11 +144,10 @@ private void loggedOut(WebSession session, ServerHttpRequest req) { } private Mono removeResponseHeaders(ServerWebExchange exchange) { - return Mono.fromRunnable( - () -> { - HttpHeaders responseHeaders = exchange.getResponse().getHeaders(); - removeResponseHeaders(exchange.getRequest(), responseHeaders); - }); + return Mono.fromRunnable(() -> { + HttpHeaders responseHeaders = exchange.getResponse().getHeaders(); + removeResponseHeaders(exchange.getRequest(), responseHeaders); + }); } private void removeResponseHeaders(ServerHttpRequest req, HttpHeaders responseHeaders) { @@ -169,14 +157,12 @@ private void removeResponseHeaders(ServerHttpRequest req, HttpHeaders responseHe private void removeResponseHeader(ServerHttpRequest req, HttpHeaders headers, String name) { removeHeader(headers, name) - .ifPresent( - value -> - log.trace( - "removed response header {}: '{}'. {} {}", - name, - value, - req.getMethod(), - req.getURI().getPath())); + .ifPresent(value -> log.trace( + "removed response header {}: '{}'. {} {}", + name, + value, + req.getMethod(), + req.getURI().getPath())); } private Optional removeHeader(HttpHeaders httpHeaders, String name) { diff --git a/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationPreFilter.java b/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationPreFilter.java index 11811a47b..19d728055 100644 --- a/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationPreFilter.java +++ b/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationPreFilter.java @@ -7,8 +7,12 @@ import static org.geoserver.cloud.security.gateway.sharedauth.SharedAuthConfigurationProperties.X_GSCLOUD_ROLES; import static org.geoserver.cloud.security.gateway.sharedauth.SharedAuthConfigurationProperties.X_GSCLOUD_USERNAME; +import java.net.InetSocketAddress; +import java.net.URI; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; - import org.springframework.boot.autoconfigure.neo4j.Neo4jProperties.Authentication; import org.springframework.cloud.gateway.filter.GatewayFilterChain; import org.springframework.cloud.gateway.filter.GlobalFilter; @@ -19,15 +23,8 @@ import org.springframework.util.StringUtils; import org.springframework.web.server.ServerWebExchange; import org.springframework.web.server.WebSession; - import reactor.core.publisher.Mono; -import java.net.InetSocketAddress; -import java.net.URI; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - /** * {@link GlobalFilter} working in tandem with {@link GatewaySharedAuthenticationPostFilter} to * enable sharing the webui form-based authentication object with the other services. @@ -85,31 +82,28 @@ private Mono addHeadersFromSession(ServerWebExchange exchange return exchange.getSession().map(session -> addHeadersFromSession(session, exchange)); } - private ServerWebExchange addHeadersFromSession( - WebSession session, ServerWebExchange exchange) { + private ServerWebExchange addHeadersFromSession(WebSession session, ServerWebExchange exchange) { final String username = session.getAttribute(X_GSCLOUD_USERNAME); if (StringUtils.hasText(username)) { final List roles = session.getAttributeOrDefault(X_GSCLOUD_ROLES, List.of()); final var origRequest = exchange.getRequest(); - var request = - origRequest - .mutate() - .headers( - headers -> { - headers.set(X_GSCLOUD_USERNAME, username); - headers.remove(X_GSCLOUD_ROLES); - roles.forEach(role -> headers.add(X_GSCLOUD_ROLES, role)); - log.debug( - "appended shared-auth request headers from session[{}] {}: {}, {}: {} to {} {}", - session.getId(), - X_GSCLOUD_USERNAME, - username, - X_GSCLOUD_ROLES, - roles, - origRequest.getMethod(), - origRequest.getURI().getPath()); - }) - .build(); + var request = origRequest + .mutate() + .headers(headers -> { + headers.set(X_GSCLOUD_USERNAME, username); + headers.remove(X_GSCLOUD_ROLES); + roles.forEach(role -> headers.add(X_GSCLOUD_ROLES, role)); + log.debug( + "appended shared-auth request headers from session[{}] {}: {}, {}: {} to {} {}", + session.getId(), + X_GSCLOUD_USERNAME, + username, + X_GSCLOUD_ROLES, + roles, + origRequest.getMethod(), + origRequest.getURI().getPath()); + }) + .build(); exchange = exchange.mutate().request(request).build(); } else { @@ -127,11 +121,10 @@ private ServerWebExchange addHeadersFromSession( private ServerWebExchange removeRequestHeaders(ServerWebExchange exchange) { if (impersonationAttempt(exchange)) { var origRequest = exchange.getRequest(); - var request = - exchange.getRequest() - .mutate() - .headers(headers -> removeRequestHeaders(origRequest, headers)) - .build(); + var request = exchange.getRequest() + .mutate() + .headers(headers -> removeRequestHeaders(origRequest, headers)) + .build(); exchange = exchange.mutate().request(request).build(); } return exchange; @@ -142,22 +135,19 @@ private void removeRequestHeaders(ServerHttpRequest origRequest, HttpHeaders req removeRequestHeader(origRequest, requestHeaders, X_GSCLOUD_ROLES); } - private void removeRequestHeader( - ServerHttpRequest origRequest, HttpHeaders headers, String name) { - removeHeader(headers, name) - .ifPresent( - value -> { - HttpMethod method = origRequest.getMethod(); - URI uri = origRequest.getURI(); - InetSocketAddress remoteAddress = origRequest.getRemoteAddress(); - log.warn( - "removed incoming request header {}: {}. Request: [{} {}], from: {}", - name, - value, - method, - uri, - remoteAddress); - }); + private void removeRequestHeader(ServerHttpRequest origRequest, HttpHeaders headers, String name) { + removeHeader(headers, name).ifPresent(value -> { + HttpMethod method = origRequest.getMethod(); + URI uri = origRequest.getURI(); + InetSocketAddress remoteAddress = origRequest.getRemoteAddress(); + log.warn( + "removed incoming request header {}: {}. Request: [{} {}], from: {}", + name, + value, + method, + uri, + remoteAddress); + }); } private Optional removeHeader(HttpHeaders httpHeaders, String name) { diff --git a/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/SharedAuthConfigurationProperties.java b/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/SharedAuthConfigurationProperties.java index 0b0cfdc9a..cb94615fa 100644 --- a/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/SharedAuthConfigurationProperties.java +++ b/src/apps/infrastructure/gateway/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/SharedAuthConfigurationProperties.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.security.gateway.sharedauth; import lombok.Data; - import org.springframework.boot.context.properties.ConfigurationProperties; /** diff --git a/src/apps/infrastructure/gateway/src/test/java/org/geoserver/cloud/autoconfigure/gateway/GatewayApplicationAutoconfigurationTest.java b/src/apps/infrastructure/gateway/src/test/java/org/geoserver/cloud/autoconfigure/gateway/GatewayApplicationAutoconfigurationTest.java index 24e0e617d..b2ea17476 100644 --- a/src/apps/infrastructure/gateway/src/test/java/org/geoserver/cloud/autoconfigure/gateway/GatewayApplicationAutoconfigurationTest.java +++ b/src/apps/infrastructure/gateway/src/test/java/org/geoserver/cloud/autoconfigure/gateway/GatewayApplicationAutoconfigurationTest.java @@ -15,19 +15,15 @@ class GatewayApplicationAutoconfigurationTest { - private ReactiveWebApplicationContextRunner runner = - new ReactiveWebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(GatewayApplicationAutoconfiguration.class)); + private ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(GatewayApplicationAutoconfiguration.class)); @Test void testDefaultAppContextContributions() { - runner.run( - context -> - assertThat(context) - .hasNotFailed() - .hasSingleBean(RegExpQueryRoutePredicateFactory.class) - .hasSingleBean(RouteProfileGatewayFilterFactory.class) - .hasSingleBean(StripBasePathGatewayFilterFactory.class)); + runner.run(context -> assertThat(context) + .hasNotFailed() + .hasSingleBean(RegExpQueryRoutePredicateFactory.class) + .hasSingleBean(RouteProfileGatewayFilterFactory.class) + .hasSingleBean(StripBasePathGatewayFilterFactory.class)); } } diff --git a/src/apps/infrastructure/gateway/src/test/java/org/geoserver/cloud/autoconfigure/gateway/GatewaySharedAuthAutoConfigurationTest.java b/src/apps/infrastructure/gateway/src/test/java/org/geoserver/cloud/autoconfigure/gateway/GatewaySharedAuthAutoConfigurationTest.java index 6a65a5de9..68432c4d6 100644 --- a/src/apps/infrastructure/gateway/src/test/java/org/geoserver/cloud/autoconfigure/gateway/GatewaySharedAuthAutoConfigurationTest.java +++ b/src/apps/infrastructure/gateway/src/test/java/org/geoserver/cloud/autoconfigure/gateway/GatewaySharedAuthAutoConfigurationTest.java @@ -14,10 +14,8 @@ class GatewaySharedAuthAutoConfigurationTest { - private ReactiveWebApplicationContextRunner runner = - new ReactiveWebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(GatewaySharedAuthAutoConfiguration.class)); + private ReactiveWebApplicationContextRunner runner = new ReactiveWebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(GatewaySharedAuthAutoConfiguration.class)); @Test void enabledByDefault() { @@ -26,28 +24,22 @@ void enabledByDefault() { @Test void enabledByConfig() { - assertEnabled( - runner.withPropertyValues("geoserver.security.gateway-shared-auth.enabled: true")); + assertEnabled(runner.withPropertyValues("geoserver.security.gateway-shared-auth.enabled: true")); } private void assertEnabled(ReactiveWebApplicationContextRunner contextRunner) { - contextRunner.run( - context -> - assertThat(context) - .hasNotFailed() - .hasSingleBean(GatewaySharedAuthenticationPreFilter.class) - .hasSingleBean(GatewaySharedAuthenticationPostFilter.class)); + contextRunner.run(context -> assertThat(context) + .hasNotFailed() + .hasSingleBean(GatewaySharedAuthenticationPreFilter.class) + .hasSingleBean(GatewaySharedAuthenticationPostFilter.class)); } @Test void disableByConfig() { runner.withPropertyValues("geoserver.security.gateway-shared-auth.enabled: false") - .run( - context -> - assertThat(context) - .hasNotFailed() - .doesNotHaveBean(GatewaySharedAuthenticationPreFilter.class) - .doesNotHaveBean( - GatewaySharedAuthenticationPostFilter.class)); + .run(context -> assertThat(context) + .hasNotFailed() + .doesNotHaveBean(GatewaySharedAuthenticationPreFilter.class) + .doesNotHaveBean(GatewaySharedAuthenticationPostFilter.class)); } } diff --git a/src/apps/infrastructure/gateway/src/test/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationTest.java b/src/apps/infrastructure/gateway/src/test/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationTest.java index 2307fd385..a1411ef89 100644 --- a/src/apps/infrastructure/gateway/src/test/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationTest.java +++ b/src/apps/infrastructure/gateway/src/test/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationTest.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.security.gateway.sharedauth; import static com.github.tomakehurst.wiremock.stubbing.StubMapping.buildFrom; - import static org.assertj.core.api.Assertions.assertThat; import com.github.tomakehurst.wiremock.client.WireMock; @@ -14,9 +13,13 @@ import com.github.tomakehurst.wiremock.junit5.WireMockTest; import com.github.tomakehurst.wiremock.stubbing.StubMapping; import com.github.tomakehurst.wiremock.verification.LoggedRequest; - +import java.net.URI; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; import lombok.NonNull; - import org.geoserver.cloud.gateway.GatewayApplication; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; @@ -44,13 +47,6 @@ import org.springframework.web.server.session.WebSessionManager; import org.springframework.web.server.session.WebSessionStore; -import java.net.URI; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; -import java.util.stream.Stream; - /** * Wiremock integration test for a running gateway with {@link GatewaySharedAuthenticationPreFilter} * and {@link GatewaySharedAuthenticationPostFilter} @@ -174,14 +170,16 @@ static void registerRoutes(DynamicPropertyRegistry registry) { registry.add("spring.cloud.gateway.routes[0].predicates[0]", () -> "Path=/**"); } - @Autowired TestRestTemplate testRestTemplate; + @Autowired + TestRestTemplate testRestTemplate; /** * Concrete implementation of {@link WebSessionManager} as created by {@link * EnableWebFluxConfiguration#webSessionManager()} so we can access {@link * DefaultWebSessionManager#getSessionStore()} */ - @Autowired DefaultWebSessionManager webSessionManager; + @Autowired + DefaultWebSessionManager webSessionManager; private URI login; private URI logout; @@ -214,23 +212,19 @@ void setUp(WireMockRuntimeInfo runtimeInfo) { @DisplayName("pre-filter avoids impersonation attempts") void preFilterRemovesIncomingSharedAuthHeaders(WireMockRuntimeInfo runtimeInfo) { ResponseEntity response = - getCapabilities( - "x-gsc-username", "user", "x-gsc-roles", "ROLE_1", "x-gsc-roles", "ROLE_2"); + getCapabilities("x-gsc-username", "user", "x-gsc-roles", "ROLE_1", "x-gsc-roles", "ROLE_2"); assertThat(response.getBody()).startsWith(" getcaps = - getCapabilities("Cookie", "SESSION=%s".formatted(gatewaySessionId)); + ResponseEntity getcaps = getCapabilities("Cookie", "SESSION=%s".formatted(gatewaySessionId)); assertThat(getcaps.getBody()).startsWith(" loginResponse = login(); final String gatewaySessionId = getGatewaySessionId(loginResponse.getHeaders()); @@ -307,11 +295,9 @@ void postFilterRemovesUserAndRolesFromSessionOnEmptyUserResponseHeader( logout(gatewaySessionId); Map attributes = getSessionAttributes(gatewaySessionId); assertThat(attributes) - .as( - "GatewaySharedAuhenticationPostFilter did not remove x-gsc-username from the session") + .as("GatewaySharedAuhenticationPostFilter did not remove x-gsc-username from the session") .doesNotContainKey("x-gsc-username") - .as( - "GatewaySharedAuhenticationPostFilter did not remove x-gsc-roles from the session") + .as("GatewaySharedAuhenticationPostFilter did not remove x-gsc-roles from the session") .doesNotContainKey("x-gsc-roles"); } @@ -327,18 +313,18 @@ void postFilterRemovesOutgoingSharedAuthHeaders(WireMockRuntimeInfo runtimeInfo) ResponseEntity response = login(); HttpHeaders responseHeaders = response.getHeaders(); assertThat(responseHeaders) - .as( - "GatewaySharedAuhenticationGlobalFilter should have removed the x-gsc-username response header") + .as("GatewaySharedAuhenticationGlobalFilter should have removed the x-gsc-username response header") .doesNotContainKey("x-gsc-username") - .as( - "GatewaySharedAuhenticationGlobalFilter should have removed the x-gsc-roles response header") + .as("GatewaySharedAuhenticationGlobalFilter should have removed the x-gsc-roles response header") .doesNotContainKey("x-gsc-roles"); } private String getGatewaySessionId(HttpHeaders responseHeaders) { List cookies = responseHeaders.get("Set-Cookie"); - String cookie = - cookies.stream().filter(c -> c.startsWith("SESSION=")).findFirst().orElseThrow(); + String cookie = cookies.stream() + .filter(c -> c.startsWith("SESSION=")) + .findFirst() + .orElseThrow(); String sessionId = cookie.substring("SESSION=".length()); sessionId = sessionId.substring(0, sessionId.indexOf(';')); return sessionId; @@ -362,34 +348,30 @@ private URI gatewayUriOf(StubMapping mapping) { } ResponseEntity login() { - HttpEntity entity = - withHeaders( // - "Accept", "text/html,application/xhtml+xml", // - "Content-Type", "application/x-www-form-urlencoded"); + HttpEntity entity = withHeaders( // + "Accept", "text/html,application/xhtml+xml", // + "Content-Type", "application/x-www-form-urlencoded"); ResponseEntity response = testRestTemplate.postForEntity(login, entity, Void.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FOUND); HttpHeaders headers = response.getHeaders(); - assertThat(headers) - .containsEntry("Location", List.of("http://0.0.0.0:9090/geoserver/cloud/web")); + assertThat(headers).containsEntry("Location", List.of("http://0.0.0.0:9090/geoserver/cloud/web")); return response; } ResponseEntity logout(@NonNull String gatewaySessionId) { - HttpEntity entity = - withHeaders( // - "Accept", "text/html,application/xhtml+xml", // - "Content-Type", "application/x-www-form-urlencoded", - "Cookie", "SESSION=%s".formatted(gatewaySessionId)); + HttpEntity entity = withHeaders( // + "Accept", "text/html,application/xhtml+xml", // + "Content-Type", "application/x-www-form-urlencoded", + "Cookie", "SESSION=%s".formatted(gatewaySessionId)); ResponseEntity response = testRestTemplate.postForEntity(logout, entity, Void.class); assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FOUND); HttpHeaders headers = response.getHeaders(); - assertThat(headers) - .containsEntry("Location", List.of("http://0.0.0.0:9090/geoserver/cloud/web")); + assertThat(headers).containsEntry("Location", List.of("http://0.0.0.0:9090/geoserver/cloud/web")); return response; } diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/GeoServerBackendAutoConfiguration.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/GeoServerBackendAutoConfiguration.java index b18c97800..714d8fd5f 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/GeoServerBackendAutoConfiguration.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/GeoServerBackendAutoConfiguration.java @@ -22,7 +22,6 @@ * * @see CoreBackendConfiguration */ -@AutoConfiguration( - after = {GeoToolsHttpClientAutoConfiguration.class, JNDIDataSourceConfiguration.class}) +@AutoConfiguration(after = {GeoToolsHttpClientAutoConfiguration.class, JNDIDataSourceConfiguration.class}) @Import(CoreBackendConfiguration.class) public class GeoServerBackendAutoConfiguration {} diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/LifecycleEventAutoConfiguration.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/LifecycleEventAutoConfiguration.java index ce2986a85..ef1e12cfd 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/LifecycleEventAutoConfiguration.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/LifecycleEventAutoConfiguration.java @@ -22,8 +22,7 @@ public class LifecycleEventAutoConfiguration { @Bean - LifecycleEventProcessor lifecycleEventProcessor( - @Qualifier("geoServer") GeoServerImpl rawGeoServer) { + LifecycleEventProcessor lifecycleEventProcessor(@Qualifier("geoServer") GeoServerImpl rawGeoServer) { return new LifecycleEventProcessor(rawGeoServer); } diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/XstreamServiceLoadersAutoConfiguration.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/XstreamServiceLoadersAutoConfiguration.java index 85592b645..76288e249 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/XstreamServiceLoadersAutoConfiguration.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/XstreamServiceLoadersAutoConfiguration.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.autoconfigure.catalog.backend.core; import lombok.extern.slf4j.Slf4j; - import org.geoserver.config.util.XStreamServiceLoader; import org.geoserver.gwc.wmts.WMTSFactoryExtension; import org.geoserver.gwc.wmts.WMTSXStreamLoader; diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/GeoToolsHttpClientAutoConfiguration.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/GeoToolsHttpClientAutoConfiguration.java index 43f1f074f..86903643a 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/GeoToolsHttpClientAutoConfiguration.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/GeoToolsHttpClientAutoConfiguration.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.autoconfigure.geotools; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.autoconfigure.geotools.GeoToolsHttpClientProxyConfigurationProperties.ProxyHostConfig; import org.geotools.http.HTTPClientFactory; import org.springframework.boot.autoconfigure.AutoConfiguration; @@ -67,10 +66,7 @@ */ @AutoConfiguration @EnableConfigurationProperties(GeoToolsHttpClientProxyConfigurationProperties.class) -@ConditionalOnProperty( - name = "geotools.httpclient.proxy.enabled", - havingValue = "true", - matchIfMissing = true) +@ConditionalOnProperty(name = "geotools.httpclient.proxy.enabled", havingValue = "true", matchIfMissing = true) @Slf4j(topic = "org.geotools.autoconfigure.httpclient") public class GeoToolsHttpClientAutoConfiguration { @@ -89,16 +85,12 @@ SpringEnvironmentAwareGeoToolsHttpClientFactory springEnvironmentAwareGeoToolsHt private void log(ProxyHostConfig config, String protocol) { config.host() .ifPresentOrElse( - host -> - log.info( - "{} proxy configured for GeoTools cascaded OWS stores: {}:{}, secured: {}", - protocol, - host, - config.port(), - config.isSecured()), - () -> - log.info( - "No {} proxy configured for GeoTools cascaded OWS stores", - protocol)); + host -> log.info( + "{} proxy configured for GeoTools cascaded OWS stores: {}:{}, secured: {}", + protocol, + host, + config.port(), + config.isSecured()), + () -> log.info("No {} proxy configured for GeoTools cascaded OWS stores", protocol)); } } diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/GeoToolsHttpClientProxyConfigurationProperties.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/GeoToolsHttpClientProxyConfigurationProperties.java index 522914c8b..8050da17e 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/GeoToolsHttpClientProxyConfigurationProperties.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/GeoToolsHttpClientProxyConfigurationProperties.java @@ -4,18 +4,16 @@ */ package org.geoserver.cloud.autoconfigure.geotools; +import java.net.http.HttpClient; +import java.util.List; +import java.util.Optional; +import java.util.regex.Pattern; import lombok.Data; import lombok.NonNull; - import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.util.StringUtils; -import java.net.http.HttpClient; -import java.util.List; -import java.util.Optional; -import java.util.regex.Pattern; - /** * {@link EnableConfigurationProperties @EnableConfigurationProperties} to configure the HTTP proxy * for the GeoTools {@link HttpClient} using Spring environment configuration. @@ -61,16 +59,13 @@ public int port() { } public boolean isSecured() { - return StringUtils.hasLength(host) - && StringUtils.hasLength(user) - && StringUtils.hasLength(password); + return StringUtils.hasLength(host) && StringUtils.hasLength(user) && StringUtils.hasLength(password); } } public ProxyHostConfig ofProtocol(@NonNull String protocol) { if ("http".equals(protocol)) return http == null ? new ProxyHostConfig() : http; if ("https".equals(protocol)) return https == null ? new ProxyHostConfig() : https; - throw new IllegalArgumentException( - "Uknown protocol %s. Expected http(s)".formatted(protocol)); + throw new IllegalArgumentException("Uknown protocol %s. Expected http(s)".formatted(protocol)); } } diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/GeoToolsStaticContextInitializer.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/GeoToolsStaticContextInitializer.java index 2cb8cf98b..9a6d2fd51 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/GeoToolsStaticContextInitializer.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/GeoToolsStaticContextInitializer.java @@ -19,8 +19,7 @@ * * @since 1.0 */ -public class GeoToolsStaticContextInitializer - implements ApplicationContextInitializer { +public class GeoToolsStaticContextInitializer implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext applicationContext) { @@ -30,15 +29,11 @@ public void initialize(ConfigurableApplicationContext applicationContext) { } System.setProperty("org.geotools.referencing.forceXY", "true"); - boolean useEnvAwareHttpClient = - applicationContext - .getEnvironment() - .getProperty( - "geotools.httpclient.proxy.enabled", Boolean.class, Boolean.TRUE); + boolean useEnvAwareHttpClient = applicationContext + .getEnvironment() + .getProperty("geotools.httpclient.proxy.enabled", Boolean.class, Boolean.TRUE); if (useEnvAwareHttpClient) { - Hints.putSystemDefault( - Hints.HTTP_CLIENT_FACTORY, - SpringEnvironmentAwareGeoToolsHttpClientFactory.class); + Hints.putSystemDefault(Hints.HTTP_CLIENT_FACTORY, SpringEnvironmentAwareGeoToolsHttpClientFactory.class); } } } diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/SpringEnvironmentAwareGeoToolsHttpClient.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/SpringEnvironmentAwareGeoToolsHttpClient.java index 9c9d5302b..394ab06a3 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/SpringEnvironmentAwareGeoToolsHttpClient.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/SpringEnvironmentAwareGeoToolsHttpClient.java @@ -20,9 +20,19 @@ import static java.time.Duration.ofMillis; import static java.time.Duration.ofSeconds; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URI; +import java.net.URL; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.zip.GZIPInputStream; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpHost; @@ -54,18 +64,6 @@ import org.geotools.util.factory.GeoTools; import org.springframework.core.env.PropertyResolver; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URI; -import java.net.URL; -import java.nio.charset.StandardCharsets; -import java.util.Map; -import java.util.Optional; -import java.util.stream.Collectors; -import java.util.zip.GZIPInputStream; - /** * Copy of GeoTools' {@link org.geotools.http.commons.MultithreadedHttpClient} due to its lack of * extensibility, adding the ability to set up the Apache HTTPClient's proxy configuration from @@ -91,13 +89,12 @@ public SpringEnvironmentAwareGeoToolsHttpClient( connectionManager = new PoolingHttpClientConnectionManager(); connectionManager.setMaxTotal(6); connectionManager.setDefaultMaxPerRoute(6); - connectionConfig = - RequestConfig.custom() - .setCookieSpec(CookieSpecs.DEFAULT) - .setExpectContinueEnabled(true) - .setSocketTimeout((int) ofSeconds(30).toMillis()) - .setConnectTimeout((int) ofSeconds(30).toMillis()) - .build(); + connectionConfig = RequestConfig.custom() + .setCookieSpec(CookieSpecs.DEFAULT) + .setExpectContinueEnabled(true) + .setSocketTimeout((int) ofSeconds(30).toMillis()) + .setConnectTimeout((int) ofSeconds(30).toMillis()) + .build(); resetCredentials(); client = builder().build(); } @@ -158,23 +155,18 @@ private void setProxyCredentials(BasicCredentialsProvider provider, ProxyHostCon } } - private void setTargetCredentials( - BasicCredentialsProvider provider, String userName, String pwd) { + private void setTargetCredentials(BasicCredentialsProvider provider, String userName, String pwd) { AuthScope authscope = AuthScope.ANY; Credentials credentials = new UsernamePasswordCredentials(userName, pwd); provider.setCredentials(authscope, credentials); } private HttpClientBuilder builder() { - HttpClientBuilder builder = - HttpClientBuilder.create() - .setUserAgent( - "GeoTools/%s (%s)" - .formatted( - GeoTools.getVersion(), - this.getClass().getSimpleName())) - .useSystemProperties() - .setConnectionManager(connectionManager); + HttpClientBuilder builder = HttpClientBuilder.create() + .setUserAgent("GeoTools/%s (%s)" + .formatted(GeoTools.getVersion(), this.getClass().getSimpleName())) + .useSystemProperties() + .setConnectionManager(connectionManager); if (credsProvider != null) { builder.setDefaultCredentialsProvider(credsProvider); } @@ -182,16 +174,14 @@ private HttpClientBuilder builder() { } @Override - public HttpMethodResponse post( - final URL url, final InputStream postContent, final String postContentType) + public HttpMethodResponse post(final URL url, final InputStream postContent, final String postContentType) throws IOException { return post(url, postContent, postContentType, null); } @Override public HttpMethodResponse post( - URL url, InputStream postContent, String postContentType, Map headers) - throws IOException { + URL url, InputStream postContent, String postContentType, Map headers) throws IOException { if (headers == null) { headers = Map.of(); } else { @@ -204,10 +194,9 @@ public HttpMethodResponse post( if (credsProvider != null) { // we can't read the input stream twice as would be needed if the server asks us to // authenticate - String input = - new BufferedReader(new InputStreamReader(postContent, StandardCharsets.UTF_8)) - .lines() - .collect(Collectors.joining("\n")); + String input = new BufferedReader(new InputStreamReader(postContent, StandardCharsets.UTF_8)) + .lines() + .collect(Collectors.joining("\n")); requestEntity = new StringEntity(input); } else { requestEntity = new InputStreamEntity(postContent); @@ -227,9 +216,8 @@ public HttpMethodResponse post( if (200 != response.getStatusCode()) { postMethod.releaseConnection(); - throw new IOException( - "Server returned HTTP error code %d for URL %s" - .formatted(response.getStatusCode(), url.toExternalForm())); + throw new IOException("Server returned HTTP error code %d for URL %s" + .formatted(response.getStatusCode(), url.toExternalForm())); } return response; @@ -247,9 +235,7 @@ private HttpMethodResponse executeMethod(HttpRequestBase method) throws IOExcept // see https://stackoverflow.com/a/21592593 AuthCache authCache = new BasicAuthCache(); URI target = method.getURI(); - authCache.put( - new HttpHost(target.getHost(), target.getPort(), target.getScheme()), - new BasicScheme()); + authCache.put(new HttpHost(target.getHost(), target.getPort(), target.getScheme()), new BasicScheme()); localContext.setAuthCache(authCache); resp = client.execute(method, localContext); } else { @@ -292,9 +278,8 @@ public HTTPResponse get(URL url, Map headers) throws IOException if (200 != response.getStatusCode()) { getMethod.releaseConnection(); - throw new IOException( - "Server returned HTTP error code %d for URL %s" - .formatted(response.getStatusCode(), url.toExternalForm())); + throw new IOException("Server returned HTTP error code %d for URL %s" + .formatted(response.getStatusCode(), url.toExternalForm())); } return response; } @@ -313,10 +298,9 @@ public int getConnectTimeout() { @Override public void setConnectTimeout(int connectTimeout) { - connectionConfig = - RequestConfig.copy(connectionConfig) - .setConnectionRequestTimeout((int) ofSeconds(connectTimeout).toMillis()) - .build(); + connectionConfig = RequestConfig.copy(connectionConfig) + .setConnectionRequestTimeout((int) ofSeconds(connectTimeout).toMillis()) + .build(); } @Override @@ -326,10 +310,9 @@ public int getReadTimeout() { @Override public void setReadTimeout(int readTimeout) { - connectionConfig = - RequestConfig.copy(connectionConfig) - .setSocketTimeout((int) ofSeconds(readTimeout).toMillis()) - .build(); + connectionConfig = RequestConfig.copy(connectionConfig) + .setSocketTimeout((int) ofSeconds(readTimeout).toMillis()) + .build(); } @Override diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/SpringEnvironmentAwareGeoToolsHttpClientFactory.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/SpringEnvironmentAwareGeoToolsHttpClientFactory.java index fe71f5e34..df36b5a44 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/SpringEnvironmentAwareGeoToolsHttpClientFactory.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/geotools/SpringEnvironmentAwareGeoToolsHttpClientFactory.java @@ -4,15 +4,13 @@ */ package org.geoserver.cloud.autoconfigure.geotools; +import java.util.List; import lombok.AccessLevel; import lombok.Setter; - import org.geotools.http.AbstractHTTPClientFactory; import org.geotools.http.HTTPBehavior; import org.geotools.http.HTTPClient; -import java.util.List; - /** */ public class SpringEnvironmentAwareGeoToolsHttpClientFactory extends AbstractHTTPClientFactory { diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/CatalogMetrics.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/CatalogMetrics.java index 7a76d7b6a..9c5a6a720 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/CatalogMetrics.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/CatalogMetrics.java @@ -7,18 +7,15 @@ import io.micrometer.core.instrument.Gauge; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.binder.MeterBinder; - +import java.util.function.Supplier; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.Catalog; import org.geoserver.config.GeoServer; import org.geoserver.config.GeoServerInfo; import org.geoserver.platform.config.UpdateSequence; -import java.util.function.Supplier; - /** * Registers GeoServer {@link Catalog catalog} and {@link GeoServer config} metrics to be exported * by micrometer's {@link MeterRegistry}. @@ -71,28 +68,25 @@ public void bindTo(@NonNull MeterRegistry registry) { } } - private void registerObservedUpdateSequence( - MeterRegistry registry, final String instanceIdTag) { + private void registerObservedUpdateSequence(MeterRegistry registry, final String instanceIdTag) { Supplier updateSequence = () -> config.getGlobal().getUpdateSequence(); - Gauge.Builder> updateSeqBuilder = - Gauge.builder("geoserver.config.update_sequence", updateSequence) - .description("GeoServer configuration update sequence") - .baseUnit("sequence"); + Gauge.Builder> updateSeqBuilder = Gauge.builder( + "geoserver.config.update_sequence", updateSequence) + .description("GeoServer configuration update sequence") + .baseUnit("sequence"); - if (null != instanceIdTag) - updateSeqBuilder = updateSeqBuilder.tag("instance-id", instanceIdTag); + if (null != instanceIdTag) updateSeqBuilder = updateSeqBuilder.tag("instance-id", instanceIdTag); updateSeqBuilder.register(registry); } private void registerUpdateSequence(MeterRegistry registry, final String instanceIdTag) { Supplier updateSequence = realUpdateSequence::currValue; - Gauge.Builder> updateSeqBuilder = - Gauge.builder("geoserver.config.update_sequence.real", updateSequence) - .description("Cluster-wide, canonical update sequence value") - .baseUnit("sequence"); + Gauge.Builder> updateSeqBuilder = Gauge.builder( + "geoserver.config.update_sequence.real", updateSequence) + .description("Cluster-wide, canonical update sequence value") + .baseUnit("sequence"); - if (null != instanceIdTag) - updateSeqBuilder = updateSeqBuilder.tag("instance-id", instanceIdTag); + if (null != instanceIdTag) updateSeqBuilder = updateSeqBuilder.tag("instance-id", instanceIdTag); updateSeqBuilder.register(registry); } } diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/CatalogMetricsAutoConfiguration.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/CatalogMetricsAutoConfiguration.java index 5e1c80c9f..4ff109539 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/CatalogMetricsAutoConfiguration.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/CatalogMetricsAutoConfiguration.java @@ -5,9 +5,7 @@ package org.geoserver.cloud.autoconfigure.metrics.catalog; import io.micrometer.core.annotation.Timed; - import lombok.NonNull; - import org.geoserver.catalog.Catalog; import org.geoserver.config.GeoServer; import org.geoserver.platform.config.UpdateSequence; @@ -27,8 +25,7 @@ * @see CatalogMetrics * @since 1.0 */ -@AutoConfiguration( - after = {MetricsAutoConfiguration.class, CompositeMeterRegistryAutoConfiguration.class}) +@AutoConfiguration(after = {MetricsAutoConfiguration.class, CompositeMeterRegistryAutoConfiguration.class}) @ConditionalOnClass(Timed.class) @ConditionalOnGeoServerMetricsEnabled @EnableConfigurationProperties(GeoSeverMetricsConfigProperties.class) diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/ConditionalOnGeoServerMetricsEnabled.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/ConditionalOnGeoServerMetricsEnabled.java index 89846ac49..c3f9af50d 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/ConditionalOnGeoServerMetricsEnabled.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/ConditionalOnGeoServerMetricsEnabled.java @@ -6,16 +6,14 @@ import io.micrometer.core.annotation.Timed; import io.micrometer.core.instrument.MeterRegistry; - -import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.boot.actuate.autoconfigure.metrics.MetricsAutoConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; /** * Groups conditions that shall be met to enable geoserver metrics diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/GeoSeverMetricsConfigProperties.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/GeoSeverMetricsConfigProperties.java index f8ae5566f..1afa52a40 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/GeoSeverMetricsConfigProperties.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/GeoSeverMetricsConfigProperties.java @@ -6,7 +6,6 @@ package org.geoserver.cloud.autoconfigure.metrics.catalog; import lombok.Data; - import org.springframework.boot.context.properties.ConfigurationProperties; /** diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/MetricsCatalogListener.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/MetricsCatalogListener.java index d7439ec96..bad57ecc1 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/MetricsCatalogListener.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/metrics/catalog/MetricsCatalogListener.java @@ -8,9 +8,8 @@ import io.micrometer.core.instrument.Counter.Builder; import io.micrometer.core.instrument.MeterRegistry; import io.micrometer.core.instrument.binder.BaseUnits; - +import javax.annotation.Nullable; import lombok.NonNull; - import org.geoserver.catalog.CatalogException; import org.geoserver.catalog.event.CatalogAddEvent; import org.geoserver.catalog.event.CatalogListener; @@ -18,8 +17,6 @@ import org.geoserver.catalog.event.CatalogPostModifyEvent; import org.geoserver.catalog.event.CatalogRemoveEvent; -import javax.annotation.Nullable; - class MetricsCatalogListener implements CatalogListener { private final Counter added; @@ -29,33 +26,25 @@ class MetricsCatalogListener implements CatalogListener { public MetricsCatalogListener(@NonNull MeterRegistry registry, @Nullable String instanceId) { - added = - counter("geoserver.catalog.added", instanceId) - .description( - "Number of CatalogInfo objects added to this instance's Catalog") - .register(registry); - removed = - counter("geoserver.catalog.removed", instanceId) - .description( - "Number of CatalogInfo objects removed on this instance's Catalog") - .register(registry); - modified = - counter("geoserver.catalog.modified", instanceId) - .description( - "Number of modifications to CatalogInfo objects on this instance's Catalog") - .register(registry); + added = counter("geoserver.catalog.added", instanceId) + .description("Number of CatalogInfo objects added to this instance's Catalog") + .register(registry); + removed = counter("geoserver.catalog.removed", instanceId) + .description("Number of CatalogInfo objects removed on this instance's Catalog") + .register(registry); + modified = counter("geoserver.catalog.modified", instanceId) + .description("Number of modifications to CatalogInfo objects on this instance's Catalog") + .register(registry); - reloads = - Counter.builder("geoserver.catalog.reloads") - .description("Times the Catalog has been reloaded") - .baseUnit(BaseUnits.OPERATIONS) - .register(registry); + reloads = Counter.builder("geoserver.catalog.reloads") + .description("Times the Catalog has been reloaded") + .baseUnit(BaseUnits.OPERATIONS) + .register(registry); } private Counter.Builder counter(String name, String instanceId) { - Builder builder = - Counter.builder(name) // - .baseUnit(BaseUnits.OPERATIONS); + Builder builder = Counter.builder(name) // + .baseUnit(BaseUnits.OPERATIONS); if (null != instanceId) builder = builder.tag("instance-id", instanceId); return builder; } diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/security/ConditionalOnGeoServerSecurityDisabled.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/security/ConditionalOnGeoServerSecurityDisabled.java index 11308c208..f67618497 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/security/ConditionalOnGeoServerSecurityDisabled.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/security/ConditionalOnGeoServerSecurityDisabled.java @@ -4,20 +4,15 @@ */ package org.geoserver.cloud.autoconfigure.security; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) @Documented -@ConditionalOnProperty( - prefix = "geoserver.security", - name = "enabled", - havingValue = "false", - matchIfMissing = false) +@ConditionalOnProperty(prefix = "geoserver.security", name = "enabled", havingValue = "false", matchIfMissing = false) public @interface ConditionalOnGeoServerSecurityDisabled {} diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/security/ConditionalOnGeoServerSecurityEnabled.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/security/ConditionalOnGeoServerSecurityEnabled.java index 7c9442841..aed19cc8e 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/security/ConditionalOnGeoServerSecurityEnabled.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/security/ConditionalOnGeoServerSecurityEnabled.java @@ -4,20 +4,15 @@ */ package org.geoserver.cloud.autoconfigure.security; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) @Documented -@ConditionalOnProperty( - prefix = "geoserver.security", - name = "enabled", - havingValue = "true", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "geoserver.security", name = "enabled", havingValue = "true", matchIfMissing = true) public @interface ConditionalOnGeoServerSecurityEnabled {} diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/security/GeoServerSecurityAutoConfiguration.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/security/GeoServerSecurityAutoConfiguration.java index 0840a9f18..566980f97 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/security/GeoServerSecurityAutoConfiguration.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/autoconfigure/security/GeoServerSecurityAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.security; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.autoconfigure.catalog.backend.core.GeoServerBackendAutoConfiguration; import org.geoserver.cloud.event.security.SecurityConfigChanged; import org.geoserver.cloud.security.GeoServerSecurityConfiguration; @@ -18,13 +18,8 @@ import org.springframework.context.annotation.Import; import org.springframework.context.event.EventListener; -import javax.annotation.PostConstruct; - @AutoConfiguration(after = GeoServerBackendAutoConfiguration.class) -@Import({ - GeoServerSecurityAutoConfiguration.WhenEnabled.class, - GeoServerSecurityAutoConfiguration.WhenDisabled.class -}) +@Import({GeoServerSecurityAutoConfiguration.WhenEnabled.class, GeoServerSecurityAutoConfiguration.WhenDisabled.class}) @Slf4j(topic = "org.geoserver.cloud.autoconfigure.security") public class GeoServerSecurityAutoConfiguration { diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/config/catalog/backend/core/CatalogProperties.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/config/catalog/backend/core/CatalogProperties.java index 92f5a14c6..8a8cd5bc7 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/config/catalog/backend/core/CatalogProperties.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/config/catalog/backend/core/CatalogProperties.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.config.catalog.backend.core; import lombok.Data; - import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties(prefix = "geoserver.catalog") diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/config/catalog/backend/core/CoreBackendConfiguration.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/config/catalog/backend/core/CoreBackendConfiguration.java index fbe321df0..f2683f504 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/config/catalog/backend/core/CoreBackendConfiguration.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/config/catalog/backend/core/CoreBackendConfiguration.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.config.catalog.backend.core; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.LayerGroupVisibilityPolicy; import org.geoserver.catalog.impl.AdvertisedCatalog; @@ -82,8 +81,7 @@ CatalogPlugin rawCatalog( @DependsOn({"extensions", "dataDirectory", "accessRulesDao"}) @ConditionalOnGeoServerSecurityEnabled @Bean - Catalog secureCatalog(@Qualifier("rawCatalog") Catalog rawCatalog, CatalogProperties properties) - throws Exception { + Catalog secureCatalog(@Qualifier("rawCatalog") Catalog rawCatalog, CatalogProperties properties) throws Exception { if (properties.isSecure()) return new SecureCatalogImpl(rawCatalog); return rawCatalog; } @@ -108,8 +106,7 @@ DefaultResourceAccessManager defaultResourceAccessManager( // @Qualifier("rawCatalog") Catalog rawCatalog, LayerGroupContainmentCache layerGroupContainmentCache) { - DefaultResourceAccessManager accessManager = - new DefaultResourceAccessManager(dao, rawCatalog); + DefaultResourceAccessManager accessManager = new DefaultResourceAccessManager(dao, rawCatalog); accessManager.setGroupsCache(layerGroupContainmentCache); return accessManager; } @@ -126,8 +123,7 @@ DefaultResourceAccessManager defaultResourceAccessManager( // name = "geoserver.security.layergroup-containmentcache", havingValue = "true", matchIfMissing = false) - LayerGroupContainmentCache enabledLayerGroupContainmentCache( - @Qualifier("rawCatalog") Catalog rawCatalog) { + LayerGroupContainmentCache enabledLayerGroupContainmentCache(@Qualifier("rawCatalog") Catalog rawCatalog) { log.info("using {}", GsCloudLayerGroupContainmentCache.class.getSimpleName()); return new GsCloudLayerGroupContainmentCache(rawCatalog); @@ -162,8 +158,7 @@ Catalog secureCatalogDisabled(@Qualifier("rawCatalog") Catalog rawCatalog) { * {@code secureCatalog} otherwise. */ @Bean - Catalog advertisedCatalog( - @Qualifier("secureCatalog") Catalog secureCatalog, CatalogProperties properties) { + Catalog advertisedCatalog(@Qualifier("secureCatalog") Catalog secureCatalog, CatalogProperties properties) { if (properties.isAdvertised()) { AdvertisedCatalog advertisedCatalog = new AdvertisedCatalog(secureCatalog); advertisedCatalog.setLayerGroupVisibilityPolicy(LayerGroupVisibilityPolicy.HIDE_NEVER); @@ -178,18 +173,14 @@ Catalog advertisedCatalog( */ @Bean(name = {"catalog", "localWorkspaceCatalog"}) Catalog localWorkspaceCatalog( - @Qualifier("advertisedCatalog") Catalog advertisedCatalog, - CatalogProperties properties) { - return properties.isLocalWorkspace() - ? new LocalWorkspaceCatalog(advertisedCatalog) - : advertisedCatalog; + @Qualifier("advertisedCatalog") Catalog advertisedCatalog, CatalogProperties properties) { + return properties.isLocalWorkspace() ? new LocalWorkspaceCatalog(advertisedCatalog) : advertisedCatalog; } @ConditionalOnMissingBean(GeoServerImpl.class) @Bean(name = "geoServer") GeoServerImpl geoServer( - @Qualifier("catalog") Catalog catalog, - @Qualifier("geoserverFacade") GeoServerFacade facade) { + @Qualifier("catalog") Catalog catalog, @Qualifier("geoserverFacade") GeoServerFacade facade) { GeoServerImpl gs = new GeoServerImpl(facade); gs.setCatalog(catalog); return gs; diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/event/remote/lifecycle/LifecycleEventProcessor.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/event/remote/lifecycle/LifecycleEventProcessor.java index 95daeacf3..33e6f92ff 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/event/remote/lifecycle/LifecycleEventProcessor.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/event/remote/lifecycle/LifecycleEventProcessor.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.event.remote.lifecycle; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.config.catalog.events.CatalogApplicationEventPublisher; import org.geoserver.cloud.event.GeoServerEvent; import org.geoserver.cloud.event.lifecycle.ReloadEvent; diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/event/remote/resourcepool/RemoteEventResourcePoolProcessor.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/event/remote/resourcepool/RemoteEventResourcePoolProcessor.java index fd87aa1bb..85ffac686 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/event/remote/resourcepool/RemoteEventResourcePoolProcessor.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/event/remote/resourcepool/RemoteEventResourcePoolProcessor.java @@ -6,8 +6,8 @@ import static java.util.Optional.ofNullable; +import java.util.Optional; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.ResourceInfo; @@ -24,8 +24,6 @@ import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; -import java.util.Optional; - /** * Cleans up cached {@link ResourcePool} entries upon remote {@link CatalogInfoAdded}s, {@link * CatalogInfoModified}s, and {@link CatalogInfoRemoved}s. @@ -58,18 +56,14 @@ public void onCatalogRemoteAddEvent(CatalogInfoAdded event) { @Order(Ordered.HIGHEST_PRECEDENCE) public void onCatalogRemoteRemoveEvent(CatalogInfoRemoved event) { event.remote() - .ifPresentOrElse( - this::evictFromResourcePool, - () -> log.trace("Ignoring event from self: {}", event)); + .ifPresentOrElse(this::evictFromResourcePool, () -> log.trace("Ignoring event from self: {}", event)); } @EventListener(CatalogInfoModified.class) @Order(Ordered.HIGHEST_PRECEDENCE) public void onCatalogRemoteModifyEvent(CatalogInfoModified event) { event.remote() - .ifPresentOrElse( - this::evictFromResourcePool, - () -> log.trace("Ignoring event from self: {}", event)); + .ifPresentOrElse(this::evictFromResourcePool, () -> log.trace("Ignoring event from self: {}", event)); } private void evictFromResourcePool(InfoEvent event) { @@ -99,10 +93,6 @@ private void evictFromResourcePool(InfoEvent event) { CacheClearingListener cleaner = new CacheClearingListener(resourcePool); object.accept(cleaner); }, // - () -> - log.debug( - "{}({}) not found, unable to clean up its ResourcePool cache entry", - infoType, - id)); + () -> log.debug("{}({}) not found, unable to clean up its ResourcePool cache entry", infoType, id)); } } diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/security/CloudGeoServerSecurityManager.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/security/CloudGeoServerSecurityManager.java index cdcfe28bd..a11ed176d 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/security/CloudGeoServerSecurityManager.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/security/CloudGeoServerSecurityManager.java @@ -4,9 +4,14 @@ */ package org.geoserver.cloud.security; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; +import java.util.function.Supplier; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.event.security.SecurityConfigChanged; import org.geoserver.config.GeoServerDataDirectory; import org.geoserver.security.GeoServerSecurityManager; @@ -22,13 +27,6 @@ import org.springframework.context.event.EventListener; import org.springframework.security.authentication.AuthenticationProvider; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Consumer; -import java.util.function.Supplier; - /** * Extends {@link GeoServerSecurityManager} to {@link #fireRemoteChangedEvent(String) notify} other * services of changes to the security configuration happened on the currently running service, and @@ -91,9 +89,7 @@ public void onRemoteSecurityConfigChangeEvent(SecurityConfigChanged event) { return; } if (!isInitialized()) { - log.info( - "Ignoring security config change event, security subsystem not yet initialized: {}", - event); + log.info("Ignoring security config change event, security subsystem not yet initialized: {}", event); return; } log.info("Reloading security configuration due to change event: {}", event); @@ -113,16 +109,14 @@ public void fireRemoteChangedEvent(@NonNull String reason) { /** Override to {@link #fireChanged fire} a remote {@link SecurityConfigChanged} */ @Override - public void saveRoleService(SecurityRoleServiceConfig config) - throws IOException, SecurityConfigException { + public void saveRoleService(SecurityRoleServiceConfig config) throws IOException, SecurityConfigException { super.saveRoleService(config); fireRemoteChangedEvent("SecurityRoleServiceConfig changed"); } /** Override to {@link #fireChanged fire} a remote {@link SecurityConfigChanged} */ @Override - public void savePasswordPolicy(PasswordPolicyConfig config) - throws IOException, SecurityConfigException { + public void savePasswordPolicy(PasswordPolicyConfig config) throws IOException, SecurityConfigException { super.savePasswordPolicy(config); fireRemoteChangedEvent("PasswordPolicyConfig changed"); } @@ -145,8 +139,7 @@ public void saveAuthenticationProvider(SecurityAuthProviderConfig config) /** Override to {@link #fireChanged fire} a remote {@link SecurityConfigChanged} */ @Override - public void saveFilter(SecurityNamedServiceConfig config) - throws IOException, SecurityConfigException { + public void saveFilter(SecurityNamedServiceConfig config) throws IOException, SecurityConfigException { super.saveFilter(config); fireRemoteChangedEvent("SecurityNamedServiceConfig changed"); } @@ -161,10 +154,7 @@ public synchronized void saveSecurityConfig(SecurityManagerConfig config) throws /** Override to {@link #fireChanged fire} a remote {@link SecurityConfigChanged} */ @Override public synchronized void saveMasterPasswordConfig( - MasterPasswordConfig config, - char[] currPasswd, - char[] newPasswd, - char[] newPasswdConfirm) + MasterPasswordConfig config, char[] currPasswd, char[] newPasswd, char[] newPasswdConfirm) throws Exception { super.saveMasterPasswordConfig(config, currPasswd, newPasswd, newPasswdConfirm); fireRemoteChangedEvent("MasterPasswordConfig changed"); diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/security/EnvironmentAdminAuthenticationProvider.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/security/EnvironmentAdminAuthenticationProvider.java index 2e83c11da..de2869d6d 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/security/EnvironmentAdminAuthenticationProvider.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/security/EnvironmentAdminAuthenticationProvider.java @@ -6,8 +6,9 @@ import static org.springframework.util.StringUtils.hasText; +import java.util.List; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.security.impl.GeoServerRole; import org.geoserver.security.impl.GeoServerUser; import org.springframework.beans.BeanInstantiationException; @@ -23,10 +24,6 @@ import org.springframework.security.core.GrantedAuthority; import org.springframework.util.StringUtils; -import java.util.List; - -import javax.annotation.PostConstruct; - /** * {@link AuthenticationProvider} that allows to set an administrator account (username and * password) through {@link Environment} properties {@code ${geoserver.admin.username:admin}} and @@ -90,10 +87,7 @@ void validateConfig() { } public static List adminRoles() { - return List.of( - new GeoServerRole("ADMIN"), - GeoServerRole.ADMIN_ROLE, - GeoServerRole.AUTHENTICATED_ROLE); + return List.of(new GeoServerRole("ADMIN"), GeoServerRole.ADMIN_ROLE, GeoServerRole.AUTHENTICATED_ROLE); } @Override @@ -138,14 +132,12 @@ public Authentication authenticate(Authentication token) throws AuthenticationEx if (expectedPassword.equals(pwd)) { List adminRoles = adminRoles(); UsernamePasswordAuthenticationToken authenticated = - UsernamePasswordAuthenticationToken.authenticated( - expectedName, null, adminRoles); + UsernamePasswordAuthenticationToken.authenticated(expectedName, null, adminRoles); authenticated.setDetails(token.getDetails()); return authenticated; } // this breaks the cycle through other providers, as opposed to // BadCredentialsException - throw new InternalAuthenticationServiceException( - "Bad credentials for: %s".formatted(token.getPrincipal())); + throw new InternalAuthenticationServiceException("Bad credentials for: %s".formatted(token.getPrincipal())); } } diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/security/GeoServerSecurityConfiguration.java b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/security/GeoServerSecurityConfiguration.java index 7a4dc206b..7641b16c7 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/cloud/security/GeoServerSecurityConfiguration.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/cloud/security/GeoServerSecurityConfiguration.java @@ -4,8 +4,11 @@ */ package org.geoserver.cloud.security; +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Supplier; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.autoconfigure.security.ConditionalOnGeoServerSecurityEnabled; import org.geoserver.cloud.config.factory.FilteringXmlBeanDefinitionReader; import org.geoserver.cloud.event.security.SecurityConfigChanged; @@ -21,12 +24,6 @@ import org.springframework.context.annotation.DependsOn; import org.springframework.context.annotation.ImportResource; -import java.util.List; -import java.util.function.Consumer; -import java.util.function.Supplier; - -import javax.annotation.PostConstruct; - /** * Loads geoserver security bean definitions from {@code * classpath*:/applicationSecurityContext.xml}. @@ -58,8 +55,7 @@ public class GeoServerSecurityConfiguration { private @Value("${geoserver.security.enabled:#{null}}") Boolean enabled; public @PostConstruct void log() { - log.info( - "GeoServer security being configured through classpath*:/applicationSecurityContext.xml"); + log.info("GeoServer security being configured through classpath*:/applicationSecurityContext.xml"); } @Bean @@ -87,7 +83,6 @@ CloudGeoServerSecurityManager cloudAuthenticationManager( // Consumer publisher = localContextPublisher::publishEvent; Supplier updateSequenceIncrementor = updateSequence::nextValue; - return new CloudGeoServerSecurityManager( - dataDir, publisher, updateSequenceIncrementor, List.of(envAuth)); + return new CloudGeoServerSecurityManager(dataDir, publisher, updateSequenceIncrementor, List.of(envAuth)); } } diff --git a/src/catalog/backends/common/src/main/java/org/geoserver/security/impl/GsCloudLayerGroupContainmentCache.java b/src/catalog/backends/common/src/main/java/org/geoserver/security/impl/GsCloudLayerGroupContainmentCache.java index cbb06a4d8..56afdb6bb 100644 --- a/src/catalog/backends/common/src/main/java/org/geoserver/security/impl/GsCloudLayerGroupContainmentCache.java +++ b/src/catalog/backends/common/src/main/java/org/geoserver/security/impl/GsCloudLayerGroupContainmentCache.java @@ -6,10 +6,16 @@ import com.google.common.base.Stopwatch; import com.google.common.collect.Maps; - +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.concurrent.CompletableFuture; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogException; import org.geoserver.catalog.CatalogInfo; @@ -33,15 +39,6 @@ import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.web.context.WebApplicationContext; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.CompletableFuture; - /** * Alternative to {@link LayerGroupContainmentCache} * @@ -71,8 +68,7 @@ */ @Slf4j @SuppressWarnings({"java:S2177", "java:S6201", "java:S3776", "java:S3398"}) -public class GsCloudLayerGroupContainmentCache extends LayerGroupContainmentCache - implements ApplicationContextAware { +public class GsCloudLayerGroupContainmentCache extends LayerGroupContainmentCache implements ApplicationContextAware { private Catalog rawCatalog; private ApplicationContext applicationContext; @@ -146,7 +142,9 @@ private void doBuildLayerGroupCaches() { sw, groupCache.size(), resourceContainmentCache.size(), - resourceContainmentCache.values().stream().flatMap(Set::stream).count()); + resourceContainmentCache.values().stream() + .flatMap(Set::stream) + .count()); } private LayerGroupSummary createGroupInfo(LayerGroupInfo group, LayerGroupSummary groupData) { @@ -162,8 +160,7 @@ private void registerContainedGroups(LayerGroupInfo group, LayerGroupSummary gro .forEach(p -> registerContainerGroup(groupData, p)); } - private void registerContainerGroup( - LayerGroupSummary container, LayerGroupInfo containedGroup) { + private void registerContainerGroup(LayerGroupSummary container, LayerGroupInfo containedGroup) { LayerGroupSummary contained = getGroupData(containedGroup); if (container != null && contained != null) { contained.containerGroups.add(container); @@ -171,10 +168,7 @@ private void registerContainerGroup( } private void addGroupInfo(LayerGroupInfo lg, LayerGroupSummary groupData) { - lg.getLayers().stream() - .filter(IS_LAYER) - .map(LayerInfo.class::cast) - .forEach(p -> addGroupInfo(groupData, p)); + lg.getLayers().stream().filter(IS_LAYER).map(LayerInfo.class::cast).forEach(p -> addGroupInfo(groupData, p)); } private void addGroupInfo(LayerGroupSummary groupData, LayerInfo containedLayer) { @@ -329,7 +323,8 @@ private void handleNameChange(CatalogModifyEvent event, LayerGroupSummary summar private void handleWorkspaceChange(CatalogModifyEvent event, LayerGroupSummary summary) { int wsIdx = event.getPropertyNames().indexOf("workspace"); if (wsIdx != -1) { - WorkspaceInfo newWorkspace = (WorkspaceInfo) event.getNewValues().get(wsIdx); + WorkspaceInfo newWorkspace = + (WorkspaceInfo) event.getNewValues().get(wsIdx); summary.workspace = newWorkspace == null ? null : newWorkspace.getName(); } } @@ -357,9 +352,7 @@ private void handleModeChange(CatalogModifyEvent event, LayerGroupSummary summar } private void updateContainedLayers( - @NonNull LayerGroupSummary groupSummary, - List oldLayers, - List newLayers) { + @NonNull LayerGroupSummary groupSummary, List oldLayers, List newLayers) { // do not rely on PublishedInfo.equals()... var difference = Maps.difference(toIdMap(oldLayers), toIdMap(newLayers)); diff --git a/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/LifecycleEventAutoConfigurationTest.java b/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/LifecycleEventAutoConfigurationTest.java index 893bcb287..aef51a25f 100644 --- a/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/LifecycleEventAutoConfigurationTest.java +++ b/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/LifecycleEventAutoConfigurationTest.java @@ -15,25 +15,18 @@ class LifecycleEventAutoConfigurationTest { - private final ApplicationContextRunner runner = - new ApplicationContextRunner() - .withBean("geoServer", GeoServerImpl.class) - .withConfiguration( - AutoConfigurations.of(LifecycleEventAutoConfiguration.class)); + private final ApplicationContextRunner runner = new ApplicationContextRunner() + .withBean("geoServer", GeoServerImpl.class) + .withConfiguration(AutoConfigurations.of(LifecycleEventAutoConfiguration.class)); @Test void testDefaultAppContextContributions() { - runner.run( - context -> assertThat(context).hasNotFailed().hasBean("lifecycleEventProcessor")); + runner.run(context -> assertThat(context).hasNotFailed().hasBean("lifecycleEventProcessor")); } @Test void whenDependentClassesAreNotPresent_thenBeanMissing() { runner.withClassLoader(new FilteredClassLoader(LifecycleEvent.class)) - .run( - context -> - assertThat(context) - .hasNotFailed() - .doesNotHaveBean("lifecycleEventProcessor")); + .run(context -> assertThat(context).hasNotFailed().doesNotHaveBean("lifecycleEventProcessor")); } } diff --git a/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/RemoteEventResourcePoolCleanupUpAutoConfigurationTest.java b/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/RemoteEventResourcePoolCleanupUpAutoConfigurationTest.java index 2d0c8eddf..359e478b4 100644 --- a/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/RemoteEventResourcePoolCleanupUpAutoConfigurationTest.java +++ b/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/core/RemoteEventResourcePoolCleanupUpAutoConfigurationTest.java @@ -15,29 +15,18 @@ class RemoteEventResourcePoolCleanupUpAutoConfigurationTest { - private final ApplicationContextRunner runner = - new ApplicationContextRunner() - .withBean("rawCatalog", CatalogPlugin.class) - .withConfiguration( - AutoConfigurations.of( - RemoteEventResourcePoolCleanupUpAutoConfiguration.class)); + private final ApplicationContextRunner runner = new ApplicationContextRunner() + .withBean("rawCatalog", CatalogPlugin.class) + .withConfiguration(AutoConfigurations.of(RemoteEventResourcePoolCleanupUpAutoConfiguration.class)); @Test void testDefaultAppContextContributions() { - runner.run( - context -> - assertThat(context) - .hasNotFailed() - .hasBean("remoteEventResourcePoolProcessor")); + runner.run(context -> assertThat(context).hasNotFailed().hasBean("remoteEventResourcePoolProcessor")); } @Test void whenDependentClassesAreNotPresent_thenBeanMissing() { runner.withClassLoader(new FilteredClassLoader(InfoEvent.class)) - .run( - context -> - assertThat(context) - .hasNotFailed() - .doesNotHaveBean("remoteEventResourcePoolProcessor")); + .run(context -> assertThat(context).hasNotFailed().doesNotHaveBean("remoteEventResourcePoolProcessor")); } } diff --git a/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/geotools/GeoToolsHttpClientAutoConfigurationTest.java b/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/geotools/GeoToolsHttpClientAutoConfigurationTest.java index 6d209911c..e175c72c6 100644 --- a/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/geotools/GeoToolsHttpClientAutoConfigurationTest.java +++ b/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/geotools/GeoToolsHttpClientAutoConfigurationTest.java @@ -20,11 +20,9 @@ */ class GeoToolsHttpClientAutoConfigurationTest { - private WebApplicationContextRunner runner = - new WebApplicationContextRunner() // - .withInitializer(new GeoToolsStaticContextInitializer()) // - .withConfiguration( - AutoConfigurations.of(GeoToolsHttpClientAutoConfiguration.class)); + private WebApplicationContextRunner runner = new WebApplicationContextRunner() // + .withInitializer(new GeoToolsStaticContextInitializer()) // + .withConfiguration(AutoConfigurations.of(GeoToolsHttpClientAutoConfiguration.class)); private final String forceXYSystemProperty = "org.geotools.referencing.forceXY"; @@ -36,27 +34,22 @@ void clearSystemPropertiesAndGeoToolsHints() { @Test void enabledByDefault() { - runner.run( - context -> { - assertThat(context) - .hasSingleBean(GeoToolsHttpClientProxyConfigurationProperties.class); - assertThat(context) - .hasSingleBean(SpringEnvironmentAwareGeoToolsHttpClientFactory.class); - assertThat( - context.getBean( - GeoToolsHttpClientProxyConfigurationProperties.class)) - .hasFieldOrPropertyWithValue("enabled", true); + runner.run(context -> { + assertThat(context).hasSingleBean(GeoToolsHttpClientProxyConfigurationProperties.class); + assertThat(context).hasSingleBean(SpringEnvironmentAwareGeoToolsHttpClientFactory.class); + assertThat(context.getBean(GeoToolsHttpClientProxyConfigurationProperties.class)) + .hasFieldOrPropertyWithValue("enabled", true); - HTTPClient client = HTTPClientFinder.createClient(); - assertThat(client) - .as( - """ + HTTPClient client = HTTPClientFinder.createClient(); + assertThat(client) + .as( + """ Expected SpringEnvironmentAwareGeoToolsHttpClient \ after GeoToolsStaticContextInitializer sets \ SpringEnvironmentAwareGeoToolsHttpClientFactory as the default factory """) - .isInstanceOf(SpringEnvironmentAwareGeoToolsHttpClient.class); - }); + .isInstanceOf(SpringEnvironmentAwareGeoToolsHttpClient.class); + }); } @Test @@ -71,23 +64,17 @@ void testInitializerSetsHttpClientFactorySystemProperty() { final var expected = SpringEnvironmentAwareGeoToolsHttpClientFactory.class; assertNull(Hints.getSystemDefault(Hints.HTTP_CLIENT_FACTORY)); - runner.run( - context -> - assertThat(Hints.getSystemDefault(Hints.HTTP_CLIENT_FACTORY)) - .isEqualTo(expected)); + runner.run(context -> + assertThat(Hints.getSystemDefault(Hints.HTTP_CLIENT_FACTORY)).isEqualTo(expected)); Hints.removeSystemDefault(Hints.HTTP_CLIENT_FACTORY); runner.withPropertyValues("geotools.httpclient.proxy.enabled: true") - .run( - context -> - assertThat(Hints.getSystemDefault(Hints.HTTP_CLIENT_FACTORY)) - .isEqualTo(expected)); + .run(context -> assertThat(Hints.getSystemDefault(Hints.HTTP_CLIENT_FACTORY)) + .isEqualTo(expected)); Hints.removeSystemDefault(Hints.HTTP_CLIENT_FACTORY); runner.withPropertyValues("geotools.httpclient.proxy.enabled: false") - .run( - context -> - assertThat(Hints.getSystemDefault(Hints.HTTP_CLIENT_FACTORY)) - .isNull()); + .run(context -> assertThat(Hints.getSystemDefault(Hints.HTTP_CLIENT_FACTORY)) + .isNull()); } } diff --git a/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/security/EnvironmentAdminAuthenticationProviderTest.java b/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/security/EnvironmentAdminAuthenticationProviderTest.java index 020ca0bbb..4559b2bd3 100644 --- a/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/security/EnvironmentAdminAuthenticationProviderTest.java +++ b/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/security/EnvironmentAdminAuthenticationProviderTest.java @@ -7,6 +7,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertThrows; +import java.io.File; import org.geoserver.cloud.security.EnvironmentAdminAuthenticationProvider; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; @@ -19,8 +20,6 @@ import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.Authentication; -import java.io.File; - /** * {@link EnableAutoConfiguration @EnableAutoConfiguration} tests for {@link * GeoServerSecurityAutoConfiguration}'s {@link EnvironmentAdminAuthenticationProvider} @@ -29,7 +28,8 @@ */ class EnvironmentAdminAuthenticationProviderTest { - @TempDir File tempDir; + @TempDir + File tempDir; private ApplicationContextRunner runner; @@ -39,147 +39,122 @@ void setUp() { } @Test - @DisplayName( - "When username is set and password is not set Then FAILS to load the application context") + @DisplayName("When username is set and password is not set Then FAILS to load the application context") void fails_if_password_not_set() { runner.withPropertyValues( // USERNAME SET "geoserver.admin.username=myAdmin", // PASSWORD NOT SET "geoserver.admin.password=") - .run( - context -> { - assertThat(context) - .hasFailed() - .getFailure() - .hasMessageContaining( - "password not provided through config property geoserver.admin.password"); - }); + .run(context -> { + assertThat(context) + .hasFailed() + .getFailure() + .hasMessageContaining( + "password not provided through config property geoserver.admin.password"); + }); } @Test - @DisplayName( - "When password is set and username is not set Then FAILS to load the application context") + @DisplayName("When password is set and username is not set Then FAILS to load the application context") void fails_if_username_not_set() { runner.withPropertyValues( // USERNAME NOT SET "geoserver.admin.username=", // PASSWORD SET "geoserver.admin.password=s3cr3t") - .run( - context -> { - assertThat(context) - .hasFailed() - .getFailure() - .hasMessageContaining( - "admin username not provided through config property geoserver.admin.username"); - }); + .run(context -> { + assertThat(context) + .hasFailed() + .getFailure() + .hasMessageContaining( + "admin username not provided through config property geoserver.admin.username"); + }); } // success case with default admin user @Test - @DisplayName( - "When using default admin username and password matches Then returns an authenticated token") + @DisplayName("When using default admin username and password matches Then returns an authenticated token") void default_admin_and_password_matches() { - runner.withPropertyValues( - "geoserver.admin.username=admin", "geoserver.admin.password=s3cr3t") - .run( - context -> { - assertThat(context).hasNotFailed(); - Authentication token = userNamePasswordToken("admin", "s3cr3t"); - Authentication authenticated = - envAuthProvider(context).authenticate(token); - assertThat(authenticated) - .isInstanceOf(UsernamePasswordAuthenticationToken.class) - .isNotSameAs(token); - - assertThat(authenticated) - .as("should return a fully authenticated token") - .hasFieldOrPropertyWithValue("authenticated", true); - - assertThat(authenticated) - .as("should have the expected admin roles") - .hasFieldOrPropertyWithValue( - "authorities", - EnvironmentAdminAuthenticationProvider.adminRoles()); - }); + runner.withPropertyValues("geoserver.admin.username=admin", "geoserver.admin.password=s3cr3t") + .run(context -> { + assertThat(context).hasNotFailed(); + Authentication token = userNamePasswordToken("admin", "s3cr3t"); + Authentication authenticated = envAuthProvider(context).authenticate(token); + assertThat(authenticated) + .isInstanceOf(UsernamePasswordAuthenticationToken.class) + .isNotSameAs(token); + + assertThat(authenticated) + .as("should return a fully authenticated token") + .hasFieldOrPropertyWithValue("authenticated", true); + + assertThat(authenticated) + .as("should have the expected admin roles") + .hasFieldOrPropertyWithValue( + "authorities", EnvironmentAdminAuthenticationProvider.adminRoles()); + }); } // success case with a non default admin username @Test - @DisplayName( - "When NOT using default admin username and password matches Then returns an authenticated token") + @DisplayName("When NOT using default admin username and password matches Then returns an authenticated token") void non_default_admin_and_password_matches() { - runner.withPropertyValues( - "geoserver.admin.username=JohnTheAdmin", "geoserver.admin.password=s3cr3t") - .run( - context -> { - assertThat(context).hasNotFailed(); - Authentication token = userNamePasswordToken("JohnTheAdmin", "s3cr3t"); - Authentication authenticated = - envAuthProvider(context).authenticate(token); - assertThat(authenticated) - .isInstanceOf(UsernamePasswordAuthenticationToken.class) - .isNotSameAs(token); - - assertThat(authenticated) - .as("should return a fully authenticated token") - .hasFieldOrPropertyWithValue("authenticated", true); - - assertThat(authenticated) - .as("should have the expected admin roles") - .hasFieldOrPropertyWithValue( - "authorities", - EnvironmentAdminAuthenticationProvider.adminRoles()); - }); + runner.withPropertyValues("geoserver.admin.username=JohnTheAdmin", "geoserver.admin.password=s3cr3t") + .run(context -> { + assertThat(context).hasNotFailed(); + Authentication token = userNamePasswordToken("JohnTheAdmin", "s3cr3t"); + Authentication authenticated = envAuthProvider(context).authenticate(token); + assertThat(authenticated) + .isInstanceOf(UsernamePasswordAuthenticationToken.class) + .isNotSameAs(token); + + assertThat(authenticated) + .as("should return a fully authenticated token") + .hasFieldOrPropertyWithValue("authenticated", true); + + assertThat(authenticated) + .as("should have the expected admin roles") + .hasFieldOrPropertyWithValue( + "authorities", EnvironmentAdminAuthenticationProvider.adminRoles()); + }); } @Test - @DisplayName( - "When using default admin username and password does not match Then breaks the auth chain") + @DisplayName("When using default admin username and password does not match Then breaks the auth chain") void default_admin_bad_credentials() { - runner.withPropertyValues( - "geoserver.admin.username=admin", "geoserver.admin.password=s3cr3t") - .run( - context -> { - assertThat(context).hasNotFailed(); - Authentication token = userNamePasswordToken("admin", "badPWD"); - EnvironmentAdminAuthenticationProvider envAuthProvider = - envAuthProvider(context); - - assertThrows( - InternalAuthenticationServiceException.class, - () -> envAuthProvider.authenticate(token)); - }); + runner.withPropertyValues("geoserver.admin.username=admin", "geoserver.admin.password=s3cr3t") + .run(context -> { + assertThat(context).hasNotFailed(); + Authentication token = userNamePasswordToken("admin", "badPWD"); + EnvironmentAdminAuthenticationProvider envAuthProvider = envAuthProvider(context); + + assertThrows( + InternalAuthenticationServiceException.class, () -> envAuthProvider.authenticate(token)); + }); } @Test @DisplayName("When not using admin as username Then the default admin username cannot be used") void if_configured_hides_default_admin() { - runner.withPropertyValues( - "geoserver.admin.username=MyCustomAdmin", "geoserver.admin.password=s3cr3t") - .run( - context -> { - assertThat(context).hasNotFailed(); - - Authentication defaultAdminCredentials = - userNamePasswordToken("admin", "geoserver"); - EnvironmentAdminAuthenticationProvider authProvider = - envAuthProvider(context); - assertThrows( - InternalAuthenticationServiceException.class, - () -> authProvider.authenticate(defaultAdminCredentials), - "The admin user should be disabled if geoserver.admin.username is set to another value"); - }); + runner.withPropertyValues("geoserver.admin.username=MyCustomAdmin", "geoserver.admin.password=s3cr3t") + .run(context -> { + assertThat(context).hasNotFailed(); + + Authentication defaultAdminCredentials = userNamePasswordToken("admin", "geoserver"); + EnvironmentAdminAuthenticationProvider authProvider = envAuthProvider(context); + assertThrows( + InternalAuthenticationServiceException.class, + () -> authProvider.authenticate(defaultAdminCredentials), + "The admin user should be disabled if geoserver.admin.username is set to another value"); + }); } - protected UsernamePasswordAuthenticationToken userNamePasswordToken( - String principal, String credentials) { + protected UsernamePasswordAuthenticationToken userNamePasswordToken(String principal, String credentials) { return new UsernamePasswordAuthenticationToken(principal, credentials); } - protected EnvironmentAdminAuthenticationProvider envAuthProvider( - AssertableApplicationContext context) { + protected EnvironmentAdminAuthenticationProvider envAuthProvider(AssertableApplicationContext context) { return context.getBean(EnvironmentAdminAuthenticationProvider.class); } } diff --git a/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/security/GeoServerSecurityAutoConfigurationTest.java b/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/security/GeoServerSecurityAutoConfigurationTest.java index 4153d2793..e41564561 100644 --- a/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/security/GeoServerSecurityAutoConfigurationTest.java +++ b/src/catalog/backends/common/src/test/java/org/geoserver/cloud/autoconfigure/security/GeoServerSecurityAutoConfigurationTest.java @@ -7,6 +7,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; +import java.io.File; +import java.util.List; import org.geoserver.catalog.Catalog; import org.geoserver.cloud.config.factory.FilteringXmlBeanDefinitionReader; import org.geoserver.cloud.security.CloudGeoServerSecurityManager; @@ -26,9 +28,6 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import java.io.File; -import java.util.List; - /** * {@link EnableAutoConfiguration @EnableAutoConfiguration} tests for {@link * GeoServerSecurityAutoConfiguration} @@ -37,7 +36,8 @@ */ class GeoServerSecurityAutoConfigurationTest { - @TempDir File tempDir; + @TempDir + File tempDir; private ApplicationContextRunner runner; @@ -70,12 +70,10 @@ static ApplicationContextRunner createContextRunner(File tempDir) { @Test void disabled() { runner.withPropertyValues("geoserver.security.enabled: false") // - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context) - .doesNotHaveBean(CloudGeoServerSecurityManager.class); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).doesNotHaveBean(CloudGeoServerSecurityManager.class); + }); } @Test @@ -89,24 +87,20 @@ void enabledExplicitly() { } private void testEnabled(ApplicationContextRunner runner) { - runner.run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).hasBean("authenticationManager"); - assertThat(context.getBean("authenticationManager")) - .isInstanceOf(CloudGeoServerSecurityManager.class); + runner.run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasBean("authenticationManager"); + assertThat(context.getBean("authenticationManager")).isInstanceOf(CloudGeoServerSecurityManager.class); - // gs-main's applicationSecurityContext.xml contributions - SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); - new FilteringXmlBeanDefinitionReader(registry) - .loadBeanDefinitions( - GeoServerSecurityConfiguration - .APPLICATION_SECURITY_CONTEXT_FILTER); - List names = List.of(registry.getBeanDefinitionNames()); - assertThat(names).isNotEmpty(); - for (String name : names) { - assertThat(context).hasBean(name); - } - }); + // gs-main's applicationSecurityContext.xml contributions + SimpleBeanDefinitionRegistry registry = new SimpleBeanDefinitionRegistry(); + new FilteringXmlBeanDefinitionReader(registry) + .loadBeanDefinitions(GeoServerSecurityConfiguration.APPLICATION_SECURITY_CONTEXT_FILTER); + List names = List.of(registry.getBeanDefinitionNames()); + assertThat(names).isNotEmpty(); + for (String name : names) { + assertThat(context).hasBean(name); + } + }); } } diff --git a/src/catalog/backends/common/src/test/java/org/geoserver/security/impl/GsCloudLayerGroupContainmentCacheTest.java b/src/catalog/backends/common/src/test/java/org/geoserver/security/impl/GsCloudLayerGroupContainmentCacheTest.java index 0d2600ca6..8bcc2a87e 100644 --- a/src/catalog/backends/common/src/test/java/org/geoserver/security/impl/GsCloudLayerGroupContainmentCacheTest.java +++ b/src/catalog/backends/common/src/test/java/org/geoserver/security/impl/GsCloudLayerGroupContainmentCacheTest.java @@ -14,6 +14,22 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import javax.xml.namespace.QName; import org.geoserver.catalog.CascadeDeleteVisitor; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogBuilder; @@ -44,24 +60,6 @@ import org.springframework.core.io.support.PathMatchingResourcePatternResolver; import org.springframework.web.context.WebApplicationContext; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.concurrent.TimeUnit; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import javax.xml.namespace.QName; - /** * Tests {@link LayerGroupContainmentCache} udpates in face of catalog setup and changes * @@ -85,7 +83,8 @@ class GsCloudLayerGroupContainmentCacheTest { private static Catalog catalog; - @TempDir static Path tmpDir; + @TempDir + static Path tmpDir; @BeforeAll public static void setupBaseCatalog() throws Exception { @@ -106,8 +105,7 @@ public static void setupBaseCatalog() throws Exception { String nsURI = catalog.getDefaultNamespace().getURI(); var resolver = new PathMatchingResourcePatternResolver(MockData.class.getClassLoader()); - Resource[] resources = - resolver.getResources("classpath:org/geoserver/data/test/*.properties"); + Resource[] resources = resolver.getResources("classpath:org/geoserver/data/test/*.properties"); List propFiles = Stream.of(resources).map(Resource::getFilename).toList(); propFiles.stream() .filter(f -> !f.equals("MarsPoi.properties")) // crs 49900 unknown @@ -186,8 +184,7 @@ public void clearLayerGroups() { } } - private LayerGroupInfo addLayerGroup( - String name, Mode mode, WorkspaceInfo ws, PublishedInfo... layers) { + private LayerGroupInfo addLayerGroup(String name, Mode mode, WorkspaceInfo ws, PublishedInfo... layers) { CatalogBuilder cb = new CatalogBuilder(catalog); LayerGroupInfo group = catalog.getFactory().createLayerGroup(); @@ -242,8 +239,7 @@ private String getLayerId(QName name) { @Test void buildLayerGroupCaches() { - GsCloudLayerGroupContainmentCache layerGroupContainmentCache = - new GsCloudLayerGroupContainmentCache(catalog); + GsCloudLayerGroupContainmentCache layerGroupContainmentCache = new GsCloudLayerGroupContainmentCache(catalog); ContextRefreshedEvent contextRefreshedEvent = mock(ContextRefreshedEvent.class); WebApplicationContext context = mock(WebApplicationContext.class); when(contextRefreshedEvent.getApplicationContext()).thenReturn(context); @@ -272,8 +268,7 @@ void testInitialSetup() { // now check the groups containing the layers (nature being SINGLE, not a container) assertThat(containerNamesForResource(MockData.LAKES), equalTo(set(CONTAINER_GROUP))); assertThat(containerNamesForResource(MockData.FORESTS), equalTo(set(CONTAINER_GROUP))); - assertThat( - containerNamesForResource(MockData.ROAD_SEGMENTS), equalTo(set(CONTAINER_GROUP))); + assertThat(containerNamesForResource(MockData.ROAD_SEGMENTS), equalTo(set(CONTAINER_GROUP))); } @Test @@ -305,8 +300,7 @@ void testRemoveLayerFromNature() { assertThat(containerNamesForResource(MockData.LAKES), empty()); assertThat(containerNamesForResource(MockData.FORESTS), equalTo(set(CONTAINER_GROUP))); - assertThat( - containerNamesForResource(MockData.ROAD_SEGMENTS), equalTo(set(CONTAINER_GROUP))); + assertThat(containerNamesForResource(MockData.ROAD_SEGMENTS), equalTo(set(CONTAINER_GROUP))); } @Test @@ -330,8 +324,7 @@ void testRemoveNatureFromContainer() { assertThat(containerNamesForGroup(nature), empty()); assertThat(containerNamesForResource(MockData.LAKES), empty()); assertThat(containerNamesForResource(MockData.FORESTS), empty()); - assertThat( - containerNamesForResource(MockData.ROAD_SEGMENTS), equalTo(set(CONTAINER_GROUP))); + assertThat(containerNamesForResource(MockData.ROAD_SEGMENTS), equalTo(set(CONTAINER_GROUP))); } @Test @@ -353,9 +346,7 @@ void testAddRemoveNamed() { // add and check containment LayerGroupInfo named = addLayerGroup(NAMED_GROUP, Mode.NAMED, null, lakes, neatline); - assertThat( - containerNamesForResource(MockData.LAKES), - equalTo(set(CONTAINER_GROUP, NAMED_GROUP))); + assertThat(containerNamesForResource(MockData.LAKES), equalTo(set(CONTAINER_GROUP, NAMED_GROUP))); assertThat(containerNamesForResource(MockData.MAP_NEATLINE), equalTo(set(NAMED_GROUP))); assertThat(containerNamesForGroup(named), empty()); @@ -377,12 +368,8 @@ void testAddRemoveNestedNamed() { container.getLayers().add(nestedNamed); container.getStyles().add(null); catalog.save(container); - assertThat( - containerNamesForResource(MockData.LAKES), - equalTo(set(CONTAINER_GROUP, NESTED_NAMED))); - assertThat( - containerNamesForResource(MockData.MAP_NEATLINE), - equalTo(set(CONTAINER_GROUP, NESTED_NAMED))); + assertThat(containerNamesForResource(MockData.LAKES), equalTo(set(CONTAINER_GROUP, NESTED_NAMED))); + assertThat(containerNamesForResource(MockData.MAP_NEATLINE), equalTo(set(CONTAINER_GROUP, NESTED_NAMED))); assertThat(containerNamesForGroup(nestedNamed), equalTo(set(CONTAINER_GROUP))); // delete and check containment diff --git a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/datadir/ConditionalOnDataDirectoryEnabled.java b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/datadir/ConditionalOnDataDirectoryEnabled.java index e0e72db0c..fc3ef8b30 100644 --- a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/datadir/ConditionalOnDataDirectoryEnabled.java +++ b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/datadir/ConditionalOnDataDirectoryEnabled.java @@ -4,13 +4,12 @@ */ package org.geoserver.cloud.autoconfigure.catalog.backend.datadir; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) diff --git a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/catalog/backend/datadir/EventualConsistencyEnforcer.java b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/catalog/backend/datadir/EventualConsistencyEnforcer.java index 4a3ad5511..061080c9b 100644 --- a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/catalog/backend/datadir/EventualConsistencyEnforcer.java +++ b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/catalog/backend/datadir/EventualConsistencyEnforcer.java @@ -5,13 +5,21 @@ package org.geoserver.cloud.catalog.backend.datadir; import com.google.common.collect.Sets; - +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.UUID; +import java.util.concurrent.Callable; +import java.util.concurrent.locks.ReentrantLock; import lombok.AllArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.DataStoreInfo; import org.geoserver.catalog.NamespaceInfo; @@ -26,17 +34,6 @@ import org.geoserver.config.impl.GeoServerLifecycleHandler; import org.springframework.lang.Nullable; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.Callable; -import java.util.concurrent.locks.ReentrantLock; - /** * Aids {@link EventuallyConsistentCatalogFacade} in ensuring the catalog stays consistent and * eventually converges while remote events may arrive out of order and {@link CatalogInfo}s @@ -59,7 +56,8 @@ public class EventualConsistencyEnforcer implements GeoServerLifecycleHandler { private final Map>> pendingOperations = new HashMap<>(); - @Setter private ExtendedCatalogFacade rawFacade; + @Setter + private ExtendedCatalogFacade rawFacade; private final ReentrantLock lock = new ReentrantLock(); @@ -130,9 +128,7 @@ private void tryResolvePending(String missingRef) { } Optional found = rawFacade.get(missingRef); if (found.isPresent()) { - log.debug( - "previously missing ref {} found, resolving pending operations waiting for it", - missingRef); + log.debug("previously missing ref {} found, resolving pending operations waiting for it", missingRef); tryResolvePending(found.orElseThrow()); } else { log.debug( @@ -188,8 +184,7 @@ public void setDefaultNamespace(@Nullable NamespaceInfo namespace) { execute(new SetDefaultNamespace(namespace)); } - public void setDefaultDataStore( - @NonNull WorkspaceInfo workspace, @Nullable DataStoreInfo store) { + public void setDefaultDataStore(@NonNull WorkspaceInfo workspace, @Nullable DataStoreInfo store) { execute(new SetDefaultDataStore(workspace, store)); } @@ -251,7 +246,9 @@ protected boolean completedSuccessfully() { private void setPending(String missingRef, ConsistencyOp deferredOp) { log.debug("missing ref {}, deferring execution of {}", missingRef, deferredOp); - pendingOperations.computeIfAbsent(missingRef, ref -> new ArrayList<>()).add(deferredOp); + pendingOperations + .computeIfAbsent(missingRef, ref -> new ArrayList<>()) + .add(deferredOp); } private void unsetPending(String resolvedRef, ConsistencyOp completedOp) { @@ -331,14 +328,11 @@ protected T resolve() { Class type = ConfigInfoType.valueOf(info).type(); rawFacade .get(info.getId(), type) - .ifPresentOrElse( - existing -> - log.info("Ignoring add, object exists {}", info.getId()), - () -> { - T added = rawFacade.add(info); - this.info = added; - success = true; - }); + .ifPresentOrElse(existing -> log.info("Ignoring add, object exists {}", info.getId()), () -> { + T added = rawFacade.add(info); + this.info = added; + success = true; + }); } // return info to comply with the catalog facade add() contract // but delay insertion of info as it has unresolved references @@ -368,8 +362,7 @@ private class UpdateOp extends ConsistencyOp { @Override public String toString() { return "%s(%s, patch: %s)" - .formatted( - getClass().getSimpleName(), toUpdate.getId(), patch.getPropertyNames()); + .formatted(getClass().getSimpleName(), toUpdate.getId(), patch.getPropertyNames()); } @Override @@ -466,10 +459,7 @@ private void completeOrDiscard(ConsistencyOp dependant) { final String id = info.getId(); execute(dependant); if (dependant.completedSuccessfully()) { - log.debug( - "successfully executed {} depending on {} before removing it", - dependant, - id); + log.debug("successfully executed {} depending on {} before removing it", dependant, id); } else { log.warn( "operation dependant on {} didn't complete successfully before removing it. It will be discarded: {}", @@ -484,7 +474,8 @@ private void completeOrDiscard(ConsistencyOp dependant) { @RequiredArgsConstructor private class SetDefaultWorkspace extends ConsistencyOp { - @Nullable private final WorkspaceInfo workspace; + @Nullable + private final WorkspaceInfo workspace; @Override Set getMissingRefs() { @@ -513,15 +504,14 @@ protected Void resolve() { @Override public String toString() { return "%s(workspace: %s)" - .formatted( - getClass().getSimpleName(), - (workspace == null ? null : workspace.getId())); + .formatted(getClass().getSimpleName(), (workspace == null ? null : workspace.getId())); } } @RequiredArgsConstructor private class SetDefaultNamespace extends ConsistencyOp { - @Nullable private final NamespaceInfo namespace; + @Nullable + private final NamespaceInfo namespace; @Override Set getMissingRefs() { @@ -550,16 +540,17 @@ protected Void resolve() { @Override public String toString() { return "%s(namespace: %s)" - .formatted( - getClass().getSimpleName(), - (namespace == null ? null : namespace.getId())); + .formatted(getClass().getSimpleName(), (namespace == null ? null : namespace.getId())); } } @AllArgsConstructor private class SetDefaultDataStore extends ConsistencyOp { - @NonNull private WorkspaceInfo workspace; - @Nullable private DataStoreInfo store; + @NonNull + private WorkspaceInfo workspace; + + @Nullable + private DataStoreInfo store; @Override Set getMissingRefs() { @@ -602,10 +593,7 @@ protected Void resolve() { @Override public String toString() { return "%s(workspace: %s, store: %s)" - .formatted( - getClass().getSimpleName(), - workspace.getId(), - (store == null ? null : store.getId())); + .formatted(getClass().getSimpleName(), workspace.getId(), (store == null ? null : store.getId())); } } } diff --git a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/catalog/backend/datadir/EventuallyConsistentCatalogFacade.java b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/catalog/backend/datadir/EventuallyConsistentCatalogFacade.java index 52bcb65e8..f317aa436 100644 --- a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/catalog/backend/datadir/EventuallyConsistentCatalogFacade.java +++ b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/catalog/backend/datadir/EventuallyConsistentCatalogFacade.java @@ -4,10 +4,13 @@ */ package org.geoserver.cloud.catalog.backend.datadir; +import java.util.Objects; +import java.util.concurrent.TimeUnit; +import java.util.function.Predicate; +import java.util.function.Supplier; import lombok.NonNull; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.DataStoreInfo; import org.geoserver.catalog.LayerGroupInfo; @@ -28,11 +31,6 @@ import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; -import java.util.Objects; -import java.util.concurrent.TimeUnit; -import java.util.function.Predicate; -import java.util.function.Supplier; - /** * * @@ -184,13 +182,10 @@ public T getStore(String id, Class clazz) { } @Override - public T getStoreByName( - WorkspaceInfo workspace, String name, Class clazz) { + public T getStoreByName(WorkspaceInfo workspace, String name, Class clazz) { return retryOnNull( () -> super.getStoreByName(workspace, name, clazz), // - () -> - "getStoreByName(%s, %s, %s)" - .formatted(nameof(workspace), name, clazz.getSimpleName())); + () -> "getStoreByName(%s, %s, %s)".formatted(nameof(workspace), name, clazz.getSimpleName())); } @Override @@ -201,23 +196,17 @@ public T getResource(String id, Class clazz) { } @Override - public T getResourceByName( - NamespaceInfo namespace, String name, Class clazz) { + public T getResourceByName(NamespaceInfo namespace, String name, Class clazz) { return retryOnNull( () -> super.getResourceByName(namespace, name, clazz), // - () -> - "getResourceByName(%s, %s, %s)" - .formatted(nameof(namespace), name, clazz.getSimpleName())); + () -> "getResourceByName(%s, %s, %s)".formatted(nameof(namespace), name, clazz.getSimpleName())); } @Override - public T getResourceByStore( - StoreInfo store, String name, Class clazz) { + public T getResourceByStore(StoreInfo store, String name, Class clazz) { return retryOnNull( () -> super.getResourceByStore(store, name, clazz), // - () -> - "getResourceByStore(%s, %s, %s)" - .formatted(nameof(store), name, clazz.getSimpleName())); + () -> "getResourceByStore(%s, %s, %s)".formatted(nameof(store), name, clazz.getSimpleName())); } @Override @@ -339,8 +328,7 @@ private boolean isRestRequest() { return false; } - private T doRetry( - Supplier supplier, Predicate predicate, Supplier op, T ret) { + private T doRetry(Supplier supplier, Predicate predicate, Supplier op, T ret) { // poor man's Retry implementation final int maxAttempts = retryAttemptMillis.length; final String opDesc = op.get(); diff --git a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryBackendConfiguration.java b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryBackendConfiguration.java index 4670c2bb6..7b07de983 100644 --- a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryBackendConfiguration.java +++ b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryBackendConfiguration.java @@ -4,9 +4,13 @@ */ package org.geoserver.cloud.config.catalog.backend.datadirectory; +import java.io.File; +import java.nio.file.Path; +import java.util.List; +import java.util.Objects; +import java.util.Optional; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.GeoServerConfigurationLock; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.plugin.CatalogPlugin; @@ -35,12 +39,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.DependsOn; -import java.io.File; -import java.nio.file.Path; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - /** */ @Configuration(proxyBeanMethods = true) @Slf4j(topic = "org.geoserver.cloud.config.datadirectory") @@ -67,8 +65,7 @@ public DataDirectoryBackendConfiguration( @Bean ModuleStatusImpl moduleStatus() { - ModuleStatusImpl module = - new ModuleStatusImpl("gs-cloud-backend-datadir", "DataDirectory loader"); + ModuleStatusImpl module = new ModuleStatusImpl("gs-cloud-backend-datadir", "DataDirectory loader"); module.setAvailable(true); module.setEnabled(true); return module; @@ -119,9 +116,7 @@ LockingGeoServer geoServer(@Qualifier("catalog") Catalog catalog) { List retries = ecConfig.getRetries(); if (retries != null && !retries.isEmpty()) { waitMillis = retries.stream().mapToInt(Integer::intValue).toArray(); - log.info( - "Data directory catalog facade eventual consistency retries in ms: {}", - retries); + log.info("Data directory catalog facade eventual consistency retries in ms: {}", retries); } } EventualConsistencyEnforcer tracker = converger.orElseThrow(); @@ -157,8 +152,7 @@ LockingGeoServer geoServer(@Qualifier("catalog") Catalog catalog) { GeoServerResourceLoader resourceLoader = resourceLoader(); Catalog rawCatalog = rawCatalog(); LockingGeoServer geoserver = geoServer(rawCatalog); - return new DataDirectoryGeoServerLoader( - updateSequence, resourceLoader, geoserver, rawCatalog); + return new DataDirectoryGeoServerLoader(updateSequence, resourceLoader, geoserver, rawCatalog); } /** @@ -211,8 +205,7 @@ GeoServerLoader geoServerLoaderImplParallel(GeoServerSecurityManager securityMan private Path dataDirectoryFile() { DataDirectoryProperties config = this.dataDirectoryConfig; Path path = config.getLocation(); - Objects.requireNonNull( - path, "geoserver.backend.data-directory.location config property resolves to null"); + Objects.requireNonNull(path, "geoserver.backend.data-directory.location config property resolves to null"); return path; } } diff --git a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryGeoServerLoader.java b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryGeoServerLoader.java index dd106b9fa..6b064a2e7 100644 --- a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryGeoServerLoader.java +++ b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryGeoServerLoader.java @@ -4,9 +4,11 @@ */ package org.geoserver.cloud.config.catalog.backend.datadirectory; +import java.io.IOException; +import java.util.Set; +import javax.annotation.PostConstruct; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.GeoServerConfigurationLock; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.plugin.CatalogPluginStyleResourcePersister; @@ -24,11 +26,6 @@ import org.geoserver.platform.GeoServerResourceLoader; import org.geoserver.platform.config.UpdateSequence; -import java.io.IOException; -import java.util.Set; - -import javax.annotation.PostConstruct; - /** * {@link Catalog} and {@link GeoServer config} loader for the data-directory backend, loads the * configuration from disk as soon as the spring bean wiring is {@link #load() ready}; {@link @@ -154,8 +151,7 @@ protected void loadCatalog(Catalog catalog, XStreamPersister xp) throws Exceptio catalog.removeListeners(GeoServerConfigPersister.class); catalog.removeListeners(GeoServerResourcePersister.class); - catalog.addListener( - new CatalogPluginGeoServerConfigPersister(catalog.getResourceLoader(), xp)); + catalog.addListener(new CatalogPluginGeoServerConfigPersister(catalog.getResourceLoader(), xp)); catalog.addListener(new CatalogPluginStyleResourcePersister(catalog)); } } diff --git a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryLoaderSupport.java b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryLoaderSupport.java index d578eb95d..504f10f91 100644 --- a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryLoaderSupport.java +++ b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryLoaderSupport.java @@ -4,10 +4,13 @@ */ package org.geoserver.cloud.config.catalog.backend.datadirectory; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; - import org.geoserver.config.ConfigurationListener; import org.geoserver.config.GeoServer; import org.geoserver.config.GeoServerConfigPersister; @@ -20,11 +23,6 @@ import org.geoserver.platform.resource.Resource; import org.geoserver.platform.resource.Resources; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - /** * @since 1.0 */ @@ -63,37 +61,32 @@ public Optional preload(GeoServer gs, XStreamServiceLoader loade public void persistNewlyCreatedServices(GeoServer geoServer, Set existingServiceNames) { - ServicePersister servicePersister = - geoServer.getListeners().stream() - .filter(ServicePersister.class::isInstance) - .map(ServicePersister.class::cast) - .findFirst() - .orElseThrow(); + ServicePersister servicePersister = geoServer.getListeners().stream() + .filter(ServicePersister.class::isInstance) + .map(ServicePersister.class::cast) + .findFirst() + .orElseThrow(); geoServer.getServices().stream() .filter(s -> !existingServiceNames.contains(s.getName())) - .forEach( - s -> { - log.info("Persisting created service {}", s.getId()); - servicePersister.handlePostServiceChange(s); - }); + .forEach(s -> { + log.info("Persisting created service {}", s.getId()); + servicePersister.handlePostServiceChange(s); + }); } - public void replaceCatalogInfoPersisterWithFixedVersion( - final GeoServer geoServer, XStreamPersister xp) { + public void replaceCatalogInfoPersisterWithFixedVersion(final GeoServer geoServer, XStreamPersister xp) { - ConfigurationListener configPersister = - geoServer.getListeners().stream() - .filter(GeoServerConfigPersister.class::isInstance) - .findFirst() - .orElse(null); + ConfigurationListener configPersister = geoServer.getListeners().stream() + .filter(GeoServerConfigPersister.class::isInstance) + .findFirst() + .orElse(null); if (configPersister != null) { geoServer.removeListener(configPersister); } GeoServerConfigPersister fixedCatalogInfoPersister = - new CatalogPluginGeoServerConfigPersister( - geoServer.getCatalog().getResourceLoader(), xp); + new CatalogPluginGeoServerConfigPersister(geoServer.getCatalog().getResourceLoader(), xp); geoServer.addListener(fixedCatalogInfoPersister); } @@ -108,8 +101,7 @@ public void initializeEmptyConfig(final GeoServer geoServer) { geoServer.setLogging(geoServer.getFactory().createLogging()); } // ensure we have a service configuration for every service we know about - final List loaders = - GeoServerExtensions.extensions(XStreamServiceLoader.class); + final List loaders = GeoServerExtensions.extensions(XStreamServiceLoader.class); for (XStreamServiceLoader l : loaders) { ServiceInfo serviceInfo = geoServer.getService(l.getServiceClass()); if (serviceInfo == null) { diff --git a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryProperties.java b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryProperties.java index f5bf0f4a8..b15934698 100644 --- a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryProperties.java +++ b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryProperties.java @@ -4,15 +4,13 @@ */ package org.geoserver.cloud.config.catalog.backend.datadirectory; +import java.nio.file.Path; +import java.util.List; import lombok.Data; - import org.geoserver.cloud.autoconfigure.catalog.backend.datadir.DataDirectoryAutoConfiguration; import org.geoserver.cloud.config.catalog.backend.core.GeoServerBackendConfigurer; import org.springframework.boot.context.properties.ConfigurationProperties; -import java.nio.file.Path; -import java.util.List; - /** * Configuration properties to use GeoServer's traditional, file-system based data-directory as the * {@link GeoServerBackendConfigurer catalog and configuration backend} through the {@link @@ -25,8 +23,7 @@ public class DataDirectoryProperties { private boolean enabled; private Path location; private boolean parallelLoader = true; - private DataDirectoryProperties.EventualConsistencyConfig eventualConsistency = - new EventualConsistencyConfig(); + private DataDirectoryProperties.EventualConsistencyConfig eventualConsistency = new EventualConsistencyConfig(); /** * Eventual consistency enfocement configuration. Bus events may come out of order under stress diff --git a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryUpdateSequence.java b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryUpdateSequence.java index 8694d3542..87649febf 100644 --- a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryUpdateSequence.java +++ b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/DataDirectoryUpdateSequence.java @@ -4,10 +4,19 @@ */ package org.geoserver.cloud.config.catalog.backend.datadirectory; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStreamWriter; +import java.io.UncheckedIOException; +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; +import java.util.Optional; +import java.util.Properties; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.impl.ModificationProxy; import org.geoserver.config.GeoServer; @@ -23,17 +32,6 @@ import org.geoserver.platform.resource.ResourceStore; import org.geoserver.platform.resource.Resources; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStreamWriter; -import java.io.UncheckedIOException; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.Optional; -import java.util.Properties; - /** * @since 1.0 */ @@ -168,8 +166,7 @@ private void save(Resource resource, Properties props) throws IOException { protected Properties load(Resource resource) throws IOException { byte[] contents = resource.getContents(); Properties props = new Properties(); - InputStreamReader reader = - new InputStreamReader(new ByteArrayInputStream(contents), CHARSET); + InputStreamReader reader = new InputStreamReader(new ByteArrayInputStream(contents), CHARSET); props.load(reader); return props; } diff --git a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/NoServletContextDataDirectoryResourceStore.java b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/NoServletContextDataDirectoryResourceStore.java index e954e628c..6a09e88b2 100644 --- a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/NoServletContextDataDirectoryResourceStore.java +++ b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/NoServletContextDataDirectoryResourceStore.java @@ -4,15 +4,12 @@ */ package org.geoserver.cloud.config.catalog.backend.datadirectory; -import lombok.extern.slf4j.Slf4j; - -import org.geoserver.platform.resource.DataDirectoryResourceStore; -import org.geoserver.platform.resource.FileSystemResourceStore; - import java.io.File; import java.util.Objects; - import javax.servlet.ServletContext; +import lombok.extern.slf4j.Slf4j; +import org.geoserver.platform.resource.DataDirectoryResourceStore; +import org.geoserver.platform.resource.FileSystemResourceStore; /** * {@link DataDirectoryResourceStore} that works both for webmvc (servlet) and reactive (WebFlux) @@ -30,11 +27,9 @@ public NoServletContextDataDirectoryResourceStore(File resourceDirectory) { if (resourceDirectory.isFile()) { throw new IllegalArgumentException( - "Directory required, file present at this location %s" - .formatted(resourceDirectory)); + "Directory required, file present at this location %s".formatted(resourceDirectory)); } else if (!resourceDirectory.isDirectory() && !resourceDirectory.mkdirs()) { - throw new IllegalArgumentException( - "Unable to create directory %s".formatted(resourceDirectory)); + throw new IllegalArgumentException("Unable to create directory %s".formatted(resourceDirectory)); } this.setBaseDirectory(resourceDirectory); } diff --git a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/NoServletContextFileLockProvider.java b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/NoServletContextFileLockProvider.java index f37e5791d..c6d70c784 100644 --- a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/NoServletContextFileLockProvider.java +++ b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/NoServletContextFileLockProvider.java @@ -4,15 +4,12 @@ */ package org.geoserver.cloud.config.catalog.backend.datadirectory; +import java.io.File; +import javax.servlet.ServletContext; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.platform.resource.FileLockProvider; -import java.io.File; - -import javax.servlet.ServletContext; - /** * {@link FileLockProvider} that expects the data directory file at its constructor, overriding * {@link #setServletContext} to be ignored. diff --git a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/ParallelDataDirectoryGeoServerLoader.java b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/ParallelDataDirectoryGeoServerLoader.java index e7fb20b02..f3de8cbb2 100644 --- a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/ParallelDataDirectoryGeoServerLoader.java +++ b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/config/catalog/backend/datadirectory/ParallelDataDirectoryGeoServerLoader.java @@ -10,9 +10,12 @@ import static org.geoserver.catalog.StyleInfo.DEFAULT_POLYGON; import static org.geoserver.catalog.StyleInfo.DEFAULT_RASTER; +import java.io.IOException; +import java.util.Arrays; +import java.util.Set; +import javax.annotation.PostConstruct; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.GeoServerConfigurationLock; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.FeatureTypeCallback; @@ -36,12 +39,6 @@ import org.geotools.api.referencing.NoSuchAuthorityCodeException; import org.vfny.geoserver.util.DataStoreUtils; -import java.io.IOException; -import java.util.Arrays; -import java.util.Set; - -import javax.annotation.PostConstruct; - /** * Extends the parallel {@link org.geoserver.catalog.datadir.DataDirectoryGeoServerLoader} to * account for extra care needed on a cloud environment with potentially multiple instances starting @@ -67,8 +64,7 @@ * @see DataDirectoryGeoServerLoader */ @Slf4j -public class ParallelDataDirectoryGeoServerLoader - extends org.geoserver.catalog.datadir.DataDirectoryGeoServerLoader { +public class ParallelDataDirectoryGeoServerLoader extends org.geoserver.catalog.datadir.DataDirectoryGeoServerLoader { private @NonNull UpdateSequence updateSequence; private @NonNull Catalog rawCatalog; @@ -131,15 +127,13 @@ private void triggerCollaboratorBeansLoading() throws FactoryException { // misconfigured layers may end up calling FeatureTypeInfo.getFeatureType(), which in turn // will trigger GeoServerExtensions and deadlock on the main thread's while spring is // building up beans - DataStoreUtils.getAvailableDataStoreFactories() - .forEach( - f -> { - try { - DataStoreUtils.aquireFactory(f.getDisplayName()); - } catch (Exception ignore) { - // - } - }); + DataStoreUtils.getAvailableDataStoreFactories().forEach(f -> { + try { + DataStoreUtils.aquireFactory(f.getDisplayName()); + } catch (Exception ignore) { + // + } + }); GeoServerExtensions.extensions(FeatureTypeCallback.class); } @@ -151,8 +145,7 @@ public void loadCatalog(Catalog catalog, XStreamPersister xp) throws Exception { catalog.removeListeners(GeoServerConfigPersister.class); catalog.removeListeners(GeoServerResourcePersister.class); - catalog.addListener( - new CatalogPluginGeoServerConfigPersister(catalog.getResourceLoader(), xp)); + catalog.addListener(new CatalogPluginGeoServerConfigPersister(catalog.getResourceLoader(), xp)); catalog.addListener(new CatalogPluginStyleResourcePersister(catalog)); } @@ -187,13 +180,7 @@ public void loadGeoServer(GeoServer geoServer, XStreamPersister xp) throws Excep */ @Override protected void initializeDefaultStyles(Catalog catalog) throws IOException { - if (styleMissing( - catalog, - DEFAULT_POINT, - DEFAULT_LINE, - DEFAULT_POLYGON, - DEFAULT_RASTER, - DEFAULT_GENERIC)) { + if (styleMissing(catalog, DEFAULT_POINT, DEFAULT_LINE, DEFAULT_POLYGON, DEFAULT_RASTER, DEFAULT_GENERIC)) { log.info("Initializing default styles"); GeoServerConfigurationLock configLock = lockingGeoserver.getConfigurationLock(); diff --git a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/event/remote/datadir/RemoteEventDataDirectoryProcessor.java b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/event/remote/datadir/RemoteEventDataDirectoryProcessor.java index f1e10478b..586ebf117 100644 --- a/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/event/remote/datadir/RemoteEventDataDirectoryProcessor.java +++ b/src/catalog/backends/datadir/src/main/java/org/geoserver/cloud/event/remote/datadir/RemoteEventDataDirectoryProcessor.java @@ -4,10 +4,11 @@ */ package org.geoserver.cloud.event.remote.datadir; +import java.util.function.Consumer; +import java.util.function.Function; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.DataStoreInfo; import org.geoserver.catalog.Info; @@ -33,9 +34,6 @@ import org.geoserver.config.plugin.RepositoryGeoServerFacade; import org.springframework.context.event.EventListener; -import java.util.function.Consumer; -import java.util.function.Function; - /** * Listens to {@link RemoteCatalogEvent}s and updates the local catalog * @@ -94,20 +92,13 @@ public void onRemoteRemoveEvent(InfoRemoved event) { facade.remove(info); log.debug("Removed {}({}), from local catalog", type, objectId); }, - () -> - log.warn( - "Can't remove {}({}), not present in local catalog", - type, - objectId)); + () -> log.warn("Can't remove {}({}), not present in local catalog", type, objectId)); } else { boolean removed = switch (type) { case SERVICE -> remove( - objectId, - id -> configFacade.getService(id, ServiceInfo.class), - configFacade::remove); - case SETTINGS -> remove( - objectId, configFacade::getSettings, configFacade::remove); + objectId, id -> configFacade.getService(id, ServiceInfo.class), configFacade::remove); + case SETTINGS -> remove(objectId, configFacade::getSettings, configFacade::remove); default -> false; }; if (removed) { @@ -130,8 +121,7 @@ public void onRemoteAddEvent(InfoAdded event) { log.error("Remote add event didn't send the object payload for {}({})", type, objectId); return; } - if (log.isDebugEnabled()) - log.debug("Adding object from event {}: {}", event.toShortString(), object); + if (log.isDebugEnabled()) log.debug("Adding object from event {}: {}", event.toShortString(), object); ExtendedCatalogFacade facade = catalogFacade(); switch (object) { case CatalogInfo info -> facade.add(info); @@ -140,8 +130,7 @@ public void onRemoteAddEvent(InfoAdded event) { case LoggingInfo config -> log.debug("ignoring unused LoggingInfo {}", config); default -> log.warn("Don't know how to handle remote envent {})", event); } - if (log.isDebugEnabled()) - log.debug("Added object from event {}: {}", event.toShortString(), object); + if (log.isDebugEnabled()) log.debug("Added object from event {}: {}", event.toShortString(), object); } @EventListener(InfoModified.class) @@ -179,11 +168,7 @@ public void onRemoteModifyEvent(InfoModified event) { } if (log.isDebugEnabled()) - log.debug( - "Object updated: {}({}). Properties: {}", - type, - event.getObjectId(), - patch.getPropertyNames()); + log.debug("Object updated: {}({}). Properties: {}", type, event.getObjectId(), patch.getPropertyNames()); } private Info loadInfo(InfoModified event) { @@ -241,8 +226,7 @@ public void onRemoteDefaultDataStoreEvent(DefaultDataStoreSet event) { ExtendedCatalogFacade facade = catalogFacade(); - WorkspaceInfo workspace = - ResolvingProxy.create(event.getWorkspaceId(), WorkspaceInfo.class); + WorkspaceInfo workspace = ResolvingProxy.create(event.getWorkspaceId(), WorkspaceInfo.class); DataStoreInfo store = null; if (null != event.getDefaultDataStoreId()) { @@ -251,8 +235,7 @@ public void onRemoteDefaultDataStoreEvent(DefaultDataStoreSet event) { facade.setDefaultDataStore(workspace, store); } - private boolean remove( - String id, Function supplier, Consumer remover) { + private boolean remove(String id, Function supplier, Consumer remover) { T info = supplier.apply(id); if (info == null) { return false; diff --git a/src/catalog/backends/datadir/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/datadir/DataDirectoryAutoConfigurationTest.java b/src/catalog/backends/datadir/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/datadir/DataDirectoryAutoConfigurationTest.java index ca49bfa42..5703d52b3 100644 --- a/src/catalog/backends/datadir/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/datadir/DataDirectoryAutoConfigurationTest.java +++ b/src/catalog/backends/datadir/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/datadir/DataDirectoryAutoConfigurationTest.java @@ -7,6 +7,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertSame; +import java.nio.file.Paths; import org.geoserver.GeoServerConfigurationLock; import org.geoserver.catalog.CatalogFacade; import org.geoserver.catalog.plugin.CatalogPlugin; @@ -26,153 +27,118 @@ import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import java.nio.file.Paths; - /** * Test {@link DataDirectoryBackendConfiguration} through {@link DataDirectoryAutoConfiguration} * when {@code geoserver.backend.data-directory.enabled=true} */ class DataDirectoryAutoConfigurationTest { - private ApplicationContextRunner runner = - new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of( - // AutoConfigurations from gs-cloud-catalog-backend-common - org.geoserver.cloud.autoconfigure.geotools - .GeoToolsHttpClientAutoConfiguration.class, - org.geoserver.cloud.autoconfigure.catalog.backend.core - .GeoServerBackendAutoConfiguration.class, - org.geoserver.cloud.autoconfigure.catalog.backend.core - .DefaultUpdateSequenceAutoConfiguration.class, - org.geoserver.cloud.autoconfigure.catalog.backend.core - .XstreamServiceLoadersAutoConfiguration.class, - org.geoserver.cloud.autoconfigure.catalog.backend.core - .RemoteEventResourcePoolCleanupUpAutoConfiguration - .class, - org.geoserver.cloud.autoconfigure.security - .GeoServerSecurityAutoConfiguration.class, - org.geoserver.cloud.autoconfigure.metrics.catalog - .CatalogMetricsAutoConfiguration.class, - // AutoConfigurations from gs-cloud-catalog-backend-datadir - org.geoserver.cloud.autoconfigure.catalog.backend.datadir - .DataDirectoryAutoConfiguration.class // - )) - // - .withPropertyValues( - "geoserver.backend.dataDirectory.enabled=true", // - "geoserver.backend.dataDirectory.location=/tmp/data_dir_autoconfiguration_test" // - ); + private ApplicationContextRunner runner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + // AutoConfigurations from gs-cloud-catalog-backend-common + org.geoserver.cloud.autoconfigure.geotools.GeoToolsHttpClientAutoConfiguration.class, + org.geoserver.cloud.autoconfigure.catalog.backend.core.GeoServerBackendAutoConfiguration.class, + org.geoserver.cloud.autoconfigure.catalog.backend.core.DefaultUpdateSequenceAutoConfiguration.class, + org.geoserver.cloud.autoconfigure.catalog.backend.core.XstreamServiceLoadersAutoConfiguration.class, + org.geoserver.cloud.autoconfigure.catalog.backend.core + .RemoteEventResourcePoolCleanupUpAutoConfiguration.class, + org.geoserver.cloud.autoconfigure.security.GeoServerSecurityAutoConfiguration.class, + org.geoserver.cloud.autoconfigure.metrics.catalog.CatalogMetricsAutoConfiguration.class, + // AutoConfigurations from gs-cloud-catalog-backend-datadir + org.geoserver.cloud.autoconfigure.catalog.backend.datadir.DataDirectoryAutoConfiguration.class // + )) + // + .withPropertyValues( + "geoserver.backend.dataDirectory.enabled=true", // + "geoserver.backend.dataDirectory.location=/tmp/data_dir_autoconfiguration_test" // + ); @Test void testProperties() { - runner.run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(context).hasSingleBean(DataDirectoryProperties.class); - assertThat(context) - .getBean(DataDirectoryProperties.class) - .hasFieldOrPropertyWithValue( - "location", Paths.get("/tmp/data_dir_autoconfiguration_test")); - }); + runner.run(context -> { + assertThat(context).hasNotFailed(); + assertThat(context).hasSingleBean(DataDirectoryProperties.class); + assertThat(context) + .getBean(DataDirectoryProperties.class) + .hasFieldOrPropertyWithValue("location", Paths.get("/tmp/data_dir_autoconfiguration_test")); + }); } @Test void testCatalog() { - runner.run( - context -> { - assertThat(context).getBean("rawCatalog").isInstanceOf(LockingCatalog.class); - }); + runner.run(context -> { + assertThat(context).getBean("rawCatalog").isInstanceOf(LockingCatalog.class); + }); } @Test void testGeoServer() { - runner.run( - context -> { - assertThat(context).getBean("geoServer").isInstanceOf(LockingGeoServer.class); - }); + runner.run(context -> { + assertThat(context).getBean("geoServer").isInstanceOf(LockingGeoServer.class); + }); } @Test void testCatalogFacadeIsRawCatalogFacade() { - runner.run( - context -> { - CatalogFacade rawCatalogFacade = - context.getBean("catalogFacade", CatalogFacade.class); - CatalogPlugin rawCatalog = context.getBean("rawCatalog", CatalogPlugin.class); - assertSame(rawCatalogFacade, rawCatalog.getRawFacade()); - }); + runner.run(context -> { + CatalogFacade rawCatalogFacade = context.getBean("catalogFacade", CatalogFacade.class); + CatalogPlugin rawCatalog = context.getBean("rawCatalog", CatalogPlugin.class); + assertSame(rawCatalogFacade, rawCatalog.getRawFacade()); + }); } @Test void testResourceLoader() { - runner.run( - context -> { - assertThat(context) - .getBean("resourceLoader") - .isInstanceOf(GeoServerResourceLoader.class); - }); + runner.run(context -> { + assertThat(context).getBean("resourceLoader").isInstanceOf(GeoServerResourceLoader.class); + }); } @Test void testGeoserverFacade() { - runner.run( - context -> { - assertThat(context) - .getBean("geoserverFacade") - .isInstanceOf(RepositoryGeoServerFacade.class); - }); + runner.run(context -> { + assertThat(context).getBean("geoserverFacade").isInstanceOf(RepositoryGeoServerFacade.class); + }); } @Test void testGeoserverLoaderLegacy() { runner.withPropertyValues("geoserver.backend.data-directory.parallel-loader=false") - .run( - context -> { - assertThat(context) - .getBean("geoServerLoaderImpl") - .isInstanceOf(DataDirectoryGeoServerLoader.class); - }); + .run(context -> { + assertThat(context).getBean("geoServerLoaderImpl").isInstanceOf(DataDirectoryGeoServerLoader.class); + }); } @Test void testGeoserverLoader() { - runner.run( - context -> { - assertThat(context) - .getBean("geoServerLoaderImpl") - .isInstanceOf(ParallelDataDirectoryGeoServerLoader.class); - }); + runner.run(context -> { + assertThat(context).getBean("geoServerLoaderImpl").isInstanceOf(ParallelDataDirectoryGeoServerLoader.class); + }); } @Test void testResourceStoreImpl() { - runner.run( - context -> { - assertThat(context) - .getBean("resourceStoreImpl") - .isInstanceOf(NoServletContextDataDirectoryResourceStore.class); - }); + runner.run(context -> { + assertThat(context) + .getBean("resourceStoreImpl") + .isInstanceOf(NoServletContextDataDirectoryResourceStore.class); + }); } @Test void testUpdateSequence() { - runner.run( - context -> { - assertThat(context) - .getBean(UpdateSequence.class) - .isInstanceOf(DataDirectoryUpdateSequence.class); - }); + runner.run(context -> { + assertThat(context).getBean(UpdateSequence.class).isInstanceOf(DataDirectoryUpdateSequence.class); + }); } @Test void testGeoServerConfigurationLock() { - runner.run( - context -> { - assertThat(context) - .getBean(GeoServerConfigurationLock.class) - .isInstanceOf(LockProviderGeoServerConfigurationLock.class); - }); + runner.run(context -> { + assertThat(context) + .getBean(GeoServerConfigurationLock.class) + .isInstanceOf(LockProviderGeoServerConfigurationLock.class); + }); } } diff --git a/src/catalog/backends/datadir/src/test/java/org/geoserver/cloud/catalog/backend/datadir/EventuallyConsistentCatalogFacadeTest.java b/src/catalog/backends/datadir/src/test/java/org/geoserver/cloud/catalog/backend/datadir/EventuallyConsistentCatalogFacadeTest.java index 80c001bfa..9334b11ad 100644 --- a/src/catalog/backends/datadir/src/test/java/org/geoserver/cloud/catalog/backend/datadir/EventuallyConsistentCatalogFacadeTest.java +++ b/src/catalog/backends/datadir/src/test/java/org/geoserver/cloud/catalog/backend/datadir/EventuallyConsistentCatalogFacadeTest.java @@ -11,6 +11,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; +import java.util.function.Consumer; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.CoverageInfo; import org.geoserver.catalog.CoverageStoreInfo; @@ -33,8 +34,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.function.Consumer; - class EventuallyConsistentCatalogFacadeTest { EventualConsistencyEnforcer tracker; diff --git a/src/catalog/backends/datadir/src/test/java/org/geoserver/cloud/event/remote/datadir/RemoteEventDataDirectoryProcessorTest.java b/src/catalog/backends/datadir/src/test/java/org/geoserver/cloud/event/remote/datadir/RemoteEventDataDirectoryProcessorTest.java index 44fe1c346..ce507238a 100644 --- a/src/catalog/backends/datadir/src/test/java/org/geoserver/cloud/event/remote/datadir/RemoteEventDataDirectoryProcessorTest.java +++ b/src/catalog/backends/datadir/src/test/java/org/geoserver/cloud/event/remote/datadir/RemoteEventDataDirectoryProcessorTest.java @@ -14,6 +14,8 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +import java.util.List; +import java.util.Optional; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.impl.ModificationProxy; @@ -47,9 +49,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.List; -import java.util.Optional; - class RemoteEventDataDirectoryProcessorTest { ExtendedCatalogFacade mockFacade; @@ -74,13 +73,9 @@ void testRemoteEventDataDirectoryProcessor() { RepositoryGeoServerFacade configFacade = mock(RepositoryGeoServerFacade.class); CatalogPlugin rawCatalog = mock(CatalogPlugin.class); - assertThrows( - NullPointerException.class, - () -> new RemoteEventDataDirectoryProcessor(null, rawCatalog)); + assertThrows(NullPointerException.class, () -> new RemoteEventDataDirectoryProcessor(null, rawCatalog)); - assertThrows( - NullPointerException.class, - () -> new RemoteEventDataDirectoryProcessor(configFacade, null)); + assertThrows(NullPointerException.class, () -> new RemoteEventDataDirectoryProcessor(configFacade, null)); var catalogFacade = mock(ExtendedCatalogFacade.class); when(rawCatalog.getFacade()).thenReturn(catalogFacade); @@ -147,8 +142,7 @@ void testOnRemoteRemoveEvent_ConfigInfo() { ((WorkspaceInfoImpl) settings.getWorkspace()).setId("ws-id"); settings.getWorkspace().setName("ws"); - when(mockGeoServerFacade.getService(service.getId(), ServiceInfo.class)) - .thenReturn(service); + when(mockGeoServerFacade.getService(service.getId(), ServiceInfo.class)).thenReturn(service); when(mockGeoServerFacade.getSettings(settings.getId())).thenReturn(settings); ServiceRemoved serviceEvent = ServiceRemoved.createLocal(101, service); @@ -256,8 +250,7 @@ void testOnRemoteModifyEvent_IgnoresSetDefaultEvents() { @Test void testOnRemoteModifyEvent_GeoServerInfo() { - when(mockGeoServerFacade.getGlobal()) - .thenReturn(ModificationProxy.create(global, GeoServerInfo.class)); + when(mockGeoServerFacade.getGlobal()).thenReturn(ModificationProxy.create(global, GeoServerInfo.class)); global.setFeatureTypeCacheSize(1); var proxied = mockGeoServerFacade.getGlobal(); diff --git a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/ConditionalOnJdbcConfigEnabled.java b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/ConditionalOnJdbcConfigEnabled.java index 1b83c0218..aa3a0c639 100644 --- a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/ConditionalOnJdbcConfigEnabled.java +++ b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/ConditionalOnJdbcConfigEnabled.java @@ -4,16 +4,15 @@ */ package org.geoserver.cloud.autoconfigure.catalog.backend.jdbcconfig; -import org.geoserver.jdbcconfig.catalog.JDBCCatalogFacade; -import org.geoserver.jdbcconfig.config.JDBCGeoServerFacade; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.geoserver.jdbcconfig.catalog.JDBCCatalogFacade; +import org.geoserver.jdbcconfig.config.JDBCGeoServerFacade; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) diff --git a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/ConditionalOnJdbcConfigWebUIEnabled.java b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/ConditionalOnJdbcConfigWebUIEnabled.java index 52c882c20..73062b266 100644 --- a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/ConditionalOnJdbcConfigWebUIEnabled.java +++ b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/ConditionalOnJdbcConfigWebUIEnabled.java @@ -4,14 +4,13 @@ */ package org.geoserver.cloud.autoconfigure.catalog.backend.jdbcconfig; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) diff --git a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/RemoteEventJdbcConfigAutoConfiguration.java b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/RemoteEventJdbcConfigAutoConfiguration.java index dbbff465b..95afcca69 100644 --- a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/RemoteEventJdbcConfigAutoConfiguration.java +++ b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/RemoteEventJdbcConfigAutoConfiguration.java @@ -16,8 +16,7 @@ public class RemoteEventJdbcConfigAutoConfiguration { @Bean - RemoteEventJdbcConfigProcessor jdbcConfigRemoteEventProcessor( - ConfigDatabase jdbcConfigDatabase) { + RemoteEventJdbcConfigProcessor jdbcConfigRemoteEventProcessor(ConfigDatabase jdbcConfigDatabase) { return new RemoteEventJdbcConfigProcessor(jdbcConfigDatabase); } } diff --git a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcConfigDatabase.java b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcConfigDatabase.java index 4fd860523..95604c402 100644 --- a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcConfigDatabase.java +++ b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcConfigDatabase.java @@ -4,6 +4,7 @@ */ package org.geoserver.cloud.config.catalog.backend.jdbcconfig; +import javax.sql.DataSource; import org.geoserver.catalog.Info; import org.geoserver.catalog.impl.CatalogImpl; import org.geoserver.catalog.impl.ModificationProxy; @@ -13,8 +14,6 @@ import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; -import javax.sql.DataSource; - /** * Overrides {@link #save} and {@link #remove} to {@link #clearCache(Info) dispose the internal * cache} for both the {@link ModificationProxy} wrapped object (as it may contain identity diff --git a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcConfigProperties.java b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcConfigProperties.java index 4cfbbfd3d..c789fb7d6 100644 --- a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcConfigProperties.java +++ b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcConfigProperties.java @@ -6,23 +6,19 @@ import com.google.common.base.Optional; import com.google.common.base.Preconditions; - -import lombok.EqualsAndHashCode; - -import org.geoserver.jdbcconfig.internal.ConfigDatabase; -import org.geoserver.jdbcconfig.internal.JDBCConfigProperties; -import org.geoserver.jdbcconfig.internal.JDBCConfigPropertiesFactoryBean; -import org.geoserver.jdbcloader.DataSourceFactoryBean; -import org.geoserver.platform.resource.Resource; - import java.io.IOException; import java.net.URL; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; - import javax.sql.DataSource; +import lombok.EqualsAndHashCode; +import org.geoserver.jdbcconfig.internal.ConfigDatabase; +import org.geoserver.jdbcconfig.internal.JDBCConfigProperties; +import org.geoserver.jdbcconfig.internal.JDBCConfigPropertiesFactoryBean; +import org.geoserver.jdbcloader.DataSourceFactoryBean; +import org.geoserver.platform.resource.Resource; /** Extends {@link JDBCConfigProperties} to not need a {@link JDBCConfigPropertiesFactoryBean} */ @EqualsAndHashCode(callSuper = true) diff --git a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcGeoServerLoader.java b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcGeoServerLoader.java index ae3cf3307..432cc76f5 100644 --- a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcGeoServerLoader.java +++ b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcGeoServerLoader.java @@ -4,6 +4,9 @@ */ package org.geoserver.cloud.config.catalog.backend.jdbcconfig; +import java.io.IOException; +import java.util.List; +import javax.annotation.PostConstruct; import org.geoserver.catalog.Catalog; import org.geoserver.cloud.config.catalog.backend.core.CoreBackendConfiguration; import org.geoserver.config.DefaultGeoServerLoader; @@ -21,11 +24,6 @@ import org.geoserver.platform.GeoServerResourceLoader; import org.geoserver.platform.resource.Resource.Lock; -import java.io.IOException; -import java.util.List; - -import javax.annotation.PostConstruct; - /** * {@link Catalog} and {@link GeoServer config} loader for the jdbcconfig backend, loads the * configuration as soon as the spring bean wiring is {@link #load() ready}; {@link @@ -79,8 +77,7 @@ protected void loadGeoServer(GeoServer geoServer, XStreamPersister xp) { geoServer.setLogging(geoServer.getFactory().createLogging()); } // ensure we have a service configuration for every service we know about - final List loaders = - GeoServerExtensions.extensions(XStreamServiceLoader.class); + final List loaders = GeoServerExtensions.extensions(XStreamServiceLoader.class); for (XStreamServiceLoader l : loaders) { ServiceInfo s = geoServer.getService(l.getServiceClass()); if (s == null) { diff --git a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcGeoserverFacade.java b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcGeoserverFacade.java index 3fb75d7fb..74f0b0660 100644 --- a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcGeoserverFacade.java +++ b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcGeoserverFacade.java @@ -10,7 +10,13 @@ import static org.geoserver.catalog.Predicates.isNull; import com.google.common.base.Preconditions; - +import java.lang.reflect.Proxy; +import java.rmi.server.UID; +import java.util.Collection; +import java.util.List; +import java.util.logging.Logger; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; import org.geoserver.catalog.Info; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.impl.ModificationProxy; @@ -26,15 +32,6 @@ import org.geotools.api.filter.Filter; import org.geotools.util.logging.Logging; -import java.lang.reflect.Proxy; -import java.rmi.server.UID; -import java.util.Collection; -import java.util.List; -import java.util.logging.Logger; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - /** * Copy of {@link JDBCGeoServerFacade} that does not try reinitialize logging, can't extend it * 'cause the field "geoServer" is private and need to override {@link #setGeoServer(GeoServer)} @@ -226,8 +223,7 @@ public T getService(final Class clazz) { @SuppressWarnings("unchecked") @Override - public T getService( - final WorkspaceInfo workspace, final Class clazz) { + public T getService(final WorkspaceInfo workspace, final Class clazz) { return (T) db.getService(workspace, clazz); } @@ -249,9 +245,7 @@ public T getServiceByName( } private T findByName( - @Nonnull final String name, - @Nullable final WorkspaceInfo workspace, - @Nonnull final Class clazz) + @Nonnull final String name, @Nullable final WorkspaceInfo workspace, @Nonnull final Class clazz) throws AssertionError { Filter filter = equal("name", name); diff --git a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcStoreProperties.java b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcStoreProperties.java index 0b7ca9571..c7a2e4991 100644 --- a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcStoreProperties.java +++ b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/CloudJdbcStoreProperties.java @@ -6,14 +6,6 @@ import com.google.common.base.Optional; import com.google.common.base.Preconditions; - -import lombok.EqualsAndHashCode; - -import org.geoserver.jdbcloader.DataSourceFactoryBean; -import org.geoserver.jdbcstore.internal.JDBCResourceStoreProperties; -import org.geoserver.jdbcstore.internal.JDBCResourceStorePropertiesFactoryBean; -import org.geoserver.platform.resource.Resource; - import java.io.File; import java.io.IOException; import java.net.URL; @@ -21,8 +13,12 @@ import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; - import javax.sql.DataSource; +import lombok.EqualsAndHashCode; +import org.geoserver.jdbcloader.DataSourceFactoryBean; +import org.geoserver.jdbcstore.internal.JDBCResourceStoreProperties; +import org.geoserver.jdbcstore.internal.JDBCResourceStorePropertiesFactoryBean; +import org.geoserver.platform.resource.Resource; /** * Extends {@link JDBCResourceStoreProperties} to not need a {@link diff --git a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/JDBCConfigBackendConfigurer.java b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/JDBCConfigBackendConfigurer.java index 6a1ed5d3d..9618bf40f 100644 --- a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/JDBCConfigBackendConfigurer.java +++ b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/JDBCConfigBackendConfigurer.java @@ -7,12 +7,19 @@ import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.zaxxer.hikari.HikariDataSource; - +import java.io.File; +import java.io.IOException; +import java.io.Serializable; +import java.nio.file.Path; +import java.sql.Driver; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.TimeUnit; +import javax.sql.DataSource; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.GeoServerConfigurationLock; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.plugin.CatalogFacadeExtensionAdapter; @@ -59,17 +66,6 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.util.StringUtils; -import java.io.File; -import java.io.IOException; -import java.io.Serializable; -import java.nio.file.Path; -import java.sql.Driver; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.TimeUnit; - -import javax.sql.DataSource; - /** * Configure JDBC Config catalog * @@ -123,13 +119,10 @@ public class JDBCConfigBackendConfigurer extends GeoServerBackendConfigurer { private JdbcConfigConfigurationProperties jdbcconfigConfig; public JDBCConfigBackendConfigurer( - JdbcConfigConfigurationProperties backendConfig, - @Value("${info.instance-id:}") String instanceId) { + JdbcConfigConfigurationProperties backendConfig, @Value("${info.instance-id:}") String instanceId) { this.jdbcconfigConfig = backendConfig; this.instanceId = instanceId; - log.info( - "Loading geoserver config backend with {}", - JDBCConfigBackendConfigurer.class.getSimpleName()); + log.info("Loading geoserver config backend with {}", JDBCConfigBackendConfigurer.class.getSimpleName()); } @DependsOn("jdbcConfigDataSourceStartupValidator") @@ -177,12 +170,7 @@ CloudJdbcStoreProperties jdbcStoreProperties() { return loader; } - @DependsOn({ - "extensions", - "JDBCConfigDB", - "jdbcConfigDataSourceStartupValidator", - "noopCacheProvider" - }) + @DependsOn({"extensions", "JDBCConfigDB", "jdbcConfigDataSourceStartupValidator", "noopCacheProvider"}) @Bean(name = {"resourceStoreImpl"}) protected @Override ResourceStore resourceStoreImpl() { @@ -277,8 +265,7 @@ DefaultLockRepository jdbcLockRepository() { Catalog rawCatalog = (Catalog) GeoServerExtensions.bean("rawCatalog"); GeoServer geoserver = (GeoServer) GeoServerExtensions.bean("geoServer"); try { - return new CloudJdbcGeoServerLoader( - rawCatalog, geoserver, resourceLoader(), config, configdb); + return new CloudJdbcGeoServerLoader(rawCatalog, geoserver, resourceLoader(), config, configdb); } catch (Exception e) { throw new BeanInstantiationException(JDBCGeoServerLoader.class, e.getMessage(), e); } @@ -312,9 +299,7 @@ ConfigDatabase jdbcConfigDB() { } private boolean initDbSchema( - JDBCConfigProperties catalogConfig, - CloudJdbcStoreProperties resourceStoreConfig, - ConfigDatabase configDb) { + JDBCConfigProperties catalogConfig, CloudJdbcStoreProperties resourceStoreConfig, ConfigDatabase configDb) { // Need to check whether the db needs to be initialized here because secureCatalog's // constructor may use the CatalogFacade during initialization (by means of the // DefaultResourceAccessManager), before JDBCGeoServerLoader.setCatalogFacade() was called @@ -360,12 +345,12 @@ CacheProvider noopCacheProvider() { return new CacheProvider() { @SuppressWarnings("rawtypes") - private final Cache noOpCache = CacheBuilder.newBuilder().maximumSize(0).build(); + private final Cache noOpCache = + CacheBuilder.newBuilder().maximumSize(0).build(); @SuppressWarnings("unchecked") @Override - public Cache getCache( - String cacheName) { + public Cache getCache(String cacheName) { return noOpCache; } }; @@ -377,8 +362,7 @@ private static class CloudJdbcConfigCacheProvider implements org.geoserver.util. @Override @SuppressWarnings("unchecked") - public Cache getCache( - @NonNull String cacheName) { + public Cache getCache(@NonNull String cacheName) { return (Cache) caches.computeIfAbsent(cacheName, this::newCache); } @@ -455,10 +439,9 @@ ExtendedDataSourceProperties jdbcconfigDataSourceProperties() { @ConfigurationProperties(prefix = "geoserver.backend.jdbcconfig.datasource") DataSource jdbcConfigDataSource() { ExtendedDataSourceProperties props = jdbcconfigDataSourceProperties(); - HikariDataSource dataSource = - props.initializeDataSourceBuilder() // - .type(HikariDataSource.class) - .build(); + HikariDataSource dataSource = props.initializeDataSourceBuilder() // + .type(HikariDataSource.class) + .build(); dataSource.setMaximumPoolSize(props.getMaximumPoolSize()); dataSource.setMinimumIdle(props.getMinimumIdle()); diff --git a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/JdbcConfigConfigurationProperties.java b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/JdbcConfigConfigurationProperties.java index 5ba86a95b..9b527b7da 100644 --- a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/JdbcConfigConfigurationProperties.java +++ b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/JdbcConfigConfigurationProperties.java @@ -4,15 +4,13 @@ */ package org.geoserver.cloud.config.catalog.backend.jdbcconfig; +import java.nio.file.Path; import lombok.Data; - import org.geoserver.cloud.autoconfigure.catalog.backend.jdbcconfig.JDBCConfigAutoConfiguration; import org.geoserver.cloud.config.catalog.backend.core.GeoServerBackendConfigurer; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.context.properties.ConfigurationProperties; -import java.nio.file.Path; - /** * Configuration properties to use GeoServer's {@code jdbcconfig} and {@code jdbcstore} community * modules as the {@link GeoServerBackendConfigurer catalog and configuration backend} through the diff --git a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/JdbcConfigUpdateSequence.java b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/JdbcConfigUpdateSequence.java index bd2a3bb27..d0799132f 100644 --- a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/JdbcConfigUpdateSequence.java +++ b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/jdbcconfig/JdbcConfigUpdateSequence.java @@ -4,22 +4,19 @@ */ package org.geoserver.cloud.config.catalog.backend.jdbcconfig; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import javax.sql.DataSource; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.config.GeoServerFacade; import org.geoserver.config.GeoServerInfo; import org.geoserver.jdbcconfig.internal.ConfigDatabase; import org.geoserver.platform.config.UpdateSequence; import org.springframework.beans.factory.InitializingBean; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - -import javax.sql.DataSource; - /** * @since 1.0 */ @@ -56,8 +53,7 @@ public synchronized long nextValue() { public void afterPropertiesSet() throws Exception { String createSequenceStatement; if (props.isPostgreSQL()) { - createSequenceStatement = - "CREATE SEQUENCE IF NOT EXISTS %s AS BIGINT CYCLE".formatted(SEQUENCE_NAME); + createSequenceStatement = "CREATE SEQUENCE IF NOT EXISTS %s AS BIGINT CYCLE".formatted(SEQUENCE_NAME); // not using CURRVAL() to avoid the "currval of sequence "" is not yet defined in // this session" error getQuery = "SELECT last_value FROM %s".formatted(SEQUENCE_NAME); @@ -90,8 +86,7 @@ protected long runAndGetLong(String query) { if (rs.next()) { return rs.getLong(1); } - throw new IllegalStateException( - "Query did not return a result: %s".formatted(getQuery)); + throw new IllegalStateException("Query did not return a result: %s".formatted(getQuery)); } finally { c.setAutoCommit(true); } diff --git a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/event/remote/jdbcconfig/RemoteEventJdbcConfigProcessor.java b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/event/remote/jdbcconfig/RemoteEventJdbcConfigProcessor.java index 250322a0b..a5f65b5b9 100644 --- a/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/event/remote/jdbcconfig/RemoteEventJdbcConfigProcessor.java +++ b/src/catalog/backends/jdbcconfig/src/main/java/org/geoserver/cloud/event/remote/jdbcconfig/RemoteEventJdbcConfigProcessor.java @@ -7,7 +7,6 @@ import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.CatalogInfo; import org.geoserver.cloud.event.info.ConfigInfoType; import org.geoserver.cloud.event.info.InfoEvent; @@ -37,18 +36,15 @@ public void onRemoteModifyEvent(InfoModified event) { } private void evictConfigDatabaseEntry(InfoEvent event) { - event.remote() - .ifPresent( - remoteEvent -> { - ConfigInfoType infoType = event.getObjectType(); - if (ConfigInfoType.CATALOG.equals(infoType)) { - log.trace( - "ignore catalog default workspace or default namespace change event, no need to treat it."); - } else { - log.debug("Evict JDBCConfig cache for {}", event); - String catalogInfoId = event.getObjectId(); - jdbcConfigDatabase.clearCacheIfPresent(catalogInfoId); - } - }); + event.remote().ifPresent(remoteEvent -> { + ConfigInfoType infoType = event.getObjectType(); + if (ConfigInfoType.CATALOG.equals(infoType)) { + log.trace("ignore catalog default workspace or default namespace change event, no need to treat it."); + } else { + log.debug("Evict JDBCConfig cache for {}", event); + String catalogInfoId = event.getObjectId(); + jdbcConfigDatabase.clearCacheIfPresent(catalogInfoId); + } + }); } } diff --git a/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JDBCConfigAutoConfigurationTest.java b/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JDBCConfigAutoConfigurationTest.java index f8ad73048..1887ea55a 100644 --- a/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JDBCConfigAutoConfigurationTest.java +++ b/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JDBCConfigAutoConfigurationTest.java @@ -10,6 +10,7 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import java.nio.file.Paths; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.impl.CatalogImpl; @@ -28,8 +29,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; -import java.nio.file.Paths; - /** * Test {@link JDBCConfigBackendConfigurer} through {@link JDBCConfigAutoConfiguration} when {@code * geoserver.backend.jdbcconfig.enabled=true} @@ -60,8 +59,7 @@ void testProperties() { void testCatalogFacade() { assertThat(rawCatalogFacade, instanceOf(CatalogFacadeExtensionAdapter.class)); assertThat( - ((CatalogFacadeExtensionAdapter) rawCatalogFacade).getSubject(), - instanceOf(JDBCCatalogFacade.class)); + ((CatalogFacadeExtensionAdapter) rawCatalogFacade).getSubject(), instanceOf(JDBCCatalogFacade.class)); } @Test diff --git a/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JDBCConfigAutoConfigurationWebDisabledTest.java b/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JDBCConfigAutoConfigurationWebDisabledTest.java index 1d2937ef4..262c8fc89 100644 --- a/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JDBCConfigAutoConfigurationWebDisabledTest.java +++ b/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JDBCConfigAutoConfigurationWebDisabledTest.java @@ -19,16 +19,11 @@ */ @SpringBootTest( classes = AutoConfigurationTestConfiguration.class, - properties = { - "geoserver.backend.jdbcconfig.enabled=true", - "geoserver.backend.jdbcconfig.web.enabled=false" - }) + properties = {"geoserver.backend.jdbcconfig.enabled=true", "geoserver.backend.jdbcconfig.web.enabled=false"}) class JDBCConfigAutoConfigurationWebDisabledTest extends JDBCConfigTest { @Test void testJDBCConfigStatusProvider() { - assertThrows( - NoSuchBeanDefinitionException.class, - () -> context.getBean(JDBCConfigStatusProvider.class)); + assertThrows(NoSuchBeanDefinitionException.class, () -> context.getBean(JDBCConfigStatusProvider.class)); } } diff --git a/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JDBCConfigAutoConfigurationWebEnabledTest.java b/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JDBCConfigAutoConfigurationWebEnabledTest.java index b9db0f486..3b895c150 100644 --- a/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JDBCConfigAutoConfigurationWebEnabledTest.java +++ b/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JDBCConfigAutoConfigurationWebEnabledTest.java @@ -19,17 +19,12 @@ */ @SpringBootTest( classes = AutoConfigurationTestConfiguration.class, - properties = { - "geoserver.backend.jdbcconfig.enabled=true", - "geoserver.backend.jdbcconfig.web.enabled=true" - }) + properties = {"geoserver.backend.jdbcconfig.enabled=true", "geoserver.backend.jdbcconfig.web.enabled=true"}) @ActiveProfiles("test") class JDBCConfigAutoConfigurationWebEnabledTest extends JDBCConfigTest { @Test void testJDBCConfigStatusProvider() { - assertThat( - context.getBean("JDBCConfigStatusProvider"), - instanceOf(JDBCConfigStatusProvider.class)); + assertThat(context.getBean("JDBCConfigStatusProvider"), instanceOf(JDBCConfigStatusProvider.class)); } } diff --git a/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JDBCConfigTest.java b/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JDBCConfigTest.java index a1d2ec20d..6823f7bd5 100644 --- a/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JDBCConfigTest.java +++ b/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JDBCConfigTest.java @@ -5,7 +5,7 @@ package org.geoserver.cloud.autoconfigure.catalog.backend.jdbcconfig; import com.zaxxer.hikari.HikariDataSource; - +import javax.sql.DataSource; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogFacade; import org.geoserver.config.GeoServer; @@ -19,8 +19,6 @@ import org.springframework.context.ApplicationContext; import org.springframework.test.context.ActiveProfiles; -import javax.sql.DataSource; - /** * Closes the {@link DataSource} after each test run, otherwise, being an in-memory H2 db (as * configured in {@code bootstrap-test.yml}) the first test class will succeed and the following @@ -37,8 +35,7 @@ public abstract class JDBCConfigTest { protected @Autowired @Qualifier("catalogFacade") CatalogFacade rawCatalogFacade; protected @Autowired @Qualifier("geoServer") GeoServer geoServer; protected @Autowired @Qualifier("resourceLoader") GeoServerResourceLoader resourceLoader; - protected @Autowired(required = false) @Qualifier("geoserverFacade") GeoServerFacade - geoserverFacade; + protected @Autowired(required = false) @Qualifier("geoserverFacade") GeoServerFacade geoserverFacade; protected @Autowired @Qualifier("geoServerLoaderImpl") GeoServerLoader geoserverLoader; protected @Autowired @Qualifier("resourceStoreImpl") ResourceStore resourceStoreImpl; diff --git a/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JdbcConfigDataSourceTest.java b/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JdbcConfigDataSourceTest.java index c6cbc2644..820a469d0 100644 --- a/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JdbcConfigDataSourceTest.java +++ b/src/catalog/backends/jdbcconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/jdbcconfig/JdbcConfigDataSourceTest.java @@ -11,15 +11,12 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import com.zaxxer.hikari.HikariDataSource; - -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.SpringBootTest; - import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLTransientConnectionException; - import javax.sql.DataSource; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest( classes = AutoConfigurationTestConfiguration.class, diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/ConditionalOnPgconfigBackendEnabled.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/ConditionalOnPgconfigBackendEnabled.java index 3b8740d0b..7ffffe4c6 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/ConditionalOnPgconfigBackendEnabled.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/ConditionalOnPgconfigBackendEnabled.java @@ -4,13 +4,12 @@ */ package org.geoserver.cloud.autoconfigure.catalog.backend.pgconfig; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; /** * @since 1.4 diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/PgconfigTransactionManagerAutoConfiguration.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/PgconfigTransactionManagerAutoConfiguration.java index 534c26b0f..7422912c9 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/PgconfigTransactionManagerAutoConfiguration.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/PgconfigTransactionManagerAutoConfiguration.java @@ -4,22 +4,20 @@ */ package org.geoserver.cloud.autoconfigure.catalog.backend.pgconfig; +import javax.sql.DataSource; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.jdbc.datasource.DataSourceTransactionManager; import org.springframework.transaction.annotation.EnableTransactionManagement; -import javax.sql.DataSource; - @AutoConfiguration(after = PgconfigDataSourceAutoConfiguration.class) @ConditionalOnPgconfigBackendEnabled @EnableTransactionManagement public class PgconfigTransactionManagerAutoConfiguration { @Bean - DataSourceTransactionManager pgconfigTransactionManager( - @Qualifier("pgconfigDataSource") DataSource dataSource) { + DataSourceTransactionManager pgconfigTransactionManager(@Qualifier("pgconfigDataSource") DataSource dataSource) { return new DataSourceTransactionManager(dataSource); } } diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/PgconfigBackendBuilder.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/PgconfigBackendBuilder.java index d99676941..25f5d423b 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/PgconfigBackendBuilder.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/PgconfigBackendBuilder.java @@ -4,9 +4,9 @@ */ package org.geoserver.cloud.backend.pgconfig; +import javax.sql.DataSource; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.impl.CatalogImpl; import org.geoserver.catalog.plugin.CatalogPlugin; @@ -16,8 +16,6 @@ import org.geoserver.config.plugin.GeoServerImpl; import org.springframework.jdbc.core.JdbcTemplate; -import javax.sql.DataSource; - /** * @since 1.4 */ diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/PgconfigCatalogFacade.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/PgconfigCatalogFacade.java index d90cea2f7..d806ac931 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/PgconfigCatalogFacade.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/PgconfigCatalogFacade.java @@ -4,8 +4,9 @@ */ package org.geoserver.cloud.backend.pgconfig.catalog; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; import lombok.NonNull; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.plugin.RepositoryCatalogFacadeImpl; @@ -22,9 +23,6 @@ import org.geoserver.cloud.backend.pgconfig.catalog.repository.PgconfigWorkspaceRepository; import org.springframework.jdbc.core.JdbcTemplate; -import java.util.function.Supplier; -import java.util.function.UnaryOperator; - /** * @since 1.4 */ @@ -64,11 +62,9 @@ private void setOutboundResolver() { .forEach(repo -> repo.setOutboundResolver(resolvingFunction)); } - public static UnaryOperator resolvingFunction( - Supplier catalog) { + public static UnaryOperator resolvingFunction(Supplier catalog) { return CatalogPropertyResolver.of(catalog) - .andThen(ResolvingProxyResolver.of(catalog)) - .andThen(CollectionPropertiesInitializer.instance()) - ::apply; + .andThen(ResolvingProxyResolver.of(catalog)) + .andThen(CollectionPropertiesInitializer.instance())::apply; } } diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/CatalogInfoLiteralAdaptor.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/CatalogInfoLiteralAdaptor.java index dc28c1ebe..0578b3592 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/CatalogInfoLiteralAdaptor.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/CatalogInfoLiteralAdaptor.java @@ -4,9 +4,10 @@ */ package org.geoserver.cloud.backend.pgconfig.catalog.filter; +import java.util.Optional; +import java.util.Set; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.WorkspaceInfo; import org.geotools.api.filter.BinaryComparisonOperator; @@ -25,9 +26,6 @@ import org.geotools.factory.CommonFactoryFinder; import org.geotools.filter.visitor.DuplicatingFilterVisitor; -import java.util.Optional; -import java.util.Set; - /** * Converts binary comparison operators using a property name and a {@link CatalogInfo} instance * literal as a comparison by id. @@ -52,8 +50,7 @@ public CatalogInfoLiteralAdaptor(@NonNull Set supportedPropertyNames) { this.supportedPropertyNames = supportedPropertyNames; } - public static Filter replaceCatalogInfoLiterals( - Filter filter, Set supportedPropertyNames) { + public static Filter replaceCatalogInfoLiterals(Filter filter, Set supportedPropertyNames) { var adaptor = new CatalogInfoLiteralAdaptor(supportedPropertyNames); return (Filter) filter.accept(adaptor, null); } @@ -101,8 +98,7 @@ private static interface BinaryComparisonBuilder F adapt( - F filter, BinaryComparisonBuilder builder) { + private F adapt(F filter, BinaryComparisonBuilder builder) { PropertyName prop = propertyName(filter); Literal literal = literal(filter); @@ -118,10 +114,7 @@ private F adapt( boolean matchingCase = filter.isMatchingCase(); MatchAction matchAction = filter.getMatchAction(); filter = builder.build(prop, literal, matchingCase, matchAction); - log.debug( - "Fitler with CatalogInfo literal '{}' translated to '{}'", - orig, - filter); + log.debug("Fitler with CatalogInfo literal '{}' translated to '{}'", orig, filter); } } } diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/PgconfigCatalogFilterSplitter.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/PgconfigCatalogFilterSplitter.java index f28be896b..cea68768f 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/PgconfigCatalogFilterSplitter.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/PgconfigCatalogFilterSplitter.java @@ -4,14 +4,12 @@ */ package org.geoserver.cloud.backend.pgconfig.catalog.filter; +import java.util.Set; import lombok.NonNull; - import org.geotools.api.filter.Filter; import org.geotools.api.filter.expression.PropertyName; import org.geotools.filter.visitor.PostPreProcessFilterSplittingVisitor; -import java.util.Set; - /** * Splits a {@link Filter} into supported and unsupported filters for SQL encoding and * post-filtering, based on the supported column names provided in the constructor. @@ -27,8 +25,7 @@ public PgconfigCatalogFilterSplitter(@NonNull Set supportedPropertyNames this.supportedPropertyNames = supportedPropertyNames; } - public static PgconfigCatalogFilterSplitter split( - Filter filter, Set supportedPropertyNames) { + public static PgconfigCatalogFilterSplitter split(Filter filter, Set supportedPropertyNames) { var splitter = new PgconfigCatalogFilterSplitter(supportedPropertyNames); filter.accept(splitter, null); return splitter; diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/PgconfigFilterCapabilities.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/PgconfigFilterCapabilities.java index bcd9a1a00..41a2b48ac 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/PgconfigFilterCapabilities.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/PgconfigFilterCapabilities.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.backend.pgconfig.catalog.filter; import lombok.experimental.UtilityClass; - import org.geoserver.function.IsInstanceOf; import org.geotools.api.filter.ExcludeFilter; import org.geotools.api.filter.Id; diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/PgconfigFilterToSQL.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/PgconfigFilterToSQL.java index 56e7b9ade..04bc719d1 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/PgconfigFilterToSQL.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/PgconfigFilterToSQL.java @@ -4,9 +4,18 @@ */ package org.geoserver.cloud.backend.pgconfig.catalog.filter; +import java.io.IOException; +import java.io.StringWriter; +import java.io.UncheckedIOException; +import java.io.Writer; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; import lombok.NonNull; import lombok.Value; - import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.impl.ClassMappings; import org.geoserver.function.IsInstanceOf; @@ -38,17 +47,6 @@ import org.geotools.jdbc.PreparedFilterToSQL; import org.geotools.util.Converters; -import java.io.IOException; -import java.io.StringWriter; -import java.io.UncheckedIOException; -import java.io.Writer; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; -import java.util.stream.Stream; - /** * @since 1.4 */ @@ -90,20 +88,18 @@ public Object visit(PropertyIsEqualTo filter, Object extraData) { Expression left = filter.getExpression1(); Expression right = filter.getExpression2(); - PropertyName prop = - Optional.of(left) - .filter(PropertyName.class::isInstance) - .or(() -> Optional.of(right).filter(PropertyName.class::isInstance)) - .map(PropertyName.class::cast) - .orElse(null); + PropertyName prop = Optional.of(left) + .filter(PropertyName.class::isInstance) + .or(() -> Optional.of(right).filter(PropertyName.class::isInstance)) + .map(PropertyName.class::cast) + .orElse(null); if (isArray(prop)) { Expression value = right; if (right instanceof Literal literal) { - String values = - asList(literal.getValue()).stream() - .map(o -> Converters.convert(o, String.class)) - .map("'%s'"::formatted) - .collect(Collectors.joining(",")); + String values = asList(literal.getValue()).stream() + .map(o -> Converters.convert(o, String.class)) + .map("'%s'"::formatted) + .collect(Collectors.joining(",")); value = new LiteralExpressionImpl("ARRAY[%s]".formatted(values)); } try { @@ -165,8 +161,7 @@ public Object visit(PropertyIsLike filter, Object extraData) { literal += multi; } - String pattern = - LikeFilterImpl.convertToSQL92(esc, multi, single, matchCase, literal, false); + String pattern = LikeFilterImpl.convertToSQL92(esc, multi, single, matchCase, literal, false); try { att.accept(this, extraData); @@ -331,11 +326,9 @@ protected boolean visitFunction(Function function) throws IOException { Class type = typeExpr.evaluate(null, Class.class); String types = infoTypes(type); - String f = - """ + String f = """ "@type" = ANY('{%s}') - """ - .formatted(types); + """.formatted(types); out.write(f); return true; } @@ -349,11 +342,8 @@ protected boolean visitFunction(Function function) throws IOException { if (clazz.isInterface()) cm = ClassMappings.fromInterface(clazz); else cm = ClassMappings.fromImpl(clazz); if (null == cm) - throw new IllegalArgumentException( - "Unknown type for IsInstanceOf: " + clazz.getCanonicalName()); + throw new IllegalArgumentException("Unknown type for IsInstanceOf: " + clazz.getCanonicalName()); - return Stream.of(cm.concreteInterfaces()) - .map(Class::getSimpleName) - .collect(Collectors.joining(",")); + return Stream.of(cm.concreteInterfaces()).map(Class::getSimpleName).collect(Collectors.joining(",")); } } diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/PgconfigQueryBuilder.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/PgconfigQueryBuilder.java index 2b13602c7..dc29c393e 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/PgconfigQueryBuilder.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/PgconfigQueryBuilder.java @@ -7,16 +7,14 @@ import static org.geoserver.cloud.backend.pgconfig.catalog.filter.CatalogInfoLiteralAdaptor.replaceCatalogInfoLiterals; import static org.geoserver.cloud.backend.pgconfig.catalog.filter.PgconfigCatalogFilterSplitter.split; +import java.util.List; +import java.util.Set; import lombok.Getter; import lombok.RequiredArgsConstructor; - import org.geoserver.cloud.backend.pgconfig.catalog.filter.PgconfigFilterToSQL.Result; import org.geotools.api.filter.Filter; import org.geotools.filter.visitor.SimplifyingFilterVisitor; -import java.util.List; -import java.util.Set; - /** * @since 1.4 */ @@ -57,8 +55,7 @@ public PgconfigQueryBuilder build() { } private Filter adaptToSql(Filter filterPre) { - Filter supported = - ToPgsqlCompatibleFilterDuplicator.adapt(filterPre, supportedPropertyNames); + Filter supported = ToPgsqlCompatibleFilterDuplicator.adapt(filterPre, supportedPropertyNames); return simplify(supported); } diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/ToPgsqlCompatibleFilterDuplicator.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/ToPgsqlCompatibleFilterDuplicator.java index 3bc37fd10..fe19ddc84 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/ToPgsqlCompatibleFilterDuplicator.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/filter/ToPgsqlCompatibleFilterDuplicator.java @@ -4,9 +4,15 @@ */ package org.geoserver.cloud.backend.pgconfig.catalog.filter; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Set; +import java.util.function.BiFunction; +import java.util.function.Function; +import javax.annotation.Nullable; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geotools.api.filter.BinaryComparisonOperator; import org.geotools.api.filter.Filter; import org.geotools.api.filter.MultiValuedFilter.MatchAction; @@ -22,15 +28,6 @@ import org.geotools.api.filter.expression.PropertyName; import org.geotools.filter.visitor.DuplicatingFilterVisitor; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Set; -import java.util.function.BiFunction; -import java.util.function.Function; - -import javax.annotation.Nullable; - /** * Duplicates a supported filter making it directly translatable to SQL taking care of subtleties * like {@link MatchAction} and case matching. @@ -40,7 +37,8 @@ @RequiredArgsConstructor class ToPgsqlCompatibleFilterDuplicator extends DuplicatingFilterVisitor { - @NonNull private final Set supportedPropertyNames; + @NonNull + private final Set supportedPropertyNames; /** * @param supportedFilter Filter that's already been deemed as supported @@ -157,8 +155,7 @@ private Function, Filter> createOredOrAndedBuilder(final MatchActio /** * Only if exactly one of the possible combinations match, the result is true (aggregated XOR) */ - private Filter aggregateXor( - BinaryComparisonOperator origFilter, Expression leftExpr, final List values) { + private Filter aggregateXor(BinaryComparisonOperator origFilter, Expression leftExpr, final List values) { final BiFunction filterBuilder = filterBuilder(origFilter); List xor = new ArrayList<>(); @@ -216,26 +213,21 @@ private Literal determineRightExpression(BinaryComparisonOperator filter) { return right instanceof Literal r ? r : null; } - private BiFunction filterBuilder( - BinaryComparisonOperator orig) { + private BiFunction filterBuilder(BinaryComparisonOperator orig) { - if (orig instanceof PropertyIsEqualTo) - return (e1, e2) -> ff.equal(e1, e2, orig.isMatchingCase()); + if (orig instanceof PropertyIsEqualTo) return (e1, e2) -> ff.equal(e1, e2, orig.isMatchingCase()); - if (orig instanceof PropertyIsGreaterThan) - return (e1, e2) -> ff.greater(e1, e2, orig.isMatchingCase()); + if (orig instanceof PropertyIsGreaterThan) return (e1, e2) -> ff.greater(e1, e2, orig.isMatchingCase()); if (orig instanceof PropertyIsGreaterThanOrEqualTo) return (e1, e2) -> ff.greaterOrEqual(e1, e2, orig.isMatchingCase()); - if (orig instanceof PropertyIsLessThan) - return (e1, e2) -> ff.less(e1, e2, orig.isMatchingCase()); + if (orig instanceof PropertyIsLessThan) return (e1, e2) -> ff.less(e1, e2, orig.isMatchingCase()); if (orig instanceof PropertyIsLessThanOrEqualTo) return (e1, e2) -> ff.lessOrEqual(e1, e2, orig.isMatchingCase()); - if (orig instanceof PropertyIsNotEqualTo) - return (e1, e2) -> ff.notEqual(e1, e2, orig.isMatchingCase()); + if (orig instanceof PropertyIsNotEqualTo) return (e1, e2) -> ff.notEqual(e1, e2, orig.isMatchingCase()); throw new IllegalArgumentException("Unknown BinaryComparisonOperator: %s".formatted(orig)); } diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/CatalogInfoRowMapper.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/CatalogInfoRowMapper.java index 026bab5aa..c9edc4b6c 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/CatalogInfoRowMapper.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/CatalogInfoRowMapper.java @@ -6,11 +6,19 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; - +import java.io.UncheckedIOException; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Function; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.LayerGroupInfo; import org.geoserver.catalog.LayerInfo; @@ -25,17 +33,6 @@ import org.geoserver.catalog.impl.ModificationProxy; import org.springframework.jdbc.core.RowMapper; -import java.io.UncheckedIOException; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.HashMap; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.function.Function; - /** * @since 1.4 */ @@ -90,8 +87,7 @@ protected T resolveCached( return resolveCached(id, clazz, idd -> loader.apply(rs)); } - protected T resolveCached( - String id, Class clazz, Function loader) { + protected T resolveCached(String id, Class clazz, Function loader) { if (null == id) return null; var infoCache = cache(clazz); T info = infoCache.get(id); @@ -286,9 +282,8 @@ protected void setStore(ResourceInfo resource, ResultSet rs) { String storeId = resource.getStore().getId(); StoreInfo store = mapStore(storeId, rs); @SuppressWarnings("unchecked") - Class storeType = - (Class) - ClassMappings.fromImpl(store.getClass()).getInterface(); + Class storeType = (Class) + ClassMappings.fromImpl(store.getClass()).getInterface(); resource.setStore(ModificationProxy.create(store, storeType)); } @@ -382,12 +377,11 @@ protected LayerInfo mapLayer(ResultSet rs) { private void setStyles(LayerInfo layer) { LayerInfoImpl li = (LayerInfoImpl) ModificationProxy.unwrap(layer); - List styles = - li.getStyles().stream() - .map(StyleInfo::getId) - .map(this::loadStyle) - .map(s -> ModificationProxy.create(s, StyleInfo.class)) - .toList(); + List styles = li.getStyles().stream() + .map(StyleInfo::getId) + .map(this::loadStyle) + .map(s -> ModificationProxy.create(s, StyleInfo.class)) + .toList(); li.setStyles(new HashSet<>(styles)); } @@ -477,15 +471,13 @@ public static RowMapper layer(Function> s return mapper::mapLayer; } - public static RowMapper layerGroup( - Function> styleLoader) { + public static RowMapper layerGroup(Function> styleLoader) { CatalogInfoRowMapper mapper = new CatalogInfoRowMapper(); mapper.setStyleLoader(styleLoader); return mapper::mapLayerGroup; } - public static RowMapper published( - Function> styleLoader) { + public static RowMapper published(Function> styleLoader) { CatalogInfoRowMapper mapper = new CatalogInfoRowMapper(); mapper.setStyleLoader(styleLoader); return mapper::mapPublishedInfo; diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/LoggingTemplate.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/LoggingTemplate.java index 67d337567..7fcfc8a59 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/LoggingTemplate.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/LoggingTemplate.java @@ -4,13 +4,21 @@ */ package org.geoserver.cloud.backend.pgconfig.catalog.repository; +import java.time.Duration; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.concurrent.Callable; +import java.util.concurrent.atomic.AtomicLong; +import java.util.stream.Collectors; +import java.util.stream.IntStream; +import java.util.stream.Stream; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.experimental.Delegate; import lombok.extern.slf4j.Slf4j; - import org.springframework.dao.DataAccessException; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.BatchPreparedStatementSetter; @@ -22,32 +30,23 @@ import org.springframework.jdbc.core.RowMapper; import org.springframework.lang.Nullable; -import java.time.Duration; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.concurrent.Callable; -import java.util.concurrent.atomic.AtomicLong; -import java.util.stream.Collectors; -import java.util.stream.IntStream; -import java.util.stream.Stream; - @RequiredArgsConstructor @Slf4j(topic = "org.geoserver.cloud.backend.pgconfig.catalog.repository") public class LoggingTemplate { - @Getter @Delegate @NonNull private final JdbcTemplate jdbcTemplate; + @Getter + @Delegate + @NonNull + private final JdbcTemplate jdbcTemplate; private static final AtomicLong traceReqId = new AtomicLong(); @SneakyThrows private void run(String sql, Runnable op) { - run( - sql, - () -> { - op.run(); - return null; - }); + run(sql, () -> { + op.run(); + return null; + }); } @SneakyThrows @@ -96,17 +95,12 @@ private void logAfter(long reqId, String sql, Duration ellapsed, DataAccessExcep if (sql.endsWith("\n")) sql = sql.substring(0, sql.length() - 1); - final String time = - ellapsed == null ? "" : "%.2f ms".formatted(ellapsed.toNanos() / 1_000_000d); - - final String errMsg = - error == null - ? "" - : " (ERROR %s: %s)" - .formatted(error.getClass().getSimpleName(), error.getMessage()); - if (error != null - && log.isTraceEnabled() - && !(error instanceof EmptyResultDataAccessException)) { + final String time = ellapsed == null ? "" : "%.2f ms".formatted(ellapsed.toNanos() / 1_000_000d); + + final String errMsg = error == null + ? "" + : " (ERROR %s: %s)".formatted(error.getClass().getSimpleName(), error.getMessage()); + if (error != null && log.isTraceEnabled() && !(error instanceof EmptyResultDataAccessException)) { log.trace("after request #{} ({}): '{}'{}", reqId, time, sql, errMsg, error); } else { log.debug("after request #{} ({}): '{}'{}", reqId, time, sql, errMsg); @@ -114,20 +108,15 @@ private void logAfter(long reqId, String sql, Duration ellapsed, DataAccessExcep } private String stackTrace() { - String[] callers = - Stream.of(Thread.currentThread().getStackTrace()) - .map(StackTraceElement::toString) - .filter( - s -> - s.startsWith("org.geoserver.") - && !s.startsWith("org.geoserver.filters.") - && !s.startsWith("org.geoserver.security.filter.")) - .filter( - s -> - !(s.contains("LoggingTemplate.log") - || s.contains("LoggingTemplate.run") - || s.contains("LoggingTemplate.stackTrace"))) - .toArray(String[]::new); + String[] callers = Stream.of(Thread.currentThread().getStackTrace()) + .map(StackTraceElement::toString) + .filter(s -> s.startsWith("org.geoserver.") + && !s.startsWith("org.geoserver.filters.") + && !s.startsWith("org.geoserver.security.filter.")) + .filter(s -> !(s.contains("LoggingTemplate.log") + || s.contains("LoggingTemplate.run") + || s.contains("LoggingTemplate.stackTrace"))) + .toArray(String[]::new); return IntStream.range(0, callers.length) .mapToObj(i -> " ".repeat(i) + callers[i]) .collect(Collectors.joining("\n")); @@ -138,8 +127,7 @@ public void execute(final String sql) throws DataAccessException { } @Nullable - public T query(final String sql, final ResultSetExtractor rse) - throws DataAccessException { + public T query(final String sql, final ResultSetExtractor rse) throws DataAccessException { return run(sql, () -> jdbcTemplate.query(sql, rse)); } @@ -151,8 +139,7 @@ public List query(String sql, RowMapper rowMapper) throws DataAccessEx return run(sql, () -> jdbcTemplate.query(sql, rowMapper)); } - public Stream queryForStream(String sql, RowMapper rowMapper) - throws DataAccessException { + public Stream queryForStream(String sql, RowMapper rowMapper) throws DataAccessException { return run(sql, () -> jdbcTemplate.queryForStream(sql, rowMapper)); } @@ -199,8 +186,7 @@ public T query(String sql, Object[] args, int[] argTypes, ResultSetExtractor } @Nullable - public T query(String sql, ResultSetExtractor rse, @Nullable Object... args) - throws DataAccessException { + public T query(String sql, ResultSetExtractor rse, @Nullable Object... args) throws DataAccessException { return run(sql, () -> jdbcTemplate.query(sql, rse, args)); } @@ -209,18 +195,15 @@ public void query(String sql, @Nullable PreparedStatementSetter pss, RowCallback run(sql, () -> jdbcTemplate.query(sql, pss, rch)); } - public void query(String sql, Object[] args, int[] argTypes, RowCallbackHandler rch) - throws DataAccessException { + public void query(String sql, Object[] args, int[] argTypes, RowCallbackHandler rch) throws DataAccessException { run(sql, () -> jdbcTemplate.query(sql, args, argTypes, rch)); } - public void query(String sql, RowCallbackHandler rch, @Nullable Object... args) - throws DataAccessException { + public void query(String sql, RowCallbackHandler rch, @Nullable Object... args) throws DataAccessException { run(sql, () -> jdbcTemplate.query(sql, rch, args)); } - public List query( - String sql, @Nullable PreparedStatementSetter pss, RowMapper rowMapper) + public List query(String sql, @Nullable PreparedStatementSetter pss, RowMapper rowMapper) throws DataAccessException { return run(sql, () -> jdbcTemplate.query(sql, pss, rowMapper)); } @@ -230,13 +213,11 @@ public List query(String sql, Object[] args, int[] argTypes, RowMapper return run(sql, () -> jdbcTemplate.query(sql, args, argTypes, rowMapper)); } - public List query(String sql, RowMapper rowMapper, @Nullable Object... args) - throws DataAccessException { + public List query(String sql, RowMapper rowMapper, @Nullable Object... args) throws DataAccessException { return run(sql, () -> jdbcTemplate.query(sql, rowMapper, args)); } - public Stream queryForStream( - String sql, RowMapper rowMapper, @Nullable Object... args) + public Stream queryForStream(String sql, RowMapper rowMapper, @Nullable Object... args) throws DataAccessException { return run(sql, () -> jdbcTemplate.queryForStream(sql, rowMapper, args)); } @@ -264,13 +245,11 @@ public T queryForObject(String sql, Class requiredType, @Nullable Object. return run(sql, () -> jdbcTemplate.queryForObject(sql, requiredType, args)); } - public Map queryForMap(String sql, Object[] args, int[] argTypes) - throws DataAccessException { + public Map queryForMap(String sql, Object[] args, int[] argTypes) throws DataAccessException { return run(sql, () -> jdbcTemplate.queryForMap(sql, args, argTypes)); } - public Map queryForMap(String sql, @Nullable Object... args) - throws DataAccessException { + public Map queryForMap(String sql, @Nullable Object... args) throws DataAccessException { return run(sql, () -> jdbcTemplate.queryForMap(sql, args)); } @@ -289,13 +268,11 @@ public List> queryForList(String sql, Object[] args, int[] a return run(sql, () -> jdbcTemplate.queryForList(sql, args, argTypes)); } - public List> queryForList(String sql, @Nullable Object... args) - throws DataAccessException { + public List> queryForList(String sql, @Nullable Object... args) throws DataAccessException { return run(sql, () -> jdbcTemplate.queryForList(sql, args)); } - public int update(String sql, @Nullable PreparedStatementSetter pss) - throws DataAccessException { + public int update(String sql, @Nullable PreparedStatementSetter pss) throws DataAccessException { return run(sql, () -> jdbcTemplate.update(sql, pss)); } @@ -307,8 +284,7 @@ public int update(String sql, @Nullable Object... args) throws DataAccessExcepti return run(sql, () -> jdbcTemplate.update(sql, args)); } - public int[] batchUpdate(String sql, final BatchPreparedStatementSetter pss) - throws DataAccessException { + public int[] batchUpdate(String sql, final BatchPreparedStatementSetter pss) throws DataAccessException { return run(sql, () -> jdbcTemplate.batchUpdate(sql, pss)); } @@ -316,8 +292,7 @@ public int[] batchUpdate(String sql, List batchArgs) throws DataAccess return run(sql, () -> jdbcTemplate.batchUpdate(sql, batchArgs)); } - public int[] batchUpdate(String sql, List batchArgs, final int[] argTypes) - throws DataAccessException { + public int[] batchUpdate(String sql, List batchArgs, final int[] argTypes) throws DataAccessException { return run(sql, () -> jdbcTemplate.batchUpdate(sql, batchArgs, argTypes)); } diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigCatalogInfoRepository.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigCatalogInfoRepository.java index b8d5b8df6..ff497f1c1 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigCatalogInfoRepository.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigCatalogInfoRepository.java @@ -6,10 +6,20 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; - +import java.io.UncheckedIOException; +import java.sql.Connection; +import java.sql.DatabaseMetaData; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; +import java.util.function.Predicate; +import java.util.stream.Stream; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.Info; import org.geoserver.catalog.Predicates; @@ -29,25 +39,11 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; -import java.io.UncheckedIOException; -import java.sql.Connection; -import java.sql.DatabaseMetaData; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Optional; -import java.util.Set; -import java.util.TreeSet; -import java.util.function.Predicate; -import java.util.stream.Stream; - /** * @since 1.4 */ @Slf4j(topic = "org.geoserver.cloud.backend.pgconfig.catalog.repository") -public abstract class PgconfigCatalogInfoRepository - extends ResolvingCatalogInfoRepository +public abstract class PgconfigCatalogInfoRepository extends ResolvingCatalogInfoRepository implements CatalogInfoRepository, ResolvingFacade { protected static final ObjectMapper infoMapper = PgconfigObjectMapper.newObjectMapper(); @@ -100,8 +96,7 @@ private Set resolveSortableProperties() { } catch (SQLException e) { throw new UncheckedSqlException(e); } - log.debug( - "resolved queryable/sortable properties for {}: {}", queryTable, queryableColumns); + log.debug("resolved queryable/sortable properties for {}: {}", queryTable, queryableColumns); return Set.copyOf(queryableColumns); } @@ -123,8 +118,7 @@ public void remove(@NonNull T value) { template.update( """ DELETE FROM %s WHERE id = ? - """ - .formatted(getTable()), + """.formatted(getTable()), value.getId()); } @@ -132,16 +126,10 @@ public void remove(@NonNull T value) { @Override public I update(@NonNull I value, @NonNull Patch patch) { String id = value.getId(); - T patched = - findById(value.getId()) - .map(patch::applyTo) - .orElseThrow( - () -> - new NoSuchElementException( - "%s with id %s does not exist" - .formatted( - getContentType().getSimpleName(), - value.getId()))); + T patched = findById(value.getId()) + .map(patch::applyTo) + .orElseThrow(() -> new NoSuchElementException("%s with id %s does not exist" + .formatted(getContentType().getSimpleName(), value.getId()))); String encoded = encode(patched); template.update( @@ -159,8 +147,7 @@ public Stream findAll(Query query) { final Filter filter = applyTypeFilter(query.getFilter(), query.getType()); final Class type = query.getType(); - final PgconfigQueryBuilder qb = - new PgconfigQueryBuilder(filter, sortableProperties()).build(); + final PgconfigQueryBuilder qb = new PgconfigQueryBuilder(filter, sortableProperties()).build(); final Filter supportedFilter = qb.getSupportedFilter(); final Filter unsupportedFilter = qb.getUnsupportedFilter(); final String whereClause = qb.getWhereClause(); @@ -187,14 +174,12 @@ public Stream findAll(Query query) { sql = applyOffsetLimit(sql, query.getOffset(), query.getCount()); } - Stream stream = - queryForStream(type, sql, prepStatementParams).map(this::resolveOutbound); + Stream stream = queryForStream(type, sql, prepStatementParams).map(this::resolveOutbound); if (!filterFullySupported) { Predicate predicate = toPredicate(unsupportedFilter); - stream = - stream.filter(predicate) - .skip(query.offset().orElse(0)) - .limit(query.count().orElse(Integer.MAX_VALUE)); + stream = stream.filter(predicate) + .skip(query.offset().orElse(0)) + .limit(query.count().orElse(Integer.MAX_VALUE)); } return stream; } @@ -203,8 +188,7 @@ protected Stream queryForStream(String sql, Object... prepStatementParams) { return queryForStream(getContentType(), sql, prepStatementParams); } - protected Stream queryForStream( - Class type, String sql, Object... prepStatementParams) { + protected Stream queryForStream(Class type, String sql, Object... prepStatementParams) { RowMapper rowMapper = newRowMapper(); Stream stream = template.queryForStream(sql, rowMapper, prepStatementParams); @@ -244,9 +228,8 @@ protected String applySortOrder(String sql, @NonNull List sortBy) { protected void checkCanSortBy(String property) { if (!canSortBy(property)) { - throw new IllegalArgumentException( - "Unsupported sort property %s on %s. Supported properties: %s" - .formatted(property, getTable(), sortableProperties())); + throw new IllegalArgumentException("Unsupported sort property %s on %s. Supported properties: %s" + .formatted(property, getTable(), sortableProperties())); } } @@ -256,8 +239,7 @@ protected void checkCanSortBy(String property) { @Override public long count(Class of, Filter filter) { filter = applyTypeFilter(filter, of); - final PgconfigQueryBuilder qb = - new PgconfigQueryBuilder(filter, sortableProperties()).build(); + final PgconfigQueryBuilder qb = new PgconfigQueryBuilder(filter, sortableProperties()).build(); final Filter supportedFilter = qb.getSupportedFilter(); final Filter unsupportedFilter = qb.getUnsupportedFilter(); final String whereClause = qb.getWhereClause(); @@ -301,11 +283,9 @@ private Object asPreparedValue(Object val) { @Override public Optional findById(@NonNull String id, Class clazz) { - String query = - """ + String query = """ SELECT * FROM %s WHERE id = ? - """ - .formatted(getQueryTable()); + """.formatted(getQueryTable()); return findOne(query, clazz, id); } @@ -315,11 +295,10 @@ public Optional findById(@NonNull String id) { @Override public Optional findFirstByName(@NonNull String name, Class clazz) { - String query = - """ + String query = """ SELECT * FROM %s WHERE name = ? ORDER BY id """ - .formatted(getQueryTable()); + .formatted(getQueryTable()); return findOne(query, clazz, name); } @@ -327,8 +306,7 @@ protected Optional findOne(@NonNull String query, Object... args) { return findOne(query, getContentType(), args); } - protected Optional findOne( - @NonNull String query, Class clazz, Object... args) { + protected Optional findOne(@NonNull String query, Class clazz, Object... args) { return findOne(query, clazz, newRowMapper(), args); } diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigLayerGroupRepository.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigLayerGroupRepository.java index 48df12b12..c69e23212 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigLayerGroupRepository.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigLayerGroupRepository.java @@ -4,17 +4,15 @@ */ package org.geoserver.cloud.backend.pgconfig.catalog.repository; +import java.util.Optional; +import java.util.stream.Stream; import lombok.NonNull; - import org.geoserver.catalog.LayerGroupInfo; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.plugin.CatalogInfoRepository.LayerGroupRepository; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; -import java.util.Optional; -import java.util.stream.Stream; - /** * @since 1.4 */ @@ -50,8 +48,7 @@ public Optional findByNameAndWorkspaceIsNull(@NonNull String nam } @Override - public Optional findByNameAndWorkspace( - @NonNull String name, @NonNull WorkspaceInfo workspace) { + public Optional findByNameAndWorkspace(@NonNull String name, @NonNull WorkspaceInfo workspace) { String sql = """ diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigLayerRepository.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigLayerRepository.java index c8048abf4..f32f6ced8 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigLayerRepository.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigLayerRepository.java @@ -4,8 +4,9 @@ */ package org.geoserver.cloud.backend.pgconfig.catalog.repository; +import java.util.Optional; +import java.util.stream.Stream; import lombok.NonNull; - import org.geoserver.catalog.LayerInfo; import org.geoserver.catalog.ResourceInfo; import org.geoserver.catalog.StyleInfo; @@ -15,22 +16,17 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; -import java.util.Optional; -import java.util.stream.Stream; - /** * @since 1.4 */ -public class PgconfigLayerRepository extends PgconfigCatalogInfoRepository - implements LayerRepository { +public class PgconfigLayerRepository extends PgconfigCatalogInfoRepository implements LayerRepository { private final PgconfigStyleRepository styleLoader; /** * @param template */ - public PgconfigLayerRepository( - @NonNull JdbcTemplate template, @NonNull PgconfigStyleRepository styleLoader) { + public PgconfigLayerRepository(@NonNull JdbcTemplate template, @NonNull PgconfigStyleRepository styleLoader) { super(template); this.styleLoader = styleLoader; } @@ -56,8 +52,7 @@ public Optional findOneByName(@NonNull String possiblyPrefixedName) { if (possiblyPrefixedName.contains(":")) { // two options here, it's either a prefixed name like in :, or the // ResourceInfo name actually contains a colon - Optional found = - findOne(sql.formatted("prefixedName"), possiblyPrefixedName); + Optional found = findOne(sql.formatted("prefixedName"), possiblyPrefixedName); if (found.isPresent()) return found; } @@ -68,10 +63,9 @@ public Optional findOneByName(@NonNull String possiblyPrefixedName) { @Override public Stream findAllByDefaultStyleOrStyles(@NonNull StyleInfo style) { var ff = FILTER_FACTORY; - Filter filter = - ff.or( - ff.equals(ff.property("defaultStyle.id"), ff.literal(style.getId())), - ff.equals(ff.property("styles.id"), ff.literal(style.getId()))); + Filter filter = ff.or( + ff.equals(ff.property("defaultStyle.id"), ff.literal(style.getId())), + ff.equals(ff.property("styles.id"), ff.literal(style.getId()))); return findAll(Query.valueOf(LayerInfo.class, filter)); } diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigNamespaceRepository.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigNamespaceRepository.java index f11a9fc3b..214100a1f 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigNamespaceRepository.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigNamespaceRepository.java @@ -4,16 +4,14 @@ */ package org.geoserver.cloud.backend.pgconfig.catalog.repository; +import java.util.Optional; +import java.util.stream.Stream; import lombok.NonNull; - import org.geoserver.catalog.NamespaceInfo; import org.geoserver.catalog.plugin.CatalogInfoRepository.NamespaceRepository; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; -import java.util.Optional; -import java.util.stream.Stream; - /** * @since 1.4 */ @@ -65,11 +63,9 @@ public Optional getDefaultNamespace() { @Override public Optional findOneByURI(@NonNull String uri) { - return findOne( - """ + return findOne(""" SELECT namespace FROM namespaceinfos WHERE uri = ? - """, - uri); + """, uri); } @Override @@ -77,8 +73,7 @@ public Stream findAllByURI(@NonNull String uri) { return super.queryForStream( """ SELECT namespace FROM namespaceinfos WHERE uri = ? - """, - uri); + """, uri); } @Override diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigObjectMapper.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigObjectMapper.java index 82f5a0b81..0bb204487 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigObjectMapper.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigObjectMapper.java @@ -6,9 +6,7 @@ import com.fasterxml.jackson.annotation.JsonInclude.Include; import com.fasterxml.jackson.databind.ObjectMapper; - import lombok.experimental.UtilityClass; - import org.geotools.jackson.databind.util.ObjectMapperUtil; @UtilityClass diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigResourceRepository.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigResourceRepository.java index f8907c1fe..710912e23 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigResourceRepository.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigResourceRepository.java @@ -4,8 +4,9 @@ */ package org.geoserver.cloud.backend.pgconfig.catalog.repository; +import java.util.Optional; +import java.util.stream.Stream; import lombok.NonNull; - import org.geoserver.catalog.LayerInfo; import org.geoserver.catalog.NamespaceInfo; import org.geoserver.catalog.ResourceInfo; @@ -16,9 +17,6 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; -import java.util.Optional; -import java.util.stream.Stream; - /** * @since 1.4 */ @@ -31,8 +29,7 @@ public class PgconfigResourceRepository extends PgconfigCatalogInfoRepository { - Patch p = - PropertyDiff.builder(li) - .with("name", patched.getName()) - .build() - .toPatch(); + Patch p = PropertyDiff.builder(li) + .with("name", patched.getName()) + .build() + .toPatch(); layerrepo.update(li, p); }); } @@ -103,8 +99,7 @@ public Stream findAllByType(@NonNull Class clazz) } @Override - public Stream findAllByNamespace( - @NonNull NamespaceInfo ns, @NonNull Class clazz) { + public Stream findAllByNamespace(@NonNull NamespaceInfo ns, @NonNull Class clazz) { String query = """ diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigStoreRepository.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigStoreRepository.java index 99e91a046..6b68b0d22 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigStoreRepository.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigStoreRepository.java @@ -4,8 +4,9 @@ */ package org.geoserver.cloud.backend.pgconfig.catalog.repository; +import java.util.Optional; +import java.util.stream.Stream; import lombok.NonNull; - import org.geoserver.catalog.DataStoreInfo; import org.geoserver.catalog.StoreInfo; import org.geoserver.catalog.WorkspaceInfo; @@ -13,14 +14,10 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; -import java.util.Optional; -import java.util.stream.Stream; - /** * @since 1.4 */ -public class PgconfigStoreRepository extends PgconfigCatalogInfoRepository - implements StoreRepository { +public class PgconfigStoreRepository extends PgconfigCatalogInfoRepository implements StoreRepository { /** * @param template @@ -51,8 +48,7 @@ public Optional findById(@NonNull String id, Class c } @Override - public void setDefaultDataStore( - @NonNull WorkspaceInfo workspace, @NonNull DataStoreInfo dataStore) { + public void setDefaultDataStore(@NonNull WorkspaceInfo workspace, @NonNull DataStoreInfo dataStore) { String sql = "UPDATE workspaceinfo SET default_store = ? WHERE id = ?"; template.update(sql, dataStore.getId(), workspace.getId()); } @@ -115,9 +111,7 @@ public Stream findAllByType(@NonNull Class clazz) { String infotype = infoType(clazz); return super.queryForStream( - clazz, - "SELECT store, workspace FROM storeinfos WHERE \"@type\" = ?::infotype", - infotype); + clazz, "SELECT store, workspace FROM storeinfos WHERE \"@type\" = ?::infotype", infotype); } @Override diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigStyleRepository.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigStyleRepository.java index 64cb7aae0..87820fb6e 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigStyleRepository.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigStyleRepository.java @@ -4,22 +4,19 @@ */ package org.geoserver.cloud.backend.pgconfig.catalog.repository; +import java.util.Optional; +import java.util.stream.Stream; import lombok.NonNull; - import org.geoserver.catalog.StyleInfo; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.plugin.CatalogInfoRepository.StyleRepository; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; -import java.util.Optional; -import java.util.stream.Stream; - /** * @since 1.4 */ -public class PgconfigStyleRepository extends PgconfigCatalogInfoRepository - implements StyleRepository { +public class PgconfigStyleRepository extends PgconfigCatalogInfoRepository implements StyleRepository { /** * @param template @@ -76,8 +73,7 @@ public Optional findByNameAndWordkspaceNull(@NonNull String name) { } @Override - public Optional findByNameAndWorkspace( - @NonNull String name, @NonNull WorkspaceInfo workspace) { + public Optional findByNameAndWorkspace(@NonNull String name, @NonNull WorkspaceInfo workspace) { String query = """ diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigWorkspaceRepository.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigWorkspaceRepository.java index 3884ee19a..3dc4b8379 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigWorkspaceRepository.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigWorkspaceRepository.java @@ -4,16 +4,14 @@ */ package org.geoserver.cloud.backend.pgconfig.catalog.repository; +import java.util.Optional; import lombok.NonNull; - import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.plugin.CatalogInfoRepository.WorkspaceRepository; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.transaction.annotation.Transactional; -import java.util.Optional; - /** * @since 1.4 */ diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigConfigRepository.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigConfigRepository.java index 17d2e1f5d..e62a8cd4b 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigConfigRepository.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigConfigRepository.java @@ -6,10 +6,13 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; - +import java.io.UncheckedIOException; +import java.util.Arrays; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.stream.Stream; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.Info; import org.geoserver.catalog.WorkspaceInfo; @@ -25,12 +28,6 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; -import java.io.UncheckedIOException; -import java.util.Arrays; -import java.util.NoSuchElementException; -import java.util.Optional; -import java.util.stream.Stream; - /** * @since 1.4 */ @@ -65,13 +62,8 @@ public void setGlobal(GeoServerInfo global) { String value = encode(global); getGlobal() .ifPresentOrElse( - g -> - template.update( - "UPDATE geoserverinfo SET info = to_json(?::json)", value), - () -> - template.update( - "INSERT INTO geoserverinfo(info) VALUES (to_json(?::json))", - value)); + g -> template.update("UPDATE geoserverinfo SET info = to_json(?::json)", value), + () -> template.update("INSERT INTO geoserverinfo(info) VALUES (to_json(?::json))", value)); } @Override @@ -89,13 +81,11 @@ public Optional getSettingsById(String id) { return findById(id, SettingsInfo.class, "settingsinfos", SettingsInfoRowMapper); } - protected Optional findById( - String id, Class clazz, String queryTable, RowMapper mapper) { - String query = - """ + protected Optional findById(String id, Class clazz, String queryTable, RowMapper mapper) { + String query = """ SELECT info, workspace FROM %s WHERE id = ? """ - .formatted(queryTable); + .formatted(queryTable); return findOne(query, clazz, mapper, id); } @@ -107,32 +97,17 @@ public void add(SettingsInfo settings) { @Override public SettingsInfo update(SettingsInfo settings, Patch patch) { - return update( - settings, - patch, - SettingsInfo.class, - "settingsinfo", - "settingsinfos", - SettingsInfoRowMapper); + return update(settings, patch, SettingsInfo.class, "settingsinfo", "settingsinfos", SettingsInfoRowMapper); } private T update( - T value, - Patch patch, - Class clazz, - String table, - String querytable, - RowMapper mapper) { + T value, Patch patch, Class clazz, String table, String querytable, RowMapper mapper) { String id = value.getId(); Optional found = findById(id, clazz, querytable, mapper); - T patched = - found.map(patch::applyTo) - .orElseThrow( - () -> - new NoSuchElementException( - "%s with id %s does not exist" - .formatted(clazz.getSimpleName(), id))); + T patched = found.map(patch::applyTo) + .orElseThrow(() -> new NoSuchElementException( + "%s with id %s does not exist".formatted(clazz.getSimpleName(), id))); String encoded = encode(patched); template.update( @@ -184,14 +159,7 @@ public void remove(ServiceInfo service) { @SuppressWarnings("unchecked") @Override public S update(S service, Patch patch) { - return (S) - update( - service, - patch, - ServiceInfo.class, - "serviceinfo", - "serviceinfos", - ServiceInfoRowMapper); + return (S) update(service, patch, ServiceInfo.class, "serviceinfo", "serviceinfos", ServiceInfoRowMapper); } @Override @@ -222,15 +190,11 @@ public Optional getGlobalService(Class clazz) { } @Override - public Optional getServiceByWorkspace( - WorkspaceInfo workspace, Class clazz) { + public Optional getServiceByWorkspace(WorkspaceInfo workspace, Class clazz) { - return findService( - """ + return findService(""" "workspace.id" = ? - """, - clazz, - workspace.getId()); + """, clazz, workspace.getId()); } @Override @@ -240,17 +204,14 @@ public Optional getServiceById(String id, Class cl """, clazz, id); } - private Optional findService( - String whereClause, Class clazz, Object... args) { + private Optional findService(String whereClause, Class clazz, Object... args) { String sql = "SELECT info, workspace FROM serviceinfos WHERE %s".formatted(whereClause); if (!ServiceInfo.class.equals(clazz)) { String servicetype = servicetype(clazz); - sql = - """ + sql = """ %s AND "@type" = '%s' - """ - .formatted(sql, servicetype); + """.formatted(sql, servicetype); } return findOne(sql, ServiceInfo.class, ServiceInfoRowMapper, args) .filter(clazz::isInstance) @@ -259,13 +220,12 @@ private Optional findService( private String servicetype(Class clazz) { if (ServiceInfo.class.equals(clazz)) return ServiceInfo.class.getSimpleName(); - Class iface = - clazz.isInterface() - ? clazz - : Arrays.stream(clazz.getInterfaces()) - .filter(ServiceInfo.class::isAssignableFrom) - .findFirst() - .orElseThrow(IllegalArgumentException::new); + Class iface = clazz.isInterface() + ? clazz + : Arrays.stream(clazz.getInterfaces()) + .filter(ServiceInfo.class::isAssignableFrom) + .findFirst() + .orElseThrow(IllegalArgumentException::new); return iface.getSimpleName(); } @@ -318,8 +278,7 @@ private static C decode(String value, Class type) { return cm.getInterface().getSimpleName(); } - protected Optional findOne( - @NonNull String query, Class clazz, RowMapper rowMapper, Object... args) { + protected Optional findOne(@NonNull String query, Class clazz, RowMapper rowMapper, Object... args) { try { U object = template.queryForObject(query, rowMapper, args); diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigGeoServerFacade.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigGeoServerFacade.java index c5e550b9f..62d44595f 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigGeoServerFacade.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigGeoServerFacade.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.backend.pgconfig.config; import lombok.NonNull; - import org.geoserver.config.plugin.RepositoryGeoServerFacadeImpl; import org.springframework.jdbc.core.JdbcTemplate; diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigUpdateSequence.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigUpdateSequence.java index cda86dbc3..395014ef2 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigUpdateSequence.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigUpdateSequence.java @@ -4,19 +4,16 @@ */ package org.geoserver.cloud.backend.pgconfig.config; -import lombok.NonNull; -import lombok.RequiredArgsConstructor; - -import org.geoserver.config.GeoServerInfo; -import org.geoserver.config.impl.GeoServerInfoImpl; -import org.geoserver.platform.config.UpdateSequence; - import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; - import javax.sql.DataSource; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import org.geoserver.config.GeoServerInfo; +import org.geoserver.config.impl.GeoServerInfoImpl; +import org.geoserver.platform.config.UpdateSequence; /** * @since 1.4 @@ -30,8 +27,7 @@ public class PgconfigUpdateSequence implements UpdateSequence { // session" error private static final String GET_QUERY = "SELECT last_value FROM %s".formatted(SEQUENCE_NAME); - private static final String INCREMENT_AND_GET_QUERY = - "SELECT NEXTVAL('%s')".formatted(SEQUENCE_NAME); + private static final String INCREMENT_AND_GET_QUERY = "SELECT NEXTVAL('%s')".formatted(SEQUENCE_NAME); private final @NonNull DataSource dataSource; private final @NonNull PgconfigGeoServerFacade geoServer; diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/FileSystemResourceStoreCache.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/FileSystemResourceStoreCache.java index 0d354c00f..002f17ca7 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/FileSystemResourceStoreCache.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/FileSystemResourceStoreCache.java @@ -1,17 +1,6 @@ package org.geoserver.cloud.backend.pgconfig.resource; import com.google.common.base.Preconditions; - -import lombok.Getter; -import lombok.NonNull; -import lombok.SneakyThrows; -import lombok.extern.slf4j.Slf4j; - -import org.geoserver.platform.resource.FileSystemResourceStore; -import org.geoserver.platform.resource.Resource; -import org.springframework.beans.factory.DisposableBean; -import org.springframework.util.FileSystemUtils; - import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -21,6 +10,14 @@ import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileTime; import java.util.List; +import lombok.Getter; +import lombok.NonNull; +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; +import org.geoserver.platform.resource.FileSystemResourceStore; +import org.geoserver.platform.resource.Resource; +import org.springframework.beans.factory.DisposableBean; +import org.springframework.util.FileSystemUtils; @Slf4j public class FileSystemResourceStoreCache implements DisposableBean { diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigLockProvider.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigLockProvider.java index 657bb837b..81fc82864 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigLockProvider.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigLockProvider.java @@ -4,15 +4,13 @@ */ package org.geoserver.cloud.backend.pgconfig.resource; +import java.util.Objects; import lombok.extern.slf4j.Slf4j; - import org.geoserver.platform.resource.LockAdapter; import org.geoserver.platform.resource.LockProvider; import org.geoserver.platform.resource.Resource.Lock; import org.springframework.integration.support.locks.LockRegistry; -import java.util.Objects; - /** * Adapts a spring-integration-jdbc's {@link LockRegistry} to a GeoServer {@link LockProvider} * diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigResource.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigResource.java index 0470c89b3..6c1af2699 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigResource.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigResource.java @@ -4,27 +4,29 @@ */ package org.geoserver.cloud.backend.pgconfig.resource; +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; - import org.geoserver.platform.resource.Paths; import org.geoserver.platform.resource.Resource; import org.geoserver.platform.resource.ResourceListener; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.List; - /** * @since 1.4 */ @EqualsAndHashCode(exclude = {"store"}) class PgconfigResource implements Resource { - @Getter long id; - @Getter long parentId; + @Getter + long id; + + @Getter + long parentId; + Resource.Type type; String path; long lastmodified; diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigResourceRowMapper.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigResourceRowMapper.java index c861a27d2..2f0321a49 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigResourceRowMapper.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigResourceRowMapper.java @@ -4,15 +4,13 @@ */ package org.geoserver.cloud.backend.pgconfig.resource; +import java.sql.ResultSet; +import java.sql.SQLException; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.platform.resource.Resource; import org.springframework.jdbc.core.RowMapper; -import java.sql.ResultSet; -import java.sql.SQLException; - /** * @since 1.4 */ diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigResourceStore.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigResourceStore.java index af78f93a2..5bc32946e 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigResourceStore.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigResourceStore.java @@ -8,14 +8,23 @@ import static org.springframework.transaction.annotation.Propagation.SUPPORTS; import com.google.common.base.Preconditions; - +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.OutputStream; +import java.nio.file.Path; +import java.sql.Timestamp; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Stream; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.Setter; import lombok.experimental.Delegate; import lombok.extern.slf4j.Slf4j; - import org.geoserver.platform.resource.LockProvider; import org.geoserver.platform.resource.Paths; import org.geoserver.platform.resource.Resource; @@ -27,18 +36,6 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.annotation.Transactional; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.OutputStream; -import java.nio.file.Path; -import java.sql.Timestamp; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.function.Predicate; -import java.util.stream.Stream; - /** * @since 1.4 */ @@ -62,11 +59,7 @@ public PgconfigResourceStore( @NonNull JdbcTemplate template, @NonNull PgconfigLockProvider lockProvider, @NonNull Predicate fileSystemOnlyPathMatcher) { - this( - FileSystemResourceStoreCache.of(cacheDirectory), - template, - lockProvider, - fileSystemOnlyPathMatcher); + this(FileSystemResourceStoreCache.of(cacheDirectory), template, lockProvider, fileSystemOnlyPathMatcher); } public PgconfigResourceStore( @@ -84,8 +77,7 @@ public PgconfigResourceStore( } public static Predicate defaultIgnoredDirs() { - return PgconfigResourceStore.simplePathMatcher( - "temp", "tmp", "legendsamples", "data", "logs"); + return PgconfigResourceStore.simplePathMatcher("temp", "tmp", "legendsamples", "data", "logs"); } public static Predicate simplePathMatcher(String... paths) { @@ -111,7 +103,10 @@ public Resource get(@NonNull String path) { @RequiredArgsConstructor static class FileSystemResourceAdaptor implements Resource { - @Delegate @NonNull private final Resource delegate; + @Delegate + @NonNull + private final Resource delegate; + private final @NonNull PgconfigResourceStore store; @Override @@ -177,16 +172,14 @@ private static String normalize(String path) { private Optional findByPath(@NonNull String path) { path = Paths.valid(path); - Preconditions.checkArgument( - !path.startsWith("/"), "Absolute paths not supported: %s", path); + Preconditions.checkArgument(!path.startsWith("/"), "Absolute paths not supported: %s", path); try { - return Optional.of( - template.queryForObject( - """ + return Optional.of(template.queryForObject( + """ SELECT id, parentid, "type", path, mtime FROM resourcestore WHERE path = ? """, - queryMapper, - path)); + queryMapper, + path)); } catch (EmptyResultDataAccessException empty) { return Optional.empty(); } @@ -244,35 +237,27 @@ INSERT INTO resourcestore (parentid, "type", path, content) @Transactional(transactionManager = "pgconfigTransactionManager", propagation = REQUIRED) public long save(@NonNull PgconfigResource resource, byte[] contents) { if (!resource.exists()) - throw new IllegalArgumentException( - "Resource does not exist: %s".formatted(resource.path())); + throw new IllegalArgumentException("Resource does not exist: %s".formatted(resource.path())); if (!resource.isFile()) throw new IllegalArgumentException( "Resource is a directory, can't have contents: %s".formatted(resource.path())); if (null == contents) contents = new byte[0]; - template.update( - """ + template.update(""" UPDATE resourcestore SET content = ? WHERE id = ? - """, - contents, - resource.getId()); + """, contents, resource.getId()); return getLastmodified(resource.getId()); } public long getLastmodified(long resourceId) { Timestamp ts = - template.queryForObject( - "SELECT mtime FROM resourcestore WHERE id = ?", - Timestamp.class, - resourceId); + template.queryForObject("SELECT mtime FROM resourcestore WHERE id = ?", Timestamp.class, resourceId); return null == ts ? 0L : ts.getTime(); } @Transactional(transactionManager = "pgconfigTransactionManager", propagation = REQUIRED) - public boolean move( - @NonNull final PgconfigResource source, @NonNull final PgconfigResource target) { + public boolean move(@NonNull final PgconfigResource source, @NonNull final PgconfigResource target) { if (source.isUndefined()) return true; if (!source.exists()) { return false; @@ -286,22 +271,13 @@ public boolean move( } final String parentPath = target.parentPath(); if (null != parentPath && parentPath.contains(source.path())) { - log.warn( - "Cannot rename a resource to a descendant of itself ({} to {})", - source.path(), - target.path()); + log.warn("Cannot rename a resource to a descendant of itself ({} to {})", source.path(), target.path()); return false; } final List allChildren = findAllChildren(source); PgconfigResource parent = target.parent().mkdirs(); - PgconfigResource save = - new PgconfigResource( - this, - source.getId(), - parent.getId(), - source.getType(), - target.path(), - source.lastmodified()); + PgconfigResource save = new PgconfigResource( + this, source.getId(), parent.getId(), source.getType(), target.path(), source.lastmodified()); PgconfigResourceStore.this.save(save); target.copy(save); source.type = Type.UNDEFINED; @@ -322,8 +298,7 @@ public boolean move( List findAllChildren(PgconfigResource resource) { if (!resource.exists() || !resource.isDirectory()) return List.of(); - String sql = - """ + String sql = """ SELECT id, parentid, "type", path, mtime FROM resourcestore WHERE path LIKE ? """; @@ -346,8 +321,7 @@ public ResourceNotificationDispatcher getResourceNotificationDispatcher() { public byte[] contents(PgconfigResource resource) { if (!resource.exists() || resource.isUndefined()) throw new IllegalStateException("File not found %s".formatted(resource.path())); - if (resource.isDirectory()) - throw new IllegalStateException("%s is a directory".formatted(resource.path())); + if (resource.isDirectory()) throw new IllegalStateException("%s is a directory".formatted(resource.path())); long id = resource.getId(); return template.queryForObject( @@ -373,14 +347,12 @@ public boolean delete(PgconfigResource resource) { public List list(PgconfigResource resource) { if (!resource.exists() || !resource.isDirectory()) return List.of(); - String sql = - """ + String sql = """ SELECT id, parentid, "type", path, mtime FROM resourcestore WHERE parentid = ? """; List list; - try (Stream s = - template.queryForStream(sql, queryMapper, resource.getId())) { + try (Stream s = template.queryForStream(sql, queryMapper, resource.getId())) { // for pre 1.8.1 backwards compatibility, ignore resources that are only to be stored in // the filesystem (e.g. tmp/, temp/, etc) var resources = s.filter(r -> !fileSystemOnlyPathMatcher.test(r.path())); @@ -419,8 +391,7 @@ public PgconfigResource mkdirs(PgconfigResource resource) { return resource; } if (resource.isFile()) - throw new IllegalStateException( - "mkdirs() can only be called on DIRECTORY or UNDEFINED resources"); + throw new IllegalStateException("mkdirs() can only be called on DIRECTORY or UNDEFINED resources"); PgconfigResource parent = getParent(resource); if (null == parent) return resource; diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/DatabaseMigrationConfiguration.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/DatabaseMigrationConfiguration.java index a7d82597e..6a0d5a605 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/DatabaseMigrationConfiguration.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/DatabaseMigrationConfiguration.java @@ -4,16 +4,14 @@ */ package org.geoserver.cloud.config.catalog.backend.pgconfig; +import javax.sql.DataSource; import lombok.RequiredArgsConstructor; - import org.springframework.beans.factory.InitializingBean; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import javax.sql.DataSource; - /** * @since 1.4 */ @@ -23,8 +21,7 @@ public class DatabaseMigrationConfiguration { @Bean Migrations pgconfigMigrations( - PgconfigBackendProperties config, - @Qualifier("pgconfigDataSource") DataSource dataSource) { + PgconfigBackendProperties config, @Qualifier("pgconfigDataSource") DataSource dataSource) { return new Migrations(config, dataSource); } @@ -38,12 +35,11 @@ public static class Migrations implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { - databaseMigrations = - new PgconfigDatabaseMigrations() - .setInitialize(config.isInitialize()) - .setDataSource(dataSource) - .setSchema(config.schema()) - .setCreateSchema(config.isCreateSchema()); + databaseMigrations = new PgconfigDatabaseMigrations() + .setInitialize(config.isInitialize()) + .setDataSource(dataSource) + .setSchema(config.schema()) + .setCreateSchema(config.isCreateSchema()); databaseMigrations.migrate(); } diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/GeoServerConfigInitializer.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/GeoServerConfigInitializer.java index 988ab1eaa..11c4fa6c5 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/GeoServerConfigInitializer.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/GeoServerConfigInitializer.java @@ -4,10 +4,10 @@ */ package org.geoserver.cloud.config.catalog.backend.pgconfig; +import java.util.List; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; - import org.geoserver.GeoServerConfigurationLock; import org.geoserver.GeoServerConfigurationLock.LockType; import org.geoserver.config.GeoServer; @@ -19,15 +19,12 @@ import org.geoserver.platform.GeoServerExtensions; import org.springframework.core.Ordered; -import java.util.List; - /** * @since 1.4 */ @RequiredArgsConstructor @Slf4j -public class GeoServerConfigInitializer - implements GeoServerInitializer, Ordered, ExtensionPriority { +public class GeoServerConfigInitializer implements GeoServerInitializer, Ordered, ExtensionPriority { private final @NonNull GeoServerConfigurationLock configLock; @@ -57,8 +54,7 @@ public void initialize(GeoServer geoServer) throws Exception { } // also ensure we have a service configuration for every service we know about @SuppressWarnings("rawtypes") - final List loaders = - GeoServerExtensions.extensions(XStreamServiceLoader.class); + final List loaders = GeoServerExtensions.extensions(XStreamServiceLoader.class); for (ServiceLoader l : loaders) { ServiceInfo s = geoServer.getService(l.getServiceClass()); if (s == null) { diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PconfigDataSourceConfiguration.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PconfigDataSourceConfiguration.java index 3ed44c404..7e47091e0 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PconfigDataSourceConfiguration.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PconfigDataSourceConfiguration.java @@ -5,9 +5,8 @@ package org.geoserver.cloud.config.catalog.backend.pgconfig; import com.zaxxer.hikari.HikariDataSource; - +import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; - import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -18,8 +17,6 @@ import org.springframework.transaction.annotation.EnableTransactionManagement; import org.springframework.util.StringUtils; -import javax.sql.DataSource; - /** * @since 1.4 */ diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigBackendConfiguration.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigBackendConfiguration.java index 73f1f6122..142856ec6 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigBackendConfiguration.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigBackendConfiguration.java @@ -4,8 +4,9 @@ */ package org.geoserver.cloud.config.catalog.backend.pgconfig; +import java.util.function.Predicate; +import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; - import org.geoserver.GeoServerConfigurationLock; import org.geoserver.catalog.plugin.ExtendedCatalogFacade; import org.geoserver.catalog.plugin.locking.LockProviderGeoServerConfigurationLock; @@ -33,10 +34,6 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.util.StringUtils; -import java.util.function.Predicate; - -import javax.sql.DataSource; - /** * @since 1.4 */ @@ -128,9 +125,7 @@ FileSystemResourceStoreCache pgconfigFileSystemResourceStoreCache() { @Bean @Override protected GeoServerResourceLoader resourceLoader() { - log.debug( - "Creating GeoServerResourceLoader {}", - PgconfigGeoServerResourceLoader.class.getSimpleName()); + log.debug("Creating GeoServerResourceLoader {}", PgconfigGeoServerResourceLoader.class.getSimpleName()); ResourceStore resourceStore = resourceStoreImpl(); return new PgconfigGeoServerResourceLoader(resourceStore); } @@ -151,10 +146,7 @@ private LockRegistry pgconfigLockRegistry() { @Bean LockRepository pgconfigLockRepository() { - log.debug( - "Creating {} for instance {}", - LockRepository.class.getSimpleName(), - this.instanceId); + log.debug("Creating {} for instance {}", LockRepository.class.getSimpleName(), this.instanceId); String id = this.instanceId; DefaultLockRepository lockRepository; if (StringUtils.hasLength(id)) { diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigBackendProperties.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigBackendProperties.java index c4e81be3d..83037eaf5 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigBackendProperties.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigBackendProperties.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.config.catalog.backend.pgconfig; import lombok.Data; - import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.util.StringUtils; diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigCatalogResourcesSynchronizer.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigCatalogResourcesSynchronizer.java index 65a936624..5d32d0c7c 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigCatalogResourcesSynchronizer.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigCatalogResourcesSynchronizer.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.config.catalog.backend.pgconfig; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.CatalogException; import org.geoserver.catalog.FeatureTypeInfo; import org.geoserver.catalog.LayerGroupInfo; diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigDatabaseMigrations.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigDatabaseMigrations.java index 4bcd09e2c..0f670c4c5 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigDatabaseMigrations.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigDatabaseMigrations.java @@ -4,15 +4,13 @@ */ package org.geoserver.cloud.config.catalog.backend.pgconfig; +import javax.sql.DataSource; import lombok.Data; import lombok.experimental.Accessors; import lombok.extern.slf4j.Slf4j; - import org.flywaydb.core.Flyway; import org.flywaydb.core.api.output.MigrateResult; -import javax.sql.DataSource; - /** * @since 1.4 */ diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigGeoServerLoader.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigGeoServerLoader.java index 9497aa9a1..2a7bfdc4e 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigGeoServerLoader.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigGeoServerLoader.java @@ -10,9 +10,13 @@ import static org.geoserver.catalog.StyleInfo.DEFAULT_POLYGON; import static org.geoserver.catalog.StyleInfo.DEFAULT_RASTER; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.PostConstruct; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.GeoServerConfigurationLock; import org.geoserver.GeoServerConfigurationLock.LockType; import org.geoserver.catalog.Catalog; @@ -32,13 +36,6 @@ import org.geoserver.platform.GeoServerResourceLoader; import org.geoserver.platform.resource.Resource.Lock; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -import javax.annotation.PostConstruct; - /** * @since 1.4 */ @@ -53,8 +50,7 @@ public class PgconfigGeoServerLoader extends GeoServerLoader { * config when starting off an empty config */ public PgconfigGeoServerLoader( - @NonNull GeoServerResourceLoader resourceLoader, - @NonNull GeoServerConfigurationLock configLock) { + @NonNull GeoServerResourceLoader resourceLoader, @NonNull GeoServerConfigurationLock configLock) { super(resourceLoader); this.configLock = configLock; } @@ -84,13 +80,7 @@ protected void loadCatalog(Catalog catalog, XStreamPersister xp) throws Exceptio */ @Override protected void initializeDefaultStyles(Catalog catalog) throws IOException { - if (anyStyleMissing( - catalog, - DEFAULT_POINT, - DEFAULT_LINE, - DEFAULT_POLYGON, - DEFAULT_RASTER, - DEFAULT_GENERIC)) { + if (anyStyleMissing(catalog, DEFAULT_POINT, DEFAULT_LINE, DEFAULT_POLYGON, DEFAULT_RASTER, DEFAULT_GENERIC)) { final Lock lock = resourceLoader.getLockProvider().acquire("DEFAULT_STYLES"); try { super.initializeDefaultStyles(catalog); @@ -119,22 +109,19 @@ protected void loadGeoServer(GeoServer geoServer, XStreamPersister xp) throws Ex try { GeoServerInfo global = geoServer.getGlobal(); LoggingInfo logging = geoServer.getLogging(); - boolean someConfigMissing = - global == null || logging == null || !missingServices.isEmpty(); + boolean someConfigMissing = global == null || logging == null || !missingServices.isEmpty(); if (someConfigMissing) { try { log.info("Found missing config objects, acquiring config lock..."); configLock.tryUpgradeLock(); - log.info( - "Config lock acquired. Creating initial GeoServer configuration objects..."); + log.info("Config lock acquired. Creating initial GeoServer configuration objects..."); doCreateMissing(geoServer, missingServices); log.info("Done creating initial GeoServer configuration objects."); } catch (RuntimeException failedUpgrade) { - log.info( - "Unable to acquire config lock, checking if another instance initialized the config"); + log.info("Unable to acquire config lock, checking if another instance initialized the config"); verifyInitialized(geoServer, missingServices); } } @@ -145,8 +132,7 @@ protected void loadGeoServer(GeoServer geoServer, XStreamPersister xp) throws Ex } private void verifyInitialized( - GeoServer geoServer, - List> missingServices) { + GeoServer geoServer, List> missingServices) { if (geoServer.getGlobal() == null) { throw new IllegalStateException("GeoServerInfo not found"); @@ -155,12 +141,11 @@ private void verifyInitialized( throw new IllegalStateException("LoggingInfo not found"); } - String missing = - missingServices.stream() - .filter(loader -> null == geoServer.getService(loader.getServiceClass())) - .map(XStreamServiceLoader::getServiceClass) - .map(Class::getName) - .collect(Collectors.joining(", ")); + String missing = missingServices.stream() + .filter(loader -> null == geoServer.getService(loader.getServiceClass())) + .map(XStreamServiceLoader::getServiceClass) + .map(Class::getName) + .collect(Collectors.joining(", ")); if (!missing.isEmpty()) { throw new IllegalStateException("ServiceInfo not found for %s".formatted(missing)); } @@ -168,8 +153,7 @@ private void verifyInitialized( /** Must run inside a config lock to create missing config objects */ private void doCreateMissing( - GeoServer geoServer, - List> missingServices) { + GeoServer geoServer, List> missingServices) { if (geoServer.getGlobal() == null) { log.info("initializing geoserver global config"); @@ -195,8 +179,7 @@ private void doCreateMissing( } } - private List> findMissingServices( - GeoServer geoServer) { + private List> findMissingServices(GeoServer geoServer) { var loaders = GeoServerExtensions.extensions(XStreamServiceLoader.class); var missing = new ArrayList>(); diff --git a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigGeoServerResourceLoader.java b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigGeoServerResourceLoader.java index c93d539ea..b9775d2f5 100644 --- a/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigGeoServerResourceLoader.java +++ b/src/catalog/backends/pgconfig/src/main/java/org/geoserver/cloud/config/catalog/backend/pgconfig/PgconfigGeoServerResourceLoader.java @@ -4,13 +4,11 @@ */ package org.geoserver.cloud.config.catalog.backend.pgconfig; +import java.io.File; import lombok.NonNull; - import org.geoserver.platform.GeoServerResourceLoader; import org.geoserver.platform.resource.ResourceStore; -import java.io.File; - /** * @since 1.4 */ diff --git a/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/PgconfigBackendAutoConfigurationTest.java b/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/PgconfigBackendAutoConfigurationTest.java index e2568ba6a..a5bf12d24 100644 --- a/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/PgconfigBackendAutoConfigurationTest.java +++ b/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/PgconfigBackendAutoConfigurationTest.java @@ -32,16 +32,15 @@ @Testcontainers(disabledWithoutDocker = true) class PgconfigBackendAutoConfigurationTest { - @Container static PgConfigTestContainer container = new PgConfigTestContainer<>(); + @Container + static PgConfigTestContainer container = new PgConfigTestContainer<>(); - private ApplicationContextRunner runner = - new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of( - PgconfigDataSourceAutoConfiguration.class, - PgconfigTransactionManagerAutoConfiguration.class, - PgconfigMigrationAutoConfiguration.class, - PgconfigBackendAutoConfiguration.class)); + private ApplicationContextRunner runner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + PgconfigDataSourceAutoConfiguration.class, + PgconfigTransactionManagerAutoConfiguration.class, + PgconfigMigrationAutoConfiguration.class, + PgconfigBackendAutoConfiguration.class)); @BeforeEach void setUp() { @@ -50,25 +49,23 @@ void setUp() { @Test void testCatalogAndConfigBeans() { - runner.run( - context -> { - assertThat(context) - .hasNotFailed() - .hasBean("pgconfigTransactionManager") - .hasSingleBean(JdbcTemplate.class) - .hasSingleBean(GeoServerConfigurationLock.class) - .hasSingleBean(PgconfigUpdateSequence.class) - .hasSingleBean(PgconfigCatalogFacade.class) - .hasSingleBean(PgconfigGeoServerLoader.class) - .hasSingleBean(PgconfigConfigRepository.class) - .hasSingleBean(PgconfigGeoServerFacade.class) - .hasBean("resourceStoreImpl") - .hasSingleBean(PgconfigGeoServerResourceLoader.class) - .hasSingleBean(PgconfigLockProvider.class); + runner.run(context -> { + assertThat(context) + .hasNotFailed() + .hasBean("pgconfigTransactionManager") + .hasSingleBean(JdbcTemplate.class) + .hasSingleBean(GeoServerConfigurationLock.class) + .hasSingleBean(PgconfigUpdateSequence.class) + .hasSingleBean(PgconfigCatalogFacade.class) + .hasSingleBean(PgconfigGeoServerLoader.class) + .hasSingleBean(PgconfigConfigRepository.class) + .hasSingleBean(PgconfigGeoServerFacade.class) + .hasBean("resourceStoreImpl") + .hasSingleBean(PgconfigGeoServerResourceLoader.class) + .hasSingleBean(PgconfigLockProvider.class); - ExtendedCatalogFacade catalogFacade = - context.getBean("catalogFacade", ExtendedCatalogFacade.class); - assertThat(catalogFacade).isInstanceOf(PgconfigCatalogFacade.class); - }); + ExtendedCatalogFacade catalogFacade = context.getBean("catalogFacade", ExtendedCatalogFacade.class); + assertThat(catalogFacade).isInstanceOf(PgconfigCatalogFacade.class); + }); } } diff --git a/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/PgconfigDataSourceAutoConfigurationTest.java b/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/PgconfigDataSourceAutoConfigurationTest.java index fdad6a10a..4e38af25e 100644 --- a/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/PgconfigDataSourceAutoConfigurationTest.java +++ b/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/PgconfigDataSourceAutoConfigurationTest.java @@ -6,8 +6,12 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.sql.Statement; +import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.backend.pgconfig.support.PgConfigTestContainer; import org.geoserver.cloud.config.catalog.backend.pgconfig.PconfigDataSourceConfiguration; import org.junit.jupiter.api.BeforeEach; @@ -19,13 +23,6 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import java.sql.Connection; -import java.sql.ResultSet; -import java.sql.SQLException; -import java.sql.Statement; - -import javax.sql.DataSource; - /** * Tests for {@link PconfigDataSourceConfiguration} * @@ -35,12 +32,11 @@ @Slf4j class PgconfigDataSourceAutoConfigurationTest { - @Container static PgConfigTestContainer container = new PgConfigTestContainer<>(); + @Container + static PgConfigTestContainer container = new PgConfigTestContainer<>(); - private ApplicationContextRunner runner = - new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(PgconfigDataSourceAutoConfiguration.class)); + private ApplicationContextRunner runner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(PgconfigDataSourceAutoConfiguration.class)); String url; String username; @@ -59,18 +55,15 @@ void setUp() { */ @Test void testDataSource() { - container - .withJdbcUrlConfig(runner) - .run( - context -> { - assertThat(context) - .hasNotFailed() - .hasBean("pgconfigDataSource") - .getBean("pgconfigDataSource") - .isInstanceOf(DataSource.class); + container.withJdbcUrlConfig(runner).run(context -> { + assertThat(context) + .hasNotFailed() + .hasBean("pgconfigDataSource") + .getBean("pgconfigDataSource") + .isInstanceOf(DataSource.class); - assertIsPostgresql(context); - }); + assertIsPostgresql(context); + }); } /** @@ -79,21 +72,17 @@ void testDataSource() { */ @Test void testJndiDataSource() { - container - .withJndiConfig(runner) - .run( - context -> { - assertThat(context) - .hasNotFailed() - .hasBean("pgconfigDataSource") - .getBean("pgconfigDataSource") - .isInstanceOf(DataSource.class); - assertIsPostgresql(context); - }); + container.withJndiConfig(runner).run(context -> { + assertThat(context) + .hasNotFailed() + .hasBean("pgconfigDataSource") + .getBean("pgconfigDataSource") + .isInstanceOf(DataSource.class); + assertIsPostgresql(context); + }); } - private void assertIsPostgresql(AssertableApplicationContext context) - throws BeansException, SQLException { + private void assertIsPostgresql(AssertableApplicationContext context) throws BeansException, SQLException { try (Connection c = context.getBean("pgconfigDataSource", DataSource.class).getConnection()) { assertThat(c.isValid(2)).isTrue(); diff --git a/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/PgconfigMigrationAutoConfigurationTest.java b/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/PgconfigMigrationAutoConfigurationTest.java index e7bca1141..611737705 100644 --- a/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/PgconfigMigrationAutoConfigurationTest.java +++ b/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/autoconfigure/catalog/backend/pgconfig/PgconfigMigrationAutoConfigurationTest.java @@ -6,14 +6,6 @@ import static org.assertj.core.api.Assertions.assertThat; -import org.geoserver.cloud.backend.pgconfig.support.PgConfigTestContainer; -import org.geoserver.cloud.config.catalog.backend.pgconfig.PgconfigBackendProperties; -import org.junit.jupiter.api.Test; -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import org.testcontainers.junit.jupiter.Container; -import org.testcontainers.junit.jupiter.Testcontainers; - import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; @@ -23,8 +15,14 @@ import java.util.TreeMap; import java.util.function.Function; import java.util.stream.Collectors; - import javax.sql.DataSource; +import org.geoserver.cloud.backend.pgconfig.support.PgConfigTestContainer; +import org.geoserver.cloud.config.catalog.backend.pgconfig.PgconfigBackendProperties; +import org.junit.jupiter.api.Test; +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.testcontainers.junit.jupiter.Container; +import org.testcontainers.junit.jupiter.Testcontainers; /** * @since 1.4 @@ -32,35 +30,28 @@ @Testcontainers(disabledWithoutDocker = true) class PgconfigMigrationAutoConfigurationTest { - @Container static PgConfigTestContainer container = new PgConfigTestContainer<>(); + @Container + static PgConfigTestContainer container = new PgConfigTestContainer<>(); - private ApplicationContextRunner runner = - new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of( - PgconfigDataSourceAutoConfiguration.class, - PgconfigMigrationAutoConfiguration.class)); + private ApplicationContextRunner runner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + PgconfigDataSourceAutoConfiguration.class, PgconfigMigrationAutoConfiguration.class)); @Test void testMigration_enabledByDefault() { - container - .withJdbcUrlConfig(runner) - .run( - context -> { - assertThat(context) - .hasNotFailed() - .hasSingleBean(PgconfigBackendProperties.class) - .hasBean("pgconfigDataSource"); + container.withJdbcUrlConfig(runner).run(context -> { + assertThat(context) + .hasNotFailed() + .hasSingleBean(PgconfigBackendProperties.class) + .hasBean("pgconfigDataSource"); - PgconfigBackendProperties config = - context.getBean(PgconfigBackendProperties.class); - DataSource ds = context.getBean("pgconfigDataSource", DataSource.class); - assertDbSchema(ds, config); - }); + PgconfigBackendProperties config = context.getBean(PgconfigBackendProperties.class); + DataSource ds = context.getBean("pgconfigDataSource", DataSource.class); + assertDbSchema(ds, config); + }); } - private void assertDbSchema(DataSource ds, PgconfigBackendProperties config) - throws SQLException { + private void assertDbSchema(DataSource ds, PgconfigBackendProperties config) throws SQLException { String schema = config.schema(); Map expected = buildExpected(schema); Map actual = findTables(ds, schema); @@ -95,37 +86,35 @@ private Map findTables(DataSource ds, String schema) throws SQLE * @return */ private Map buildExpected(String schema) { - List views = - List.of( - "workspaceinfos", - "namespaceinfos", - "storeinfos", - "resourceinfos", - "layerinfos", - "layergroupinfos", - "styleinfos", - "settingsinfos", - "serviceinfos", - "publishedinfos", - "tilelayers"); - List tables = - List.of( - "flyway_schema_history", - "cataloginfo", - "layergroupinfo", - "layerinfo", - "namespaceinfo", - "publishedinfo", - "resourceinfo", - "storeinfo", - "styleinfo", - "workspaceinfo", - "geoserverinfo", - "settingsinfo", - "serviceinfo", - "logginginfo", - "resourcestore", - "resource_lock"); + List views = List.of( + "workspaceinfos", + "namespaceinfos", + "storeinfos", + "resourceinfos", + "layerinfos", + "layergroupinfos", + "styleinfos", + "settingsinfos", + "serviceinfos", + "publishedinfos", + "tilelayers"); + List tables = List.of( + "flyway_schema_history", + "cataloginfo", + "layergroupinfo", + "layerinfo", + "namespaceinfo", + "publishedinfo", + "resourceinfo", + "storeinfo", + "styleinfo", + "workspaceinfo", + "geoserverinfo", + "settingsinfo", + "serviceinfo", + "logginginfo", + "resourcestore", + "resource_lock"); List sequences = List.of("gs_update_sequence", "resourcestore_id_seq"); Map expected = new TreeMap<>(); diff --git a/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/catalog/PgconfigCatalogBackendConformanceTest.java b/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/catalog/PgconfigCatalogBackendConformanceTest.java index 902f99ade..806114f5e 100644 --- a/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/catalog/PgconfigCatalogBackendConformanceTest.java +++ b/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/catalog/PgconfigCatalogBackendConformanceTest.java @@ -4,6 +4,8 @@ */ package org.geoserver.cloud.backend.pgconfig.catalog; +import java.io.File; +import javax.sql.DataSource; import org.geoserver.catalog.impl.CatalogImpl; import org.geoserver.catalog.plugin.CatalogConformanceTest; import org.geoserver.catalog.plugin.CatalogPlugin; @@ -26,17 +28,14 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import java.io.File; - -import javax.sql.DataSource; - /** * @since 1.4 */ @Testcontainers(disabledWithoutDocker = true) class PgconfigCatalogBackendConformanceTest extends CatalogConformanceTest { - @Container static PgConfigTestContainer container = new PgConfigTestContainer<>(); + @Container + static PgConfigTestContainer container = new PgConfigTestContainer<>(); @Override @BeforeEach @@ -56,16 +55,11 @@ protected CatalogImpl createCatalog(File tmpFolder) { PgconfigLockProvider lockProvider = new PgconfigLockProvider(pgconfigLockRegistry()); File cacheDirectory = tmpFolder; - PgconfigResourceStore resourceStore = - new PgconfigResourceStore( - cacheDirectory.toPath(), - template, - lockProvider, - PgconfigResourceStore.defaultIgnoredDirs()); + PgconfigResourceStore resourceStore = new PgconfigResourceStore( + cacheDirectory.toPath(), template, lockProvider, PgconfigResourceStore.defaultIgnoredDirs()); var resourceLoader = new PgconfigGeoServerResourceLoader(resourceStore); - CatalogPlugin catalog = - new PgconfigBackendBuilder(container.getDataSource()).createCatalog(); + CatalogPlugin catalog = new PgconfigBackendBuilder(container.getDataSource()).createCatalog(); catalog.setResourceLoader(resourceLoader); final boolean backupSldFiles = false; catalog.addListener(new CatalogPluginStyleResourcePersister(catalog, backupSldFiles)); @@ -78,8 +72,7 @@ private LockRegistry pgconfigLockRegistry() { LockRepository pgconfigLockRepository() { DataSource dataSource = container.getDataSource(); - DefaultLockRepository lockRepository = - new DefaultLockRepository(dataSource, "test-instance"); + DefaultLockRepository lockRepository = new DefaultLockRepository(dataSource, "test-instance"); // override default table prefix "INT" by "RESOURCE_" (matching table definition // RESOURCE_LOCK in init.XXX.sql lockRepository.setPrefix("RESOURCE_"); diff --git a/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigWorkspaceRepositoryTest.java b/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigWorkspaceRepositoryTest.java index 4d3fbc524..369860fb9 100644 --- a/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigWorkspaceRepositoryTest.java +++ b/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/catalog/repository/PgconfigWorkspaceRepositoryTest.java @@ -6,6 +6,7 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.util.Optional; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.impl.WorkspaceInfoImpl; import org.geoserver.cloud.backend.pgconfig.support.PgConfigTestContainer; @@ -15,15 +16,14 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import java.util.Optional; - /** * @since 1.4 */ @Testcontainers(disabledWithoutDocker = true) class PgconfigWorkspaceRepositoryTest { - @Container static PgConfigTestContainer container = new PgConfigTestContainer<>(); + @Container + static PgConfigTestContainer container = new PgConfigTestContainer<>(); PgconfigWorkspaceRepository repo; diff --git a/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigConfigRepositoryConformanceTest.java b/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigConfigRepositoryConformanceTest.java index e53f38540..9b71dbad5 100644 --- a/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigConfigRepositoryConformanceTest.java +++ b/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigConfigRepositoryConformanceTest.java @@ -26,7 +26,8 @@ @Testcontainers(disabledWithoutDocker = true) class PgconfigConfigRepositoryConformanceTest extends GeoServerConfigConformanceTest { - @Container static PgConfigTestContainer container = new PgConfigTestContainer<>(); + @Container + static PgConfigTestContainer container = new PgConfigTestContainer<>(); @Override @BeforeEach @@ -65,12 +66,9 @@ void testAddDuplicateServiceToWorkspace() { dupTypeAndWorkspace.setName("TEST-OWS"); dupTypeAndWorkspace.setTitle("Service for WS1"); - var ex = - assertThrows( - IllegalArgumentException.class, () -> geoServer.add(dupTypeAndWorkspace)); + var ex = assertThrows(IllegalArgumentException.class, () -> geoServer.add(dupTypeAndWorkspace)); assertThat(ex.getMessage()) - .contains( - "service with name 'TEST-OWS' already exists in workspace 'TEST-WORKSPACE-1'"); + .contains("service with name 'TEST-OWS' already exists in workspace 'TEST-WORKSPACE-1'"); } } diff --git a/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigUpdateSequenceTest.java b/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigUpdateSequenceTest.java index 1b3565eb1..2f7b91833 100644 --- a/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigUpdateSequenceTest.java +++ b/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/config/PgconfigUpdateSequenceTest.java @@ -21,7 +21,8 @@ @SuppressWarnings("java:S2187") class PgconfigUpdateSequenceTest implements UpdateSequenceConformanceTest { - @Container static PgConfigTestContainer container = new PgConfigTestContainer<>(); + @Container + static PgConfigTestContainer container = new PgConfigTestContainer<>(); private UpdateSequence sequence; private PgconfigGeoServerFacade facade; diff --git a/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigResourceTest.java b/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigResourceTest.java index e4e5e5e1a..9948997ce 100644 --- a/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigResourceTest.java +++ b/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/resource/PgconfigResourceTest.java @@ -19,8 +19,16 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; +import java.io.File; +import java.sql.SQLException; +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; +import javax.sql.DataSource; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.backend.pgconfig.support.PgConfigTestContainer; import org.geoserver.platform.resource.Paths; import org.geoserver.platform.resource.Resource; @@ -45,17 +53,6 @@ import org.springframework.integration.support.locks.LockRegistry; import org.springframework.jdbc.core.JdbcTemplate; -import java.io.File; -import java.sql.SQLException; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.TreeSet; -import java.util.stream.Collectors; - -import javax.sql.DataSource; - /** * Note by inheriting from {@link ResourceTheoryTest}, this is a Junit 4 test class and must be * {@code public} @@ -64,9 +61,12 @@ @RunWith(Theories.class) public class PgconfigResourceTest extends ResourceTheoryTest { - @ClassRule public static PgConfigTestContainer container = new PgConfigTestContainer<>(); + @ClassRule + public static PgConfigTestContainer container = new PgConfigTestContainer<>(); + + @Rule + public TemporaryFolder tmpDir = new TemporaryFolder(); - @Rule public TemporaryFolder tmpDir = new TemporaryFolder(); private PgconfigResourceStore store; private File cacheDirectory; @@ -104,12 +104,8 @@ public void setUp() throws Exception { JdbcTemplate template = container.getTemplate(); PgconfigLockProvider lockProvider = new PgconfigLockProvider(pgconfigLockRegistry()); cacheDirectory = tmpDir.newFolder(); - store = - new PgconfigResourceStore( - cacheDirectory.toPath(), - template, - lockProvider, - PgconfigResourceStore.defaultIgnoredDirs()); + store = new PgconfigResourceStore( + cacheDirectory.toPath(), template, lockProvider, PgconfigResourceStore.defaultIgnoredDirs()); setupTestData(template); } @@ -130,10 +126,7 @@ private void setupTestData(JdbcTemplate template) throws Exception { String parentPath = Paths.parent(path); Objects.requireNonNull(parentPath); long parentId = - template.queryForObject( - "SELECT id FROM resourcestore WHERE path = ?", - Long.class, - parentPath); + template.queryForObject("SELECT id FROM resourcestore WHERE path = ?", Long.class, parentPath); Resource.Type type = dir ? Type.DIRECTORY : Type.RESOURCE; byte[] contents = dir ? null : path.getBytes("UTF-8"); String sql = @@ -158,8 +151,7 @@ private LockRegistry pgconfigLockRegistry() { LockRepository pgconfigLockRepository() { DataSource dataSource = container.getDataSource(); - DefaultLockRepository lockRepository = - new DefaultLockRepository(dataSource, "test-instance"); + DefaultLockRepository lockRepository = new DefaultLockRepository(dataSource, "test-instance"); // override default table prefix "INT" by "RESOURCE_" (matching table definition // RESOURCE_LOCK in init.XXX.sql lockRepository.setPrefix("RESOURCE_"); @@ -287,18 +279,14 @@ private void assertFileSystemFile(String path) { assertFileSystemDir(resource.parent().path()); assertFalse(resource instanceof PgconfigResource); assertTrue(resource instanceof PgconfigResourceStore.FileSystemResourceAdaptor); - assertTrue( - resource.file() - .getAbsolutePath() - .startsWith(this.cacheDirectory.getAbsolutePath())); + assertTrue(resource.file().getAbsolutePath().startsWith(this.cacheDirectory.getAbsolutePath())); } private void assertFileSystemDir(String path) { Resource resource = getResource(path); assertFalse(resource instanceof PgconfigResource); assertTrue(resource instanceof PgconfigResourceStore.FileSystemResourceAdaptor); - assertTrue( - resource.dir().getAbsolutePath().startsWith(this.cacheDirectory.getAbsolutePath())); + assertTrue(resource.dir().getAbsolutePath().startsWith(this.cacheDirectory.getAbsolutePath())); } @Test @@ -411,9 +399,7 @@ public void trestMovePathFilesystemOnlyToDatabaseIsUnsupported() { UnsupportedOperationException.class, () -> store.move("legendsamples/sample.png", "workspaces/sample2.png")); - assertThrows( - UnsupportedOperationException.class, - () -> store.move("workspaces/ws1", "temp/ws1")); + assertThrows(UnsupportedOperationException.class, () -> store.move("workspaces/ws1", "temp/ws1")); } @Test diff --git a/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/support/PgConfigTestContainer.java b/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/support/PgConfigTestContainer.java index 6f4027cb7..5a6c44609 100644 --- a/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/support/PgConfigTestContainer.java +++ b/src/catalog/backends/pgconfig/src/test/java/org/geoserver/cloud/backend/pgconfig/support/PgConfigTestContainer.java @@ -6,10 +6,9 @@ import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; - +import javax.sql.DataSource; import lombok.Getter; import lombok.SneakyThrows; - import org.geoserver.cloud.autoconfigure.jndi.SimpleJNDIStaticContextInitializer; import org.geoserver.cloud.config.catalog.backend.pgconfig.PgconfigDatabaseMigrations; import org.geoserver.cloud.config.jndi.JNDIDataSourceConfiguration; @@ -19,8 +18,6 @@ import org.testcontainers.Testcontainers; import org.testcontainers.containers.PostgreSQLContainer; -import javax.sql.DataSource; - /** * A {@link Testcontainers test container} based on {@link PostgreSQLContainer} using PostgreSQL 15 * to aid in setting up the {@code DataSource}, {@code JdbcTemplate}, and {@link @@ -30,8 +27,7 @@ * @since 1.6 */ @SuppressWarnings("java:S119") -public class PgConfigTestContainer> - extends PostgreSQLContainer { +public class PgConfigTestContainer> extends PostgreSQLContainer { private @Getter DataSource dataSource; private @Getter JdbcTemplate template; @@ -57,11 +53,10 @@ public PgConfigTestContainer setUp() { hikariConfig.setSchema(schema); dataSource = new HikariDataSource(hikariConfig); template = new JdbcTemplate(dataSource); - databaseMigrations = - new PgconfigDatabaseMigrations() - .setSchema(schema) - .setDataSource(dataSource) - .setCleanDisabled(false); + databaseMigrations = new PgconfigDatabaseMigrations() + .setSchema(schema) + .setDataSource(dataSource) + .setCleanDisabled(false); databaseMigrations.migrate(); return this; } @@ -76,13 +71,12 @@ public void tearDown() { String url = getJdbcUrl(); String username = getUsername(); String password = getPassword(); - return (R) - runner.withPropertyValues( // - "geoserver.backend.pgconfig.enabled=true", // - "geoserver.backend.pgconfig.datasource.url=" + url, // - "geoserver.backend.pgconfig.datasource.username=" + username, // - "geoserver.backend.pgconfig.datasource.password=" + password // - ); + return (R) runner.withPropertyValues( // + "geoserver.backend.pgconfig.enabled=true", // + "geoserver.backend.pgconfig.datasource.url=" + url, // + "geoserver.backend.pgconfig.datasource.username=" + username, // + "geoserver.backend.pgconfig.datasource.password=" + password // + ); } @SuppressWarnings("unchecked") @@ -90,19 +84,18 @@ public void tearDown() { String url = getJdbcUrl(); String username = getUsername(); String password = getPassword(); - return (R) - runner - // enable simplejndi - .withInitializer(new SimpleJNDIStaticContextInitializer()) - .withConfiguration(AutoConfigurations.of(JNDIDataSourceConfiguration.class)) - .withPropertyValues( - "geoserver.backend.pgconfig.enabled: true", // - // java:comp/env/jdbc/testdb config properties - "jndi.datasources.testdb.enabled: true", // - "jndi.datasources.testdb.url: " + url, - "jndi.datasources.testdb.username: " + username, // - "jndi.datasources.testdb.password: " + password, // - // pgconfig backend datasource config using jndi - "geoserver.backend.pgconfig.datasource.jndi-name: java:comp/env/jdbc/testdb"); + return (R) runner + // enable simplejndi + .withInitializer(new SimpleJNDIStaticContextInitializer()) + .withConfiguration(AutoConfigurations.of(JNDIDataSourceConfiguration.class)) + .withPropertyValues( + "geoserver.backend.pgconfig.enabled: true", // + // java:comp/env/jdbc/testdb config properties + "jndi.datasources.testdb.enabled: true", // + "jndi.datasources.testdb.url: " + url, + "jndi.datasources.testdb.username: " + username, // + "jndi.datasources.testdb.password: " + password, // + // pgconfig backend datasource config using jndi + "geoserver.backend.pgconfig.datasource.jndi-name: java:comp/env/jdbc/testdb"); } } diff --git a/src/catalog/cache/src/main/java/org/geoserver/cloud/autoconfigure/catalog/cache/ConditionalOnBackendCacheEnabled.java b/src/catalog/cache/src/main/java/org/geoserver/cloud/autoconfigure/catalog/cache/ConditionalOnBackendCacheEnabled.java index 124b25f32..de62b2e24 100644 --- a/src/catalog/cache/src/main/java/org/geoserver/cloud/autoconfigure/catalog/cache/ConditionalOnBackendCacheEnabled.java +++ b/src/catalog/cache/src/main/java/org/geoserver/cloud/autoconfigure/catalog/cache/ConditionalOnBackendCacheEnabled.java @@ -4,22 +4,18 @@ */ package org.geoserver.cloud.autoconfigure.catalog.cache; -import org.geoserver.cloud.catalog.cache.GeoServerBackendCacheConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.geoserver.cloud.catalog.cache.GeoServerBackendCacheConfiguration; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) @Documented @ConditionalOnClass(GeoServerBackendCacheConfiguration.class) -@ConditionalOnProperty( - name = "geoserver.catalog.caching.enabled", - havingValue = "true", - matchIfMissing = false) +@ConditionalOnProperty(name = "geoserver.catalog.caching.enabled", havingValue = "true", matchIfMissing = false) public @interface ConditionalOnBackendCacheEnabled {} diff --git a/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachedReferenceCleaner.java b/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachedReferenceCleaner.java index 33352362d..08793e860 100644 --- a/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachedReferenceCleaner.java +++ b/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachedReferenceCleaner.java @@ -6,12 +6,12 @@ import com.github.benmanes.caffeine.cache.Cache; import com.google.common.base.Stopwatch; - +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicInteger; import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.LayerGroupInfo; import org.geoserver.catalog.LayerInfo; @@ -23,23 +23,20 @@ import org.geoserver.catalog.plugin.AbstractCatalogVisitor; import org.springframework.lang.Nullable; -import java.util.concurrent.ConcurrentMap; -import java.util.concurrent.atomic.AtomicInteger; - @RequiredArgsConstructor @Slf4j(topic = "org.geoserver.cloud.catalog.cache") class CachedReferenceCleaner { - @NonNull private final Cache caffeine; + @NonNull + private final Cache caffeine; static CachedReferenceCleaner newInstance(org.springframework.cache.@NonNull Cache cache) { Object nativeCache = cache.getNativeCache(); if (nativeCache instanceof com.github.benmanes.caffeine.cache.Cache caffeineCache) { return new CachedReferenceCleaner(caffeineCache); } - throw new UnsupportedOperationException( - "Expected Caffeine cache, got unsupported cache implementation: %s" - .formatted(nativeCache.getClass().getCanonicalName())); + throw new UnsupportedOperationException("Expected Caffeine cache, got unsupported cache implementation: %s" + .formatted(nativeCache.getClass().getCanonicalName())); } /** @@ -60,10 +57,7 @@ public void cascadeEvict(InfoIdKey evicted) { try { cascadedEvictCount = cascadeEvict(evicted, cache, visited); } catch (RuntimeException e) { - log.warn( - "Error cascade-evicting cached entries referencing {}, clearing out the whole cache", - evicted, - e); + log.warn("Error cascade-evicting cached entries referencing {}, clearing out the whole cache", evicted, e); caffeine.invalidateAll(); return; } @@ -102,10 +96,8 @@ private final boolean canReference(CatalogInfo cached, InfoIdKey evicted) { return switch (evicted.type()) { case WORKSPACE -> canReferenceWorkspace(cached, evicted); case NAMESPACE -> canReferenceNamespace(cached, evicted); - case COVERAGESTORE, DATASTORE, WMSSTORE, WMTSSTORE -> canReferenceStore( - cached, evicted); - case COVERAGE, FEATURETYPE, WMSLAYER, WMTSLAYER -> canReferenceResource( - cached, evicted); + case COVERAGESTORE, DATASTORE, WMSSTORE, WMTSSTORE -> canReferenceStore(cached, evicted); + case COVERAGE, FEATURETYPE, WMSLAYER, WMTSLAYER -> canReferenceResource(cached, evicted); // evicted a LayerInfo, only LayerGroupInfos may reference it case LAYER -> cached instanceof LayerGroupInfo; @@ -124,8 +116,7 @@ private boolean canReferenceStyle(CatalogInfo cached, InfoIdKey evicted) { || (cached instanceof LayerInfo l && (canReference(l.getDefaultStyle(), evicted) || (!l.getStyles().isEmpty() - && l.getStyles().stream() - .anyMatch(s -> canReference(s, evicted))))) + && l.getStyles().stream().anyMatch(s -> canReference(s, evicted))))) || cached instanceof LayerGroupInfo; } @@ -167,10 +158,12 @@ private boolean canReferenceWorkspace(CatalogInfo cached, InfoIdKey evicted) { @RequiredArgsConstructor private static class CachedReferenceCleanerVisitor extends AbstractCatalogVisitor { - @NonNull private final ConcurrentMap cache; + @NonNull + private final ConcurrentMap cache; /** key for the evicted oject. Will evict any cached object that has a reference to it */ - @NonNull private final InfoIdKey evictedKey; + @NonNull + private final InfoIdKey evictedKey; /** * The cached object being traversed, to be evicted if it has any nested reference to {@link @@ -182,7 +175,8 @@ private static class CachedReferenceCleanerVisitor extends AbstractCatalogVisito * Number of cascaded evictions (0, 1 or 2 for {@link #cached}'s InfoIdKey and/or * InfoNameKey) */ - @Getter private int count; + @Getter + private int count; public int cascadeEvict(CatalogInfo cached) { this.cached = cached; @@ -252,12 +246,10 @@ private void traverse(@Nullable CatalogInfo info) { if (0 == count) lg.getLayers().forEach(this::traverse); if (0 == count) lg.getStyles().forEach(this::traverse); if (0 == count) - lg.getLayerGroupStyles() - .forEach( - lgs -> { - lgs.getStyles().forEach(this::traverse); - lgs.getLayers().forEach(this::traverse); - }); + lg.getLayerGroupStyles().forEach(lgs -> { + lgs.getStyles().forEach(this::traverse); + lgs.getLayers().forEach(this::traverse); + }); } } } diff --git a/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachingCatalogFacade.java b/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachingCatalogFacade.java index 3b399bbb9..0cc43dc65 100644 --- a/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachingCatalogFacade.java +++ b/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachingCatalogFacade.java @@ -11,9 +11,9 @@ import static org.geoserver.cloud.event.info.ConfigInfoType.WORKSPACE; import com.google.common.annotations.VisibleForTesting; - +import java.util.List; +import java.util.Optional; import lombok.NonNull; - import org.geoserver.catalog.CatalogFacade; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.DataStoreInfo; @@ -39,9 +39,6 @@ import org.springframework.context.event.EventListener; import org.springframework.lang.Nullable; -import java.util.List; -import java.util.Optional; - /** * @see CachingCatalogFacadeContainmentSupport */ @@ -63,8 +60,7 @@ public CachingCatalogFacade(@NonNull ExtendedCatalogFacade facade, @NonNull Cach } CachingCatalogFacade( - @NonNull ExtendedCatalogFacade facade, - @NonNull CachingCatalogFacadeContainmentSupport support) { + @NonNull ExtendedCatalogFacade facade, @NonNull CachingCatalogFacadeContainmentSupport support) { super(facade); this.support = support; } @@ -138,12 +134,10 @@ public I update(@NonNull final I info, @NonNull final Pa } private void evictNewName(final I info, final Patch patch) { - newPrefixedName(info, patch) - .ifPresent( - newPrefixexName -> { - var type = ConfigInfoType.valueOf(info); - support.evict(info.getId(), newPrefixexName, type); - }); + newPrefixedName(info, patch).ifPresent(newPrefixexName -> { + var type = ConfigInfoType.valueOf(info); + support.evict(info.getId(), newPrefixexName, type); + }); } Optional newPrefixedName(CatalogInfo info, Patch patch) { @@ -213,9 +207,7 @@ public StyleInfo getStyleByName(@NonNull WorkspaceInfo workspace, @NonNull Strin return super.getStyleByName(workspace, name); } - return support.get( - InfoNameKey.valueOf(workspace, name, STYLE), - () -> super.getStyleByName(workspace, name)); + return support.get(InfoNameKey.valueOf(workspace, name, STYLE), () -> super.getStyleByName(workspace, name)); } @Override @@ -244,8 +236,7 @@ public LayerGroupInfo getLayerGroupByName(@NonNull String name) { } @Override - public LayerGroupInfo getLayerGroupByName( - @NonNull WorkspaceInfo workspace, @NonNull String name) { + public LayerGroupInfo getLayerGroupByName(@NonNull WorkspaceInfo workspace, @NonNull String name) { if (NO_WORKSPACE == workspace || ANY_WORKSPACE == workspace) { return super.getLayerGroupByName(workspace, name); } @@ -282,8 +273,7 @@ public DataStoreInfo getDefaultDataStore(@NonNull WorkspaceInfo workspace) { } @Override - public void setDefaultDataStore( - @NonNull WorkspaceInfo workspace, @Nullable DataStoreInfo store) { + public void setDefaultDataStore(@NonNull WorkspaceInfo workspace, @Nullable DataStoreInfo store) { support.evictDefaultDataStore(workspace); super.setDefaultDataStore(workspace, store); } diff --git a/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachingCatalogFacadeContainmentSupport.java b/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachingCatalogFacadeContainmentSupport.java index 258a48dae..da9f8f30a 100644 --- a/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachingCatalogFacadeContainmentSupport.java +++ b/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachingCatalogFacadeContainmentSupport.java @@ -8,13 +8,16 @@ import static org.geoserver.cloud.event.info.ConfigInfoType.STORE; import com.google.common.annotations.VisibleForTesting; - +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.concurrent.Callable; +import javax.annotation.ParametersAreNonnullByDefault; import lombok.AccessLevel; import lombok.Getter; import lombok.NonNull; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.CatalogFacade; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.DataStoreInfo; @@ -31,13 +34,6 @@ import org.springframework.cache.Cache; import org.springframework.cache.caffeine.CaffeineCacheManager; -import java.util.Collection; -import java.util.List; -import java.util.Objects; -import java.util.concurrent.Callable; - -import javax.annotation.ParametersAreNonnullByDefault; - /** * @since 1.7 */ @@ -107,8 +103,7 @@ public boolean evict(String id, String prefixedName, ConfigInfoType type) { return evictInternal(id, prefixedName, type, true); } - private boolean evictInternal( - String id, String prefixedName, ConfigInfoType type, boolean doLog) { + private boolean evictInternal(String id, String prefixedName, ConfigInfoType type, boolean doLog) { boolean evicted = false; if (type.isA(WorkspaceInfo.class)) { evictDefaultDataStore(id, prefixedName); @@ -124,8 +119,7 @@ private boolean evictInternal( evicted |= evict(idKey); evicted |= evict(nameKey); if (evicted && doLog) - log.debug( - "evicted {}[id: {}, name: {}]", type.type().getSimpleName(), id, prefixedName); + log.debug("evicted {}[id: {}, name: {}]", type.type().getSimpleName(), id, prefixedName); // regardless of the object being evicted or not, cascade evict any entry referencing it referenceCleaner.cascadeEvict(idKey); return evicted; @@ -171,8 +165,7 @@ public T get(Object key, Callable loader) { return value; } - public List getLayersByResource( - String resourceInfoId, Callable> loader) { + public List getLayersByResource(String resourceInfoId, Callable> loader) { InfoIdKey key = generateLayersByResourceKey(resourceInfoId); return get(key, loader); } @@ -209,8 +202,7 @@ public void evictDefaultNamespace() { } } - public DataStoreInfo getDefaultDataStore( - WorkspaceInfo workspace, Callable loader) { + public DataStoreInfo getDefaultDataStore(WorkspaceInfo workspace, Callable loader) { return cache.get(generateDefaultDataStoreKey(workspace.getId()), loader); } diff --git a/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachingFacadesLifeCycleHandler.java b/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachingFacadesLifeCycleHandler.java index 41caad1db..4ea1e379c 100644 --- a/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachingFacadesLifeCycleHandler.java +++ b/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachingFacadesLifeCycleHandler.java @@ -7,7 +7,6 @@ import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogFacade; import org.geoserver.catalog.impl.CatalogImpl; diff --git a/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachingGeoServerFacade.java b/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachingGeoServerFacade.java index 1a1f5ee48..9fa4d0469 100644 --- a/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachingGeoServerFacade.java +++ b/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/CachingGeoServerFacade.java @@ -4,9 +4,9 @@ */ package org.geoserver.cloud.catalog.cache; +import javax.annotation.Nullable; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.cloud.event.UpdateSequenceEvent; import org.geoserver.config.GeoServerFacade; @@ -23,8 +23,6 @@ import org.springframework.cache.annotation.Cacheable; import org.springframework.context.event.EventListener; -import javax.annotation.Nullable; - /** */ @CacheConfig(cacheNames = CachingGeoServerFacade.CACHE_NAME) @Slf4j(topic = "org.geoserver.cloud.catalog.caching") @@ -65,8 +63,7 @@ void onUpdateSequenceEvent(UpdateSequenceEvent event) { } ////// Cache manipulation functions /////// - T cachePutIncludeNull( - @NonNull Object key, @NonNull Cache cache, T service) { + T cachePutIncludeNull(@NonNull Object key, @NonNull Cache cache, T service) { if (service == null) { cache.put(key, null); @@ -234,15 +231,13 @@ public T getServiceByName(String name, Class clazz) { } @Override - public T getServiceByName( - String name, WorkspaceInfo workspace, Class clazz) { + public T getServiceByName(String name, WorkspaceInfo workspace, Class clazz) { Object key = CachingGeoServerFacade.serviceByNameKey(workspace, name); ValueWrapper value = cache.get(key); ServiceInfo service; if (value == null) { - service = - cachePutIncludeNull(key, cache, super.getServiceByName(name, workspace, clazz)); + service = cachePutIncludeNull(key, cache, super.getServiceByName(name, workspace, clazz)); } else { service = (ServiceInfo) value.get(); } @@ -264,8 +259,7 @@ public static Object serviceByNameKey(@Nullable WorkspaceInfo ws, @NonNull Strin return ServiceInfoKey.byName(ws, name); } - public static Object serviceByTypeKey( - @Nullable WorkspaceInfo ws, @NonNull Class type) { + public static Object serviceByTypeKey(@Nullable WorkspaceInfo ws, @NonNull Class type) { return ServiceInfoKey.byType(ws, type); } diff --git a/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/GeoServerBackendCacheConfiguration.java b/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/GeoServerBackendCacheConfiguration.java index 77a8af640..5d8b89475 100644 --- a/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/GeoServerBackendCacheConfiguration.java +++ b/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/GeoServerBackendCacheConfiguration.java @@ -4,6 +4,7 @@ */ package org.geoserver.cloud.catalog.cache; +import java.util.Objects; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogFacade; import org.geoserver.catalog.plugin.CatalogFacadeExtensionAdapter; @@ -20,8 +21,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import java.util.Objects; - /** * Enables caching at the {@link CatalogFacade} and {@link GeoServerFacade} level instead of at the * {@link Catalog} and {@link GeoServer} level, which would be the natural choice, in order not to @@ -61,8 +60,7 @@ CachingCatalogFacade cachingCatalogFacade( @Bean CachingGeoServerFacade cachingGeoServerFacade( - @Qualifier("geoserverFacade") GeoServerFacade rawGeoServerFacade, - CacheManager cacheManager) { + @Qualifier("geoserverFacade") GeoServerFacade rawGeoServerFacade, CacheManager cacheManager) { Cache cache = getCache(cacheManager, CachingGeoServerFacade.CACHE_NAME); return new CachingGeoServerFacade(rawGeoServerFacade, cache); } diff --git a/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/InfoIdKey.java b/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/InfoIdKey.java index 6b25e3e44..dc609b407 100644 --- a/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/InfoIdKey.java +++ b/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/InfoIdKey.java @@ -4,16 +4,14 @@ */ package org.geoserver.cloud.catalog.cache; +import java.io.Serializable; import lombok.NonNull; - import org.geoserver.catalog.Info; import org.geoserver.catalog.impl.ClassMappings; import org.geoserver.cloud.event.info.ConfigInfoType; import org.geoserver.cloud.event.info.InfoEvent; import org.springframework.cache.interceptor.SimpleKey; -import java.io.Serializable; - /** * A key to for a cached {@link Info} using its {@link Info#getId() id}. * diff --git a/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/InfoNameKey.java b/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/InfoNameKey.java index b29940315..563a6297d 100644 --- a/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/InfoNameKey.java +++ b/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/InfoNameKey.java @@ -4,8 +4,9 @@ */ package org.geoserver.cloud.catalog.cache; +import java.io.Serializable; +import java.util.Optional; import lombok.NonNull; - import org.geoserver.catalog.CatalogFacade; import org.geoserver.catalog.Info; import org.geoserver.catalog.NamespaceInfo; @@ -14,9 +15,6 @@ import org.geoserver.cloud.event.info.InfoEvent; import org.springframework.cache.interceptor.SimpleKey; -import java.io.Serializable; -import java.util.Optional; - /** * A key to for a cached {@link Info} using its prefixed name, according to {@link * InfoEvent#prefixedName(Info)}. @@ -24,15 +22,13 @@ *

    easier than implementing multiple key generators; it's also a smaller memory footprint than * {@link SimpleKey} */ -record InfoNameKey(@NonNull String prefixexName, @NonNull ConfigInfoType type) - implements Serializable { +record InfoNameKey(@NonNull String prefixexName, @NonNull ConfigInfoType type) implements Serializable { public static InfoNameKey valueOf(@NonNull Info info) { return new InfoNameKey(InfoEvent.prefixedName(info), InfoEvent.typeOf(info)); } - public static InfoNameKey valueOf( - WorkspaceInfo workspace, @NonNull String name, ConfigInfoType type) { + public static InfoNameKey valueOf(WorkspaceInfo workspace, @NonNull String name, ConfigInfoType type) { if (CatalogFacade.NO_WORKSPACE == workspace) { return valueOf(name, type); diff --git a/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/ServiceInfoKey.java b/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/ServiceInfoKey.java index d2086aa1a..bcad0941e 100644 --- a/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/ServiceInfoKey.java +++ b/src/catalog/cache/src/main/java/org/geoserver/cloud/catalog/cache/ServiceInfoKey.java @@ -4,11 +4,10 @@ */ package org.geoserver.cloud.catalog.cache; +import java.io.Serializable; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.config.ServiceInfo; -import java.io.Serializable; - /** */ record ServiceInfoKey(String key, String qualifier) implements Serializable { diff --git a/src/catalog/cache/src/test/java/org/geoserver/cloud/catalog/cache/CachingCatalogFacadeContainmentSupportTest.java b/src/catalog/cache/src/test/java/org/geoserver/cloud/catalog/cache/CachingCatalogFacadeContainmentSupportTest.java index c5826e787..c4843ca93 100644 --- a/src/catalog/cache/src/test/java/org/geoserver/cloud/catalog/cache/CachingCatalogFacadeContainmentSupportTest.java +++ b/src/catalog/cache/src/test/java/org/geoserver/cloud/catalog/cache/CachingCatalogFacadeContainmentSupportTest.java @@ -14,8 +14,11 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.util.List; +import java.util.Set; +import java.util.concurrent.Callable; +import java.util.function.BiFunction; import lombok.NonNull; - import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.CoverageInfo; import org.geoserver.catalog.CoverageStoreInfo; @@ -48,11 +51,6 @@ import org.junit.jupiter.api.Test; import org.springframework.cache.Cache.ValueWrapper; -import java.util.List; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.function.BiFunction; - /** * @since 1.7 */ @@ -73,9 +71,7 @@ private Callable loader() { @Test void testGetDefaultWorkspace() throws Exception { assertCaches( - WorkspaceInfo.class, - (supp, loader) -> supp.getDefaultWorkspace(loader), - DEFAULT_WORKSPACE_CACHE_KEY); + WorkspaceInfo.class, (supp, loader) -> supp.getDefaultWorkspace(loader), DEFAULT_WORKSPACE_CACHE_KEY); } @Test @@ -88,9 +84,7 @@ void testEvictDefaultWorkspace() { @Test void testGetDefaultNamespace() throws Exception { assertCaches( - NamespaceInfo.class, - (supp, loader) -> supp.getDefaultNamespace(loader), - DEFAULT_NAMESPACE_CACHE_KEY); + NamespaceInfo.class, (supp, loader) -> supp.getDefaultNamespace(loader), DEFAULT_NAMESPACE_CACHE_KEY); } @Test @@ -104,8 +98,7 @@ void testEvictDefaultNamespace() { void testGetDefaultDataStore() throws Exception { WorkspaceInfo ws = stub(WorkspaceInfo.class); Object key = support.generateDefaultDataStoreKey(ws.getId()); - assertCaches( - DataStoreInfo.class, (supp, loader) -> supp.getDefaultDataStore(ws, loader), key); + assertCaches(DataStoreInfo.class, (supp, loader) -> supp.getDefaultDataStore(ws, loader), key); } @Test @@ -246,8 +239,7 @@ private void testEvictEvictsIdAndNameKeys(Class clazz) { } @Test - @DisplayName( - "when a CatalogInfo is evicted, both the InfoIdKey and InfoNameKey entries are evicted") + @DisplayName("when a CatalogInfo is evicted, both the InfoIdKey and InfoNameKey entries are evicted") void testEvictCatalogInfoEvictsIdAndNameKeys() { WorkspaceInfo ws = stub(WorkspaceInfo.class); @@ -266,8 +258,7 @@ void testEvictCatalogInfoEvictsIdAndNameKeys() { } @Test - @DisplayName( - "when a LayerInfo is evicted, the layers by resource list for its ResourceInfo is evicted") + @DisplayName("when a LayerInfo is evicted, the layers by resource list for its ResourceInfo is evicted") void testEvictCatalogInfoLayerInfoEvictsLayersByResource() { LayerInfo layer = stub(LayerInfo.class); FeatureTypeInfo resource = stub(FeatureTypeInfo.class); @@ -283,8 +274,7 @@ void testEvictCatalogInfoLayerInfoEvictsLayersByResource() { } @Test - @DisplayName( - "when a StoreInfo is evicted, the keys for StoreInfo and its concrete type are evicted") + @DisplayName("when a StoreInfo is evicted, the keys for StoreInfo and its concrete type are evicted") void testEvictStoreInfoEvictsTheGenericAndConcreteTypeKeys() { var store = stubWithRefs(DataStoreInfo.class); InfoIdKey id = InfoIdKey.valueOf(store); @@ -304,8 +294,7 @@ void testEvictStoreInfoEvictsTheGenericAndConcreteTypeKeys() { } @Test - @DisplayName( - "when a ResourceInfo is evicted, the keys for ResourceInfo and its concrete type are evicted") + @DisplayName("when a ResourceInfo is evicted, the keys for ResourceInfo and its concrete type are evicted") void testEvictResourceInfoEvictsTheGenericAndConcreteTypeKeys() { var resource = stubWithRefs(FeatureTypeInfo.class); InfoIdKey id = InfoIdKey.valueOf(resource); @@ -363,8 +352,7 @@ void testEvictStyleEvictsLayersAndLayerGroupsReferencingIt() { LayerInfo layer2 = stubLayer("layer2", defStyle2, Set.of(defStyle2, style2)); LayerGroupInfo lg1 = stubLayerGroup("lg1", List.of(layer1), List.of(defStyle1)); - LayerGroupInfo lg2 = - stubLayerGroup("lg2", List.of(layer1, layer2), List.of(defStyle1, defStyle2)); + LayerGroupInfo lg2 = stubLayerGroup("lg2", List.of(layer1, layer2), List.of(defStyle1, defStyle2)); put(defStyle1, defStyle2, style1, style2, layer1, layer2, lg1, lg2); assertAllCached(defStyle1, defStyle2, style1, style2, layer1, layer2, lg1, lg2); @@ -389,8 +377,7 @@ void testEvictStyleEvictsLayersAndLayerGroupsReferencingIt() { } @Test - @DisplayName( - "when a WorkspaceInfo is evicted, all objects referencing it directly or indirectly are evicted") + @DisplayName("when a WorkspaceInfo is evicted, all objects referencing it directly or indirectly are evicted") void testEvictWorkspaceInfoEvictsAllInfosReferencingIt() { WorkspaceInfo ws1 = stubReal(WorkspaceInfo.class, "ws1", "workspace1"); NamespaceInfo ns1 = stubReal(NamespaceInfo.class, "ns1", "workspace1"); @@ -433,9 +420,7 @@ void testEvictWorkspaceInfoEvictsAllInfosReferencingIt() { } void assertCaches( - Class type, - BiFunction, T> getter, - Object... keys) + Class type, BiFunction, T> getter, Object... keys) throws Exception { Callable loader = loader(); @@ -557,8 +542,7 @@ private C create(@NonNull ConfigInfoType type) { case NAMESPACE -> new NamespaceInfoImpl(); case WORKSPACE -> new WorkspaceInfoImpl(); case DATASTORE -> new DataStoreInfoImpl(null); - default -> throw new UnsupportedOperationException( - "not configured to create " + type); + default -> throw new UnsupportedOperationException("not configured to create " + type); }); } @@ -589,8 +573,7 @@ private LayerInfo stubLayer(String name, StyleInfo defaultStyle, Set return layer; } - private LayerGroupInfo stubLayerGroup( - String name, List layers, List styles) { + private LayerGroupInfo stubLayerGroup(String name, List layers, List styles) { var lg = stubReal(LayerGroupInfo.class, name + "-id", name); lg.getLayers().addAll(layers); diff --git a/src/catalog/cache/src/test/java/org/geoserver/cloud/catalog/cache/CachingCatalogFacadeTest.java b/src/catalog/cache/src/test/java/org/geoserver/cloud/catalog/cache/CachingCatalogFacadeTest.java index 783e2d4a4..9a896051f 100644 --- a/src/catalog/cache/src/test/java/org/geoserver/cloud/catalog/cache/CachingCatalogFacadeTest.java +++ b/src/catalog/cache/src/test/java/org/geoserver/cloud/catalog/cache/CachingCatalogFacadeTest.java @@ -21,8 +21,13 @@ import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.concurrent.Callable; +import java.util.function.Function; +import java.util.function.Supplier; import lombok.SneakyThrows; - import org.geoserver.catalog.CatalogFacade; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.CoverageInfo; @@ -58,17 +63,13 @@ import org.mockito.internal.verification.VerificationModeFactory; import org.mockito.verification.VerificationMode; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.Callable; -import java.util.function.Function; -import java.util.function.Supplier; - class CachingCatalogFacadeTest { - @Mock ExtendedCatalogFacade subject; - @Mock CachingCatalogFacadeContainmentSupport supportMock; + @Mock + ExtendedCatalogFacade subject; + + @Mock + CachingCatalogFacadeContainmentSupport supportMock; CachingCatalogFacade facade; @@ -151,8 +152,7 @@ void testAdd(Class type) { @Test void testUpdate() { assertThrows(NullPointerException.class, () -> facade.update(null, mock(Patch.class))); - assertThrows( - NullPointerException.class, () -> facade.update(mock(WorkspaceInfo.class), null)); + assertThrows(NullPointerException.class, () -> facade.update(mock(WorkspaceInfo.class), null)); testUpdate(WorkspaceInfo.class); testUpdate(NamespaceInfo.class); testUpdate(DataStoreInfo.class); @@ -177,14 +177,13 @@ void testUpdate(Class type) { String propName = NamespaceInfo.class.equals(type) ? "prefix" : "name"; Patch patch = new Patch(List.of(new Patch.Property(propName, newPrefixedName))); - facade = - new CachingCatalogFacade(subject, supportMock) { + facade = new CachingCatalogFacade(subject, supportMock) { - @Override - Optional newPrefixedName(CatalogInfo info, Patch patch) { - return Optional.of(newPrefixedName); - } - }; + @Override + Optional newPrefixedName(CatalogInfo info, Patch patch) { + return Optional.of(newPrefixedName); + } + }; facade.update(info, patch); @@ -279,8 +278,7 @@ void testSetDefaultDataStore() { @Test void testGetResource() { - assertThrows( - NullPointerException.class, () -> facade.getResource(null, ResourceInfo.class)); + assertThrows(NullPointerException.class, () -> facade.getResource(null, ResourceInfo.class)); assertThrows(NullPointerException.class, () -> facade.getResource("id", null)); testGetResource(FeatureTypeInfo.class); testGetResource(CoverageInfo.class); @@ -303,17 +301,12 @@ void testGetResource(Class type) { @Test void testGetResourceByName() { + assertThrows(NullPointerException.class, () -> facade.getResourceByName(null, "name", ResourceInfo.class)); assertThrows( NullPointerException.class, - () -> facade.getResourceByName(null, "name", ResourceInfo.class)); + () -> facade.getResourceByName(mock(NamespaceInfo.class), null, ResourceInfo.class)); assertThrows( - NullPointerException.class, - () -> - facade.getResourceByName( - mock(NamespaceInfo.class), null, ResourceInfo.class)); - assertThrows( - NullPointerException.class, - () -> facade.getResourceByName(mock(NamespaceInfo.class), "name", null)); + NullPointerException.class, () -> facade.getResourceByName(mock(NamespaceInfo.class), "name", null)); facade = new CachingCatalogFacade(subject); FeatureTypeInfo info = stub(FeatureTypeInfo.class); @@ -596,9 +589,7 @@ void testOnDefaultNamespaceSet() { @Test void testOnDefaultDataStoreSet() { - var event = - DefaultDataStoreSet.createLocal( - 1_000L, stub(WorkspaceInfo.class), stub(DataStoreInfo.class)); + var event = DefaultDataStoreSet.createLocal(1_000L, stub(WorkspaceInfo.class), stub(DataStoreInfo.class)); facade.onDefaultDataStoreSet(event); verify(supportMock, once()).evictDefaultDataStore(eq(event.getWorkspaceId()), any()); @@ -611,8 +602,7 @@ void testOnCatalogInfoAdded() { facade.onCatalogInfoAdded(event); - verify(supportMock, once()) - .evict(event.getObjectId(), event.getObjectName(), event.getObjectType()); + verify(supportMock, once()).evict(event.getObjectId(), event.getObjectName(), event.getObjectType()); when(event.isRemote()).thenReturn(false); clearInvocations(supportMock); @@ -628,10 +618,8 @@ void testOnCatalogInfoModified() { facade.onCatalogInfoModified(event); - verify(supportMock, once()) - .evict(event.getObjectId(), event.getObjectName(), event.getObjectType()); - verify(supportMock, once()) - .evict(event.getObjectId(), event.getOldName(), event.getObjectType()); + verify(supportMock, once()).evict(event.getObjectId(), event.getObjectName(), event.getObjectType()); + verify(supportMock, once()).evict(event.getObjectId(), event.getOldName(), event.getObjectType()); when(event.isRemote()).thenReturn(false); clearInvocations(supportMock); @@ -646,8 +634,7 @@ void testOnCatalogInfoRemoveEvent() { facade.onCatalogInfoRemovedEvent(event); - verify(supportMock, once()) - .evict(event.getObjectId(), event.getObjectName(), event.getObjectType()); + verify(supportMock, once()).evict(event.getObjectId(), event.getObjectName(), event.getObjectType()); when(event.isRemote()).thenReturn(false); clearInvocations(supportMock); diff --git a/src/catalog/cache/src/test/java/org/geoserver/cloud/catalog/cache/CachingGeoServerFacadeTest.java b/src/catalog/cache/src/test/java/org/geoserver/cloud/catalog/cache/CachingGeoServerFacadeTest.java index c20a77771..343ac88a5 100644 --- a/src/catalog/cache/src/test/java/org/geoserver/cloud/catalog/cache/CachingGeoServerFacadeTest.java +++ b/src/catalog/cache/src/test/java/org/geoserver/cloud/catalog/cache/CachingGeoServerFacadeTest.java @@ -20,6 +20,10 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.time.Duration; +import java.util.Arrays; +import java.util.function.Function; +import java.util.function.Supplier; import org.geoserver.catalog.Info; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.plugin.CatalogPlugin; @@ -59,11 +63,6 @@ import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; -import java.time.Duration; -import java.util.Arrays; -import java.util.function.Function; -import java.util.function.Supplier; - @SpringBootTest(classes = GeoServerBackendCacheConfiguration.class) @EnableAutoConfiguration(exclude = LocalCatalogEventsAutoConfiguration.class) class CachingGeoServerFacadeTest { diff --git a/src/catalog/cache/src/test/java/org/geoserver/cloud/catalog/cache/GeoServerBackendCacheConfigurationTest.java b/src/catalog/cache/src/test/java/org/geoserver/cloud/catalog/cache/GeoServerBackendCacheConfigurationTest.java index 207496023..18fb607a8 100644 --- a/src/catalog/cache/src/test/java/org/geoserver/cloud/catalog/cache/GeoServerBackendCacheConfigurationTest.java +++ b/src/catalog/cache/src/test/java/org/geoserver/cloud/catalog/cache/GeoServerBackendCacheConfigurationTest.java @@ -20,41 +20,25 @@ /** */ class GeoServerBackendCacheConfigurationTest { - private final ApplicationContextRunner contextRunner = - new ApplicationContextRunner() - .withAllowBeanDefinitionOverriding(true) - .withBean("rawCatalog", CatalogPlugin.class) - .withBean("geoServer", GeoServerImpl.class) - .withBean( - "catalogFacade", - ExtendedCatalogFacade.class, - () -> mock(ExtendedCatalogFacade.class)) - .withBean( - "geoserverFacade", - GeoServerFacade.class, - () -> mock(GeoServerFacade.class)) - .withConfiguration( - UserConfigurations.of(GeoServerBackendCacheConfiguration.class)) - .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withAllowBeanDefinitionOverriding(true) + .withBean("rawCatalog", CatalogPlugin.class) + .withBean("geoServer", GeoServerImpl.class) + .withBean("catalogFacade", ExtendedCatalogFacade.class, () -> mock(ExtendedCatalogFacade.class)) + .withBean("geoserverFacade", GeoServerFacade.class, () -> mock(GeoServerFacade.class)) + .withConfiguration(UserConfigurations.of(GeoServerBackendCacheConfiguration.class)) + .withConfiguration(AutoConfigurations.of(CacheAutoConfiguration.class)); @Test void testCachingCatalogFacade() { - contextRunner.run( - context -> - assertThat( - context.isTypeMatch( - "cachingCatalogFacade", CachingCatalogFacade.class)) - .isTrue()); + contextRunner.run(context -> assertThat(context.isTypeMatch("cachingCatalogFacade", CachingCatalogFacade.class)) + .isTrue()); } @Test void testCachingGeoServerFacade() { contextRunner.run( - context -> - assertThat( - context.isTypeMatch( - "cachingGeoServerFacade", - CachingGeoServerFacade.class)) - .isTrue()); + context -> assertThat(context.isTypeMatch("cachingGeoServerFacade", CachingGeoServerFacade.class)) + .isTrue()); } } diff --git a/src/catalog/event-bus/src/main/java/org/geoserver/cloud/autoconfigure/event/bus/ConditionalOnGeoServerRemoteEventsDisabled.java b/src/catalog/event-bus/src/main/java/org/geoserver/cloud/autoconfigure/event/bus/ConditionalOnGeoServerRemoteEventsDisabled.java index 0ecfaa2f9..1da3d9671 100644 --- a/src/catalog/event-bus/src/main/java/org/geoserver/cloud/autoconfigure/event/bus/ConditionalOnGeoServerRemoteEventsDisabled.java +++ b/src/catalog/event-bus/src/main/java/org/geoserver/cloud/autoconfigure/event/bus/ConditionalOnGeoServerRemoteEventsDisabled.java @@ -4,16 +4,15 @@ */ package org.geoserver.cloud.autoconfigure.event.bus; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.bus.BusBridge; -import org.springframework.cloud.bus.ConditionalOnBusEnabled; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.cloud.bus.BusBridge; +import org.springframework.cloud.bus.ConditionalOnBusEnabled; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) diff --git a/src/catalog/event-bus/src/main/java/org/geoserver/cloud/autoconfigure/event/bus/ConditionalOnGeoServerRemoteEventsEnabled.java b/src/catalog/event-bus/src/main/java/org/geoserver/cloud/autoconfigure/event/bus/ConditionalOnGeoServerRemoteEventsEnabled.java index b2c287c6b..ac8bf45f1 100644 --- a/src/catalog/event-bus/src/main/java/org/geoserver/cloud/autoconfigure/event/bus/ConditionalOnGeoServerRemoteEventsEnabled.java +++ b/src/catalog/event-bus/src/main/java/org/geoserver/cloud/autoconfigure/event/bus/ConditionalOnGeoServerRemoteEventsEnabled.java @@ -4,14 +4,13 @@ */ package org.geoserver.cloud.autoconfigure.event.bus; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.bus.ConditionalOnBusEnabled; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.cloud.bus.ConditionalOnBusEnabled; /** * GeoServer remote events enablement checks base on {@link diff --git a/src/catalog/event-bus/src/main/java/org/geoserver/cloud/autoconfigure/event/bus/GeoServerBusIntegrationAutoConfiguration.java b/src/catalog/event-bus/src/main/java/org/geoserver/cloud/autoconfigure/event/bus/GeoServerBusIntegrationAutoConfiguration.java index b25a58c61..3cd8cb2c8 100644 --- a/src/catalog/event-bus/src/main/java/org/geoserver/cloud/autoconfigure/event/bus/GeoServerBusIntegrationAutoConfiguration.java +++ b/src/catalog/event-bus/src/main/java/org/geoserver/cloud/autoconfigure/event/bus/GeoServerBusIntegrationAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.event.bus; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.autoconfigure.catalog.event.ConditionalOnCatalogEvents; import org.geoserver.cloud.event.bus.RemoteGeoServerEventsConfiguration; import org.springframework.boot.autoconfigure.AutoConfiguration; @@ -13,13 +13,9 @@ import org.springframework.cloud.bus.BusAutoConfiguration; import org.springframework.context.annotation.Import; -import javax.annotation.PostConstruct; - /** Log a message if spring-cloud-bus is explicitly disables */ @AutoConfiguration -@Import({ - GeoServerBusIntegrationAutoConfiguration.Enabled.class, - GeoServerBusIntegrationAutoConfiguration.Disabled.class +@Import({GeoServerBusIntegrationAutoConfiguration.Enabled.class, GeoServerBusIntegrationAutoConfiguration.Disabled.class }) @Slf4j(topic = "org.geoserver.cloud.autoconfigure.bus") public class GeoServerBusIntegrationAutoConfiguration { diff --git a/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/InfoEventResolver.java b/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/InfoEventResolver.java index 4fcdb9ad9..fca1477d2 100644 --- a/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/InfoEventResolver.java +++ b/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/InfoEventResolver.java @@ -4,9 +4,11 @@ */ package org.geoserver.cloud.event.bus; +import java.util.Optional; +import java.util.function.BiConsumer; +import java.util.function.UnaryOperator; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.Info; @@ -21,10 +23,6 @@ import org.geoserver.cloud.event.info.InfoModified; import org.geoserver.config.GeoServer; -import java.util.Optional; -import java.util.function.BiConsumer; -import java.util.function.UnaryOperator; - /** * Ensures the {@link Info} and {@link Patch} object payloads on {@link InfoAdded} and {@link * InfoModified} events from a remote source get their properties resolved before being catch up by @@ -42,27 +40,18 @@ public InfoEventResolver(@NonNull Catalog rawCatalog, @NonNull GeoServer geoserv proxyUtils = new ProxyUtils(() -> rawCatalog, Optional.of(geoserverConfig)); - BiConsumer onNotFound = - (info, proxy) -> - log.debug( - "Event object contains a reference to a non existing object ResolvingProxy(ref={})", - proxy.getRef()); + BiConsumer onNotFound = (info, proxy) -> log.debug( + "Event object contains a reference to a non existing object ResolvingProxy(ref={})", proxy.getRef()); - configInfoResolver = - CollectionPropertiesInitializer.instance() - .andThen( - ResolvingProxyResolver.of(rawCatalog) - .onNotFound(onNotFound)) - ::apply; + configInfoResolver = CollectionPropertiesInitializer.instance() + .andThen(ResolvingProxyResolver.of(rawCatalog).onNotFound(onNotFound))::apply; var catalogResolver = CatalogPropertyResolver.of(rawCatalog); var resolvingProxyResolver = ResolvingProxyResolver.of(rawCatalog).onNotFound(onNotFound); var collectionsInitializer = CollectionPropertiesInitializer.instance(); - catalogInfoResolver = - catalogResolver.andThen(collectionsInitializer).andThen(resolvingProxyResolver) - ::apply; + catalogInfoResolver = catalogResolver.andThen(collectionsInitializer).andThen(resolvingProxyResolver)::apply; } @SuppressWarnings("unchecked") diff --git a/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/RemoteGeoServerEvent.java b/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/RemoteGeoServerEvent.java index 94bf49f0d..903215d75 100644 --- a/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/RemoteGeoServerEvent.java +++ b/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/RemoteGeoServerEvent.java @@ -7,7 +7,6 @@ import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; - import org.geoserver.cloud.event.GeoServerEvent; import org.springframework.cloud.bus.event.Destination; import org.springframework.cloud.bus.event.RemoteApplicationEvent; @@ -16,7 +15,9 @@ @SuppressWarnings("serial") public class RemoteGeoServerEvent extends RemoteApplicationEvent { - @Getter @NonNull private GeoServerEvent event; + @Getter + @NonNull + private GeoServerEvent event; /** Deserialization-time constructor, {@link #getSource()} will be {@code null} */ @SuppressWarnings("java:S2637") // final fields initialized by deserialization @@ -38,11 +39,7 @@ public RemoteGeoServerEvent( public String toString() { return "[%s id: '%s', originService: '%s', destinationService: '%s', payload: %s]" .formatted( - getClass().getSimpleName(), - getId(), - getOriginService(), - getDestinationService(), - getEvent()); + getClass().getSimpleName(), getId(), getOriginService(), getDestinationService(), getEvent()); } public String toShortString() { diff --git a/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/RemoteGeoServerEventBridge.java b/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/RemoteGeoServerEventBridge.java index c1689afb9..2cf9d2e8e 100644 --- a/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/RemoteGeoServerEventBridge.java +++ b/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/RemoteGeoServerEventBridge.java @@ -5,10 +5,10 @@ package org.geoserver.cloud.event.bus; import com.google.common.annotations.VisibleForTesting; - +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.impl.ResolvingProxy; import org.geoserver.cloud.event.GeoServerEvent; @@ -19,9 +19,6 @@ import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Consumer; - /** * Listens to local catalog and configuration change {@link InfoEvent}s produced by this service * instance and broadcasts them to the cluster as {@link RemoteGeoServerEvent}, and conversely, @@ -81,8 +78,7 @@ void disable() { @Override public void destroy() { - log.info( - "RemoteGeoServerEventBridge received destroy signal, stopping remote event processing"); + log.info("RemoteGeoServerEventBridge received destroy signal, stopping remote event processing"); disable(); } @@ -114,8 +110,7 @@ public void publishLocalEvent(RemoteGeoServerEvent busEvent) { @EventListener(GeoServerEvent.class) @Order(Ordered.LOWEST_PRECEDENCE) public void publishRemoteEvent(GeoServerEvent event) { - mapper.mapIfLocal(event) - .ifPresentOrElse(this::dispatchAccepted, () -> logIgnoreRemoteLocal(event)); + mapper.mapIfLocal(event).ifPresentOrElse(this::dispatchAccepted, () -> logIgnoreRemoteLocal(event)); } private void dispatchAccepted(RemoteGeoServerEvent event) { @@ -141,8 +136,7 @@ private void doSend(RemoteGeoServerEvent outgoing) { private void doReceive(RemoteGeoServerEvent incoming) { try { GeoServerEvent localRemoteEvent = mapper.toLocalRemote(incoming); - if (log.isDebugEnabled()) - log.debug("publishing as local event {}", incoming.toShortString()); + if (log.isDebugEnabled()) log.debug("publishing as local event {}", incoming.toShortString()); inboundEventPublisher.accept(localRemoteEvent); } catch (RuntimeException e) { log.error("{}: error accepting remote {}", mapper.localBusServiceId(), incoming, e); @@ -153,9 +147,7 @@ private void doReceive(RemoteGeoServerEvent incoming) { private void logIgnoreLocalRemote(RemoteGeoServerEvent incoming) { if (log.isTraceEnabled()) log.trace( - "{}: not broadcasting local-remote event {}", - mapper.localBusServiceId(), - incoming.toShortString()); + "{}: not broadcasting local-remote event {}", mapper.localBusServiceId(), incoming.toShortString()); } private void logIgnoreRemoteLocal(GeoServerEvent event) { diff --git a/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/RemoteGeoServerEventMapper.java b/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/RemoteGeoServerEventMapper.java index f14836fc9..c520075a5 100644 --- a/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/RemoteGeoServerEventMapper.java +++ b/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/RemoteGeoServerEventMapper.java @@ -4,16 +4,14 @@ */ package org.geoserver.cloud.event.bus; +import java.util.Optional; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.cloud.event.GeoServerEvent; import org.geoserver.cloud.event.info.InfoEvent; import org.springframework.cloud.bus.ServiceMatcher; import org.springframework.cloud.bus.event.Destination; -import java.util.Optional; - /** * Aids {@link RemoteGeoServerEventBridge} in mapping {@link RemoteGeoServerEvent} to local {@link * GeoServerEvent} and vice-versa. @@ -42,8 +40,7 @@ private Destination destinationService() { public RemoteGeoServerEvent toRemote(GeoServerEvent anyLocalCatalogOrConfigEvent) { String origin = localBusServiceId(); Destination destination = destinationService(); - RemoteGeoServerEvent remote = - new RemoteGeoServerEvent(this, anyLocalCatalogOrConfigEvent, origin, destination); + RemoteGeoServerEvent remote = new RemoteGeoServerEvent(this, anyLocalCatalogOrConfigEvent, origin, destination); anyLocalCatalogOrConfigEvent.setOrigin(origin); anyLocalCatalogOrConfigEvent.setId(remote.getId()); return remote; @@ -72,8 +69,7 @@ public GeoServerEvent toLocalRemote(@NonNull RemoteGeoServerEvent incoming) { GeoServerEvent event = incoming.getEvent(); event.setRemote(true); event.setOrigin(incoming.getOriginService()); - if (event instanceof InfoEvent infoEvent) - event = remoteEventsPropertyResolver.resolve(infoEvent); + if (event instanceof InfoEvent infoEvent) event = remoteEventsPropertyResolver.resolve(infoEvent); return event; } } diff --git a/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/RemoteGeoServerEventsConfiguration.java b/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/RemoteGeoServerEventsConfiguration.java index 42d7efce3..b0b36d241 100644 --- a/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/RemoteGeoServerEventsConfiguration.java +++ b/src/catalog/event-bus/src/main/java/org/geoserver/cloud/event/bus/RemoteGeoServerEventsConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.event.bus; +import java.util.function.Consumer; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.Info; @@ -27,8 +27,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import java.util.function.Consumer; - /** Catalog and config events integration with spring cloud bus */ @Configuration(proxyBeanMethods = false) @RemoteApplicationEventScan(basePackageClasses = {RemoteGeoServerEvent.class}) @@ -76,8 +74,7 @@ GeoServerConfigModule geoServerConfigJacksonModule() { * other listeners. */ @Bean - InfoEventResolver remoteInfoEventInboundResolver( - @Qualifier("rawCatalog") Catalog rawCatalog, GeoServer geoserver) { + InfoEventResolver remoteInfoEventInboundResolver(@Qualifier("rawCatalog") Catalog rawCatalog, GeoServer geoserver) { return new InfoEventResolver(rawCatalog, geoserver); } @@ -87,8 +84,7 @@ RemoteGeoServerEventMapper remoteGeoServerEventMapper( ServiceMatcher serviceMatcher, Destination.Factory destinationFactory) { - return new RemoteGeoServerEventMapper( - remoteEventPropertiesResolver, serviceMatcher, destinationFactory); + return new RemoteGeoServerEventMapper(remoteEventPropertiesResolver, serviceMatcher, destinationFactory); } @Bean @@ -99,7 +95,6 @@ RemoteGeoServerEventBridge remoteEventBroadcaster( Consumer localEventPublisher = eventPublisher::publishEvent; Consumer remoteEventPublisher = eventPublisher::publishEvent; - return new RemoteGeoServerEventBridge( - localEventPublisher, remoteEventPublisher, eventMapper); + return new RemoteGeoServerEventBridge(localEventPublisher, remoteEventPublisher, eventMapper); } } diff --git a/src/catalog/event-bus/src/test/java/org/geoserver/cloud/autoconfigure/event/bus/GeoServerBusIntegrationAutoConfigurationTest.java b/src/catalog/event-bus/src/test/java/org/geoserver/cloud/autoconfigure/event/bus/GeoServerBusIntegrationAutoConfigurationTest.java index a2492c8e0..a6fdfd6a8 100644 --- a/src/catalog/event-bus/src/test/java/org/geoserver/cloud/autoconfigure/event/bus/GeoServerBusIntegrationAutoConfigurationTest.java +++ b/src/catalog/event-bus/src/test/java/org/geoserver/cloud/autoconfigure/event/bus/GeoServerBusIntegrationAutoConfigurationTest.java @@ -31,17 +31,14 @@ class GeoServerBusIntegrationAutoConfigurationTest { private final GeoServer mockGeoserver = mock(GeoServer.class); private final UpdateSequence updateSequence = mock(UpdateSequence.class); - private ApplicationContextRunner runner = - new ApplicationContextRunner() - .withBean(ServiceMatcher.class, () -> mockServiceMatcher) - .withBean(BusBridge.class, () -> mockBusBridge) - .withBean(UpdateSequence.class, () -> updateSequence) - .withBean("rawCatalog", Catalog.class, () -> mockCatalog) - .withBean("Geoserver", GeoServer.class, () -> mockGeoserver) - .withConfiguration( - AutoConfigurations.of( - BusAutoConfiguration.class, - GeoServerBusIntegrationAutoConfiguration.class)); + private ApplicationContextRunner runner = new ApplicationContextRunner() + .withBean(ServiceMatcher.class, () -> mockServiceMatcher) + .withBean(BusBridge.class, () -> mockBusBridge) + .withBean(UpdateSequence.class, () -> updateSequence) + .withBean("rawCatalog", Catalog.class, () -> mockCatalog) + .withBean("Geoserver", GeoServer.class, () -> mockGeoserver) + .withConfiguration( + AutoConfigurations.of(BusAutoConfiguration.class, GeoServerBusIntegrationAutoConfiguration.class)); @Test void enabledByDefault() { @@ -65,25 +62,23 @@ void conditionalOnCatalogEvents() { private void assertEnabled(ApplicationContextRunner runner) { - runner.run( - context -> { - assertThat(context) - .hasNotFailed() - .hasSingleBean(GeoServerCatalogModule.class) - .hasSingleBean(GeoServerConfigModule.class) - .hasSingleBean(RemoteGeoServerEventBridge.class); - }); + runner.run(context -> { + assertThat(context) + .hasNotFailed() + .hasSingleBean(GeoServerCatalogModule.class) + .hasSingleBean(GeoServerConfigModule.class) + .hasSingleBean(RemoteGeoServerEventBridge.class); + }); } private void assertDisabled(ApplicationContextRunner runner) { - runner.run( - context -> { - assertThat(context) - .hasNotFailed() - .doesNotHaveBean(GeoServerCatalogModule.class) - .doesNotHaveBean(GeoServerConfigModule.class) - .doesNotHaveBean(RemoteGeoServerEventBridge.class); - }); + runner.run(context -> { + assertThat(context) + .hasNotFailed() + .doesNotHaveBean(GeoServerCatalogModule.class) + .doesNotHaveBean(GeoServerConfigModule.class) + .doesNotHaveBean(RemoteGeoServerEventBridge.class); + }); } } diff --git a/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/BusAmqpIntegrationTests.java b/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/BusAmqpIntegrationTests.java index 4f78075aa..72932a59c 100644 --- a/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/BusAmqpIntegrationTests.java +++ b/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/BusAmqpIntegrationTests.java @@ -20,11 +20,14 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; +import java.lang.reflect.Proxy; +import java.util.List; +import java.util.function.Consumer; +import java.util.function.Supplier; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.NonNull; import lombok.experimental.Accessors; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.CatalogTestData; @@ -72,11 +75,6 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import java.lang.reflect.Proxy; -import java.util.List; -import java.util.function.Consumer; -import java.util.function.Supplier; - @SpringBootTest( webEnvironment = RANDOM_PORT, classes = {TestConfigurationAutoConfiguration.class, BusEventCollector.class}, @@ -93,8 +91,7 @@ public abstract class BusAmqpIntegrationTests { @Container - private static final RabbitMQContainer rabbitMQContainer = - new RabbitMQContainer("rabbitmq:3.13-management"); + private static final RabbitMQContainer rabbitMQContainer = new RabbitMQContainer("rabbitmq:3.13-management"); protected static ConfigurableApplicationContext remoteAppContext; private @Autowired ConfigurableApplicationContext localAppContext; @@ -115,16 +112,15 @@ static void properties(DynamicPropertyRegistry registry) { @BeforeAll static void setUpRemoteApplicationContext() { - remoteAppContext = - new SpringApplicationBuilder( - TestConfigurationAutoConfiguration.class, BusEventCollector.class) - .properties( - "server.port=0", - "spring.rabbitmq.host=" + rabbitMQContainer.getHost(), - "spring.rabbitmq.port=" + rabbitMQContainer.getAmqpPort(), - "spring.cloud.bus.id=app:2", - "spring.autoconfigure.exclude=org.springframework.cloud.stream.test.binder.TestSupportBinderAutoConfiguration") - .run(); + remoteAppContext = new SpringApplicationBuilder( + TestConfigurationAutoConfiguration.class, BusEventCollector.class) + .properties( + "server.port=0", + "spring.rabbitmq.host=" + rabbitMQContainer.getHost(), + "spring.rabbitmq.port=" + rabbitMQContainer.getAmqpPort(), + "spring.cloud.bus.id=app:2", + "spring.autoconfigure.exclude=org.springframework.cloud.stream.test.binder.TestSupportBinderAutoConfiguration") + .run(); } @AfterAll @@ -141,8 +137,8 @@ protected void setupClean() { Catalog remoteCatalog = remoteAppContext.getBean("rawCatalog", Catalog.class); GeoServer remoteGeoserver = remoteAppContext.getBean(GeoServer.class); - CatalogTestData remoteTestData = - CatalogTestData.empty(() -> remoteCatalog, () -> remoteGeoserver).initialize(); + CatalogTestData remoteTestData = CatalogTestData.empty(() -> remoteCatalog, () -> remoteGeoserver) + .initialize(); remoteTestData.initCatalog(true).initConfig(true).initialize(); } @@ -287,13 +283,11 @@ protected Class resolveInfoInterface(T info) { return type; } - protected RemoteGeoServerEvent testRemoteCatalogInfoAddEvent( - CatalogInfo info) { + protected RemoteGeoServerEvent testRemoteCatalogInfoAddEvent(CatalogInfo info) { return testRemoteAddEvent(info, catalog::add, CatalogInfoAdded.class); } - protected RemoteGeoServerEvent testRemoteCatalogInfoAddEvent( - T info, Consumer addOp) { + protected RemoteGeoServerEvent testRemoteCatalogInfoAddEvent(T info, Consumer addOp) { return testRemoteAddEvent(info, addOp, CatalogInfoAdded.class); } @@ -315,8 +309,7 @@ protected RemoteGeoServerEvent testRemoteAddEvent( // ok, that's the event published to the local application context, and which // spring-cloud-bus took care of not re-publishing. Let's capture the actual out-bound // message that traveled through the bus channel to the second application - RemoteGeoServerEvent remoteRemoteEvent = - eventsCaptor.remote().expectOne(eventType, infoType); + RemoteGeoServerEvent remoteRemoteEvent = eventsCaptor.remote().expectOne(eventType, infoType); assertThat(remoteRemoteEvent.getEvent().isRemote()).isTrue(); assertThat(remoteRemoteEvent.getEvent().isLocal()).isFalse(); assertRemoteEvent(info, remoteRemoteEvent); @@ -414,9 +407,7 @@ private void assertCatalogSet(Info info, Supplier accessor) { protected void assertNotAProxy(Info info, Class expected) { assertThat(ProxyUtils.isResolvingProxy(info)) - .as( - "Expected %s, got ResolvingProxy %s" - .formatted(expected.getSimpleName(), info.getId())) + .as("Expected %s, got ResolvingProxy %s".formatted(expected.getSimpleName(), info.getId())) .isFalse(); } diff --git a/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/BusEventCollector.java b/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/BusEventCollector.java index 7c71d403c..d22dba1b0 100644 --- a/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/BusEventCollector.java +++ b/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/BusEventCollector.java @@ -4,14 +4,20 @@ */ package org.geoserver.cloud.event.bus; +import static java.util.function.Predicate.not; import static org.assertj.core.api.Assertions.assertThat; import static org.testcontainers.shaded.org.awaitility.Awaitility.*; -import static java.util.function.Predicate.not; - +import java.time.Duration; +import java.util.List; +import java.util.Optional; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.function.Predicate; +import java.util.function.Supplier; +import java.util.stream.Stream; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.event.GeoServerEvent; import org.geoserver.cloud.event.info.ConfigInfoType; import org.geoserver.cloud.event.info.InfoEvent; @@ -21,15 +27,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.event.EventListener; -import java.time.Duration; -import java.util.List; -import java.util.Optional; -import java.util.concurrent.BlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.function.Predicate; -import java.util.function.Supplier; -import java.util.stream.Stream; - @Configuration @Slf4j public class BusEventCollector { @@ -51,11 +48,7 @@ public void onApplicationEvent(RemoteGeoServerEvent busEvent) { log.info("{}: captured event {}", busId, busEvent); events.add(busEvent); } else { - log.debug( - "{}: ignoring non {} event {}", - busId, - eventType.getSimpleName(), - payloadEvent); + log.debug("{}: ignoring non {} event {}", busId, eventType.getSimpleName(), payloadEvent); } } else { log.debug("{}: capturing is off, ignoring {}", busId, busEvent); @@ -76,35 +69,26 @@ public RemoteGeoServerEvent expectOne(Class payloadType return expectOne(payloadType, x -> true); } - public RemoteGeoServerEvent expectOne( - Class payloadType, ConfigInfoType infoType) { + public RemoteGeoServerEvent expectOne(Class payloadType, ConfigInfoType infoType) { return expectOne(payloadType, c -> infoType.equals(c.getObjectType())); } - public RemoteGeoServerEvent expectOne( - Class payloadType, Predicate filter) { + public RemoteGeoServerEvent expectOne(Class payloadType, Predicate filter) { - List matches = - await().atMost(Duration.ofSeconds(10)) // - .until(() -> allOf(payloadType, filter), not(List::isEmpty)); + List matches = await().atMost(Duration.ofSeconds(10)) // + .until(() -> allOf(payloadType, filter), not(List::isEmpty)); - Supplier message = - () -> - "expected 1, got %d events of type %s : %s" - .formatted(matches.size(), payloadType.getSimpleName(), matches); + Supplier message = () -> "expected 1, got %d events of type %s : %s" + .formatted(matches.size(), payloadType.getSimpleName(), matches); assertThat(matches.size()).as(message).isOne(); return matches.get(0); } - public RemoteGeoServerEvent expectOneLifecycleEvent( - Class payloadType) { + public RemoteGeoServerEvent expectOneLifecycleEvent(Class payloadType) { - List matches = - await().atMost(Duration.ofSeconds(10)) // - .until( - () -> allOfLifecycle(payloadType, filter -> true), - not(List::isEmpty)); + List matches = await().atMost(Duration.ofSeconds(10)) // + .until(() -> allOfLifecycle(payloadType, filter -> true), not(List::isEmpty)); assertThat(matches.size()).isOne(); @@ -116,9 +100,7 @@ public List allOf( Class payloadEventType, Predicate eventFilter) { return capturedEvents(payloadEventType) - .filter( - remoteEvent -> - eventFilter.test(payloadEventType.cast(remoteEvent.getEvent()))) + .filter(remoteEvent -> eventFilter.test(payloadEventType.cast(remoteEvent.getEvent()))) .toList(); } @@ -126,9 +108,7 @@ public List allOfLifecycle( Class payloadEventType, Predicate eventFilter) { return capturedLifecycleEvents(payloadEventType) - .filter( - remoteEvent -> - eventFilter.test(payloadEventType.cast(remoteEvent.getEvent()))) + .filter(remoteEvent -> eventFilter.test(payloadEventType.cast(remoteEvent.getEvent()))) .toList(); } @@ -140,13 +120,11 @@ public Optional first(Class return capturedEvents(payloadType).findFirst(); } - private Stream capturedEvents( - Class payloadType) { + private Stream capturedEvents(Class payloadType) { return capturedEvents().filter(remote -> payloadType.isInstance(remote.getEvent())); } - private Stream capturedLifecycleEvents( - Class payloadType) { + private Stream capturedLifecycleEvents(Class payloadType) { return capturedEvents().filter(remote -> payloadType.isInstance(remote.getEvent())); } diff --git a/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/CatalogRemoteApplicationEventsIT.java b/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/CatalogRemoteApplicationEventsIT.java index cb750710f..e53d5b5e8 100644 --- a/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/CatalogRemoteApplicationEventsIT.java +++ b/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/CatalogRemoteApplicationEventsIT.java @@ -9,6 +9,12 @@ import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.fail; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Predicate; +import java.util.stream.IntStream; import org.geoserver.catalog.AttributeTypeInfo; import org.geoserver.catalog.AttributionInfo; import org.geoserver.catalog.Catalog; @@ -47,13 +53,6 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.function.Consumer; -import java.util.function.Predicate; -import java.util.stream.IntStream; - class CatalogRemoteApplicationEventsIT extends BusAmqpIntegrationTests { @Test @@ -62,11 +61,9 @@ void testCatalogSetDefaultWorkspace() { catalog.add(testData.workspaceC); final Class eventType = DefaultWorkspaceSet.class; { - Patch expected = - new PropertyDiffTestSupport() - .createTestDiff( - "defaultWorkspace", testData.workspaceA, testData.workspaceC) - .toPatch(); + Patch expected = new PropertyDiffTestSupport() + .createTestDiff("defaultWorkspace", testData.workspaceA, testData.workspaceC) + .toPatch(); Consumer modifier = c -> c.setDefaultWorkspace(testData.workspaceC); Predicate filter = @@ -75,10 +72,9 @@ void testCatalogSetDefaultWorkspace() { testCatalogModifiedEvent(catalog, modifier, expected, eventType, filter); } { - Patch expected = - new PropertyDiffTestSupport() - .createTestDiff("defaultWorkspace", testData.workspaceC, null) - .toPatch(); + Patch expected = new PropertyDiffTestSupport() + .createTestDiff("defaultWorkspace", testData.workspaceC, null) + .toPatch(); Consumer modifier = c -> c.setDefaultWorkspace(null); Predicate filter = e -> e.getNewWorkspaceId() == null; @@ -97,19 +93,16 @@ void testCatalogSetDefaultNamespace() { Consumer modifier = c -> c.setDefaultNamespace(testData.namespaceB); Predicate filter = e -> testData.namespaceB.getId().equals(e.getNewNamespaceId()); - Patch expected = - new PropertyDiffTestSupport() - .createTestDiff( - "defaultNamespace", testData.namespaceA, testData.namespaceB) - .toPatch(); + Patch expected = new PropertyDiffTestSupport() + .createTestDiff("defaultNamespace", testData.namespaceA, testData.namespaceB) + .toPatch(); testCatalogModifiedEvent(catalog, modifier, expected, eventType, filter); } { - Patch expected = - new PropertyDiffTestSupport() - .createTestDiff("defaultNamespace", testData.namespaceA, null) - .toPatch(); + Patch expected = new PropertyDiffTestSupport() + .createTestDiff("defaultNamespace", testData.namespaceA, null) + .toPatch(); Consumer modifier = c -> c.setDefaultNamespace(null); Predicate filter = e -> null == e.getNewNamespaceId(); @@ -129,31 +122,26 @@ void testCatalogSetDefaultDataStoreByWorkspace() { final Class eventType = DefaultDataStoreSet.class; { - Patch expected = - new PropertyDiffTestSupport() - .createTestDiff("defaultDataStore", null, dataStore) - .toPatch(); + Patch expected = new PropertyDiffTestSupport() + .createTestDiff("defaultDataStore", null, dataStore) + .toPatch(); - Predicate filter = - e -> dataStore.getId().equals(e.getDefaultDataStoreId()); + Predicate filter = e -> dataStore.getId().equals(e.getDefaultDataStoreId()); DefaultDataStoreSet event = - testCatalogModifiedEvent( - catalog, c -> c.add(dataStore), expected, eventType, filter); + testCatalogModifiedEvent(catalog, c -> c.add(dataStore), expected, eventType, filter); assertThat(event.getWorkspaceId()).isEqualTo(workspace.getId()); assertThat(event.getDefaultDataStoreId()).isEqualTo(dataStore.getId()); } { - Patch expected = - new PropertyDiffTestSupport() - .createTestDiff("defaultDataStore", dataStore, null) - .toPatch(); + Patch expected = new PropertyDiffTestSupport() + .createTestDiff("defaultDataStore", dataStore, null) + .toPatch(); Predicate filter = e -> null == e.getDefaultDataStoreId(); DefaultDataStoreSet event = - testCatalogModifiedEvent( - catalog, c -> c.remove(dataStore), expected, eventType, filter); + testCatalogModifiedEvent(catalog, c -> c.remove(dataStore), expected, eventType, filter); assertThat(event.getWorkspaceId()).isEqualTo(workspace.getId()); assertThat(event.getDefaultDataStoreId()).isNull(); @@ -324,13 +312,12 @@ void testModifyEventsCoverageStore_COG() { cogSettings.setRangeReaderSettings(RangeReaderType.S3); cogSettings.setUsername("user"); - Patch patch = - testCatalogInfoModifyEventNoEquals( - store, - cs -> { - cs.getMetadata().put("cogSettings", cogSettings); - }, - catalog::save); + Patch patch = testCatalogInfoModifyEventNoEquals( + store, + cs -> { + cs.getMetadata().put("cogSettings", cogSettings); + }, + catalog::save); store = catalog.getCoverageStoreByName(testData.workspaceA.getName(), store.getName()); assertNotNull(store); @@ -379,39 +366,33 @@ void testModifyEventsFeatureType() throws SchemaException { setupClean(); SimpleFeatureType type = DataUtilities.createType("test", "name:String,location:Point"); - List attributes = - new CatalogBuilder(catalog).getAttributes(type, testData.featureTypeA); + List attributes = new CatalogBuilder(catalog).getAttributes(type, testData.featureTypeA); // don't run equals - Patch patch = - testCatalogInfoModifyEventNoEquals( - testData.featureTypeA, - ft -> { - ft.getMetadata().put("md-key", "md-value"); - ft.getMetadata().put("md-int-key", 1000); - ft.setNamespace(testData.namespaceC); - ft.getAttributes().addAll(attributes); - }, - catalog::save); + Patch patch = testCatalogInfoModifyEventNoEquals( + testData.featureTypeA, + ft -> { + ft.getMetadata().put("md-key", "md-value"); + ft.getMetadata().put("md-int-key", 1000); + ft.setNamespace(testData.namespaceC); + ft.getAttributes().addAll(attributes); + }, + catalog::save); Property atts = patch.get("attributes").orElseThrow(); @SuppressWarnings("unchecked") List decodedAtts = (List) atts.getValue(); assertEquals(attributes.size(), decodedAtts.size()); - IntStream.range(0, attributes.size()) - .forEach( - i -> { - AttributeTypeInfo decoded = decodedAtts.get(i); - AttributeTypeInfo orig = attributes.get(i); - assertThat(decoded.equalsIngnoreFeatureType(orig)); - assertNotNull(decoded.getFeatureType()); - FeatureTypeInfo expected = - ModificationProxy.unwrap(orig.getFeatureType()); - FeatureTypeInfo actual = - ModificationProxy.unwrap(decoded.getFeatureType()); - assertEquals(expected.getId(), actual.getId()); - assertEquals(expected.getName(), actual.getName()); - }); + IntStream.range(0, attributes.size()).forEach(i -> { + AttributeTypeInfo decoded = decodedAtts.get(i); + AttributeTypeInfo orig = attributes.get(i); + assertThat(decoded.equalsIngnoreFeatureType(orig)); + assertNotNull(decoded.getFeatureType()); + FeatureTypeInfo expected = ModificationProxy.unwrap(orig.getFeatureType()); + FeatureTypeInfo actual = ModificationProxy.unwrap(decoded.getFeatureType()); + assertEquals(expected.getId(), actual.getId()); + assertEquals(expected.getName(), actual.getName()); + }); } @Disabled("implement") @@ -426,11 +407,9 @@ void testModifyEventsWMSLayer() throws Exception { WMSLayerInfo layer = testData.wmsLayerA; - ReferencedEnvelope bounds = - new ReferencedEnvelope(-180, -90, 0, 0, CRS.decode("EPSG:4326")); + ReferencedEnvelope bounds = new ReferencedEnvelope(-180, -90, 0, 0, CRS.decode("EPSG:4326")); - testCatalogInfoModifyEvent( - layer, l -> l.setDisabledServices(List.of("WMS", "WFS")), catalog::save); + testCatalogInfoModifyEvent(layer, l -> l.setDisabledServices(List.of("WMS", "WFS")), catalog::save); testCatalogInfoModifyEvent(layer, l -> l.setAbstract("modified"), catalog::save); testCatalogInfoModifyEvent(layer, l -> l.setNativeBoundingBox(bounds), catalog::save); @@ -450,11 +429,9 @@ void testModifyEventsWMTSLayer() throws Exception { WMTSLayerInfo layer = testData.wmtsLayerA; - ReferencedEnvelope bounds = - new ReferencedEnvelope(-180, -90, 0, 0, CRS.decode("EPSG:4326")); + ReferencedEnvelope bounds = new ReferencedEnvelope(-180, -90, 0, 0, CRS.decode("EPSG:4326")); - testCatalogInfoModifyEvent( - layer, l -> l.setDisabledServices(List.of("WMS", "WFS")), catalog::save); + testCatalogInfoModifyEvent(layer, l -> l.setDisabledServices(List.of("WMS", "WFS")), catalog::save); testCatalogInfoModifyEvent(layer, l -> l.setAbstract("modified"), catalog::save); testCatalogInfoModifyEvent(layer, l -> l.setNativeBoundingBox(bounds), catalog::save); @@ -484,9 +461,7 @@ void testModifyEventsLayer() { l.setDefaultWMSInterpolationMethod(WMSInterpolation.Bicubic); l.setInternationalTitle( - testData.faker() - .internationalString( - Locale.ENGLISH, "test", Locale.ITALIAN, "proba")); + testData.faker().internationalString(Locale.ENGLISH, "test", Locale.ITALIAN, "proba")); l.setType(PublishedType.REMOTE); }, @@ -527,11 +502,7 @@ void testRemoveEvents() { } private E testCatalogModifiedEvent( - Catalog catalog, - Consumer modifier, - Patch expected, - Class eventType, - Predicate filter) { + Catalog catalog, Consumer modifier, Patch expected, Class eventType, Predicate filter) { this.eventsCaptor.stop().clear().start(); diff --git a/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/ConfigRemoteApplicationEventsIT.java b/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/ConfigRemoteApplicationEventsIT.java index b8548dd9e..e46c0441e 100644 --- a/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/ConfigRemoteApplicationEventsIT.java +++ b/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/ConfigRemoteApplicationEventsIT.java @@ -8,6 +8,8 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; +import java.util.Locale; +import java.util.Map; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.plugin.Patch; import org.geoserver.cloud.event.config.GeoServerInfoModified; @@ -35,9 +37,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Locale; -import java.util.Map; - class ConfigRemoteApplicationEventsIT extends BusAmqpIntegrationTests { @Override @@ -121,22 +120,22 @@ void testConfigRemoteModifyEvents_GeoServerInfo() { coverageInfo.setCorePoolSize(10); coverageInfo.setQueueType(QueueType.UNBOUNDED); - Patch patch = - testRemoteModifyEvent( - global, - gs -> { - gs.setAdminUsername("administrador"); - gs.setAdminPassword("secret"); - gs.setCoverageAccess(coverageInfo); - gs.getSettings().setCharset("UTF-16"); - gs.getSettings().setProxyBaseUrl("http://test2.com"); - gs.getSettings().getContact().setContactEmail("john.doe@test.com"); - gs.getSettings().getContact().setAddressCity("Buenos Aires"); - }, - geoserver::save, - GeoServerInfoModified.class); - - SettingsInfo settings = (SettingsInfo) patch.get("settings").orElseThrow().getValue(); + Patch patch = testRemoteModifyEvent( + global, + gs -> { + gs.setAdminUsername("administrador"); + gs.setAdminPassword("secret"); + gs.setCoverageAccess(coverageInfo); + gs.getSettings().setCharset("UTF-16"); + gs.getSettings().setProxyBaseUrl("http://test2.com"); + gs.getSettings().getContact().setContactEmail("john.doe@test.com"); + gs.getSettings().getContact().setAddressCity("Buenos Aires"); + }, + geoserver::save, + GeoServerInfoModified.class); + + SettingsInfo settings = + (SettingsInfo) patch.get("settings").orElseThrow().getValue(); assertThat(settings.getContact()).isNotNull(); assertThat(settings.getCharset()).isEqualTo("UTF-16"); assertThat(settings.getProxyBaseUrl()).isEqualTo("http://test2.com"); @@ -160,17 +159,17 @@ void testConfigRemotetModifyEvents_GloabalSettingsInfo() { geoserver.setGlobal(global); // patch parsed from remote event - Patch patch = - testConfigInfoModifyEvent( - global, - g -> { - g.getSettings().setCharset("ISO-8869-1"); - g.getSettings().setProxyBaseUrl("http://test.com"); - g.getSettings().getContact().setContactEmail("john@doe.com"); - g.getSettings().getContact().setAddressCity("Rosario"); - }, - geoserver::save); - SettingsInfo newSettings = (SettingsInfo) patch.get("settings").orElseThrow().getValue(); + Patch patch = testConfigInfoModifyEvent( + global, + g -> { + g.getSettings().setCharset("ISO-8869-1"); + g.getSettings().setProxyBaseUrl("http://test.com"); + g.getSettings().getContact().setContactEmail("john@doe.com"); + g.getSettings().getContact().setAddressCity("Rosario"); + }, + geoserver::save); + SettingsInfo newSettings = + (SettingsInfo) patch.get("settings").orElseThrow().getValue(); assertThat(newSettings.getContact()).isNotNull(); assertThat(newSettings.getContact().getContactEmail()).isEqualTo("john@doe.com"); assertThat(newSettings.getContact().getAddressCity()).isEqualTo("Rosario"); @@ -215,8 +214,7 @@ void testConfigRemoteRemoveEvent_SettingsInfo() { settings.setWorkspace(testData.workspaceC); geoserver.add(settings); - SettingsRemoved event = - testRemoteRemoveEvent(settings, geoserver::remove, SettingsRemoved.class); + SettingsRemoved event = testRemoteRemoveEvent(settings, geoserver::remove, SettingsRemoved.class); assertEquals(testData.workspaceC.getId(), event.getWorkspaceId()); } @@ -227,8 +225,7 @@ void testConfigRemoveEvent_ServiceInfo() { geoserver.add(service); eventsCaptor.clear().start(); - ServiceRemoved event = - testRemoteRemoveEvent(service, geoserver::remove, ServiceRemoved.class); + ServiceRemoved event = testRemoteRemoveEvent(service, geoserver::remove, ServiceRemoved.class); assertThat(event.getWorkspaceId()).isNull(); } @@ -240,8 +237,7 @@ void testConfigRemoveEvent_ServiceInfo_Workspace() { geoserver.add(service); eventsCaptor.clear().start(); - ServiceRemoved event = - testRemoteRemoveEvent(service, geoserver::remove, ServiceRemoved.class); + ServiceRemoved event = testRemoteRemoveEvent(service, geoserver::remove, ServiceRemoved.class); assertThat(event.getWorkspaceId()).isEqualTo(testData.workspaceC.getId()); } @@ -255,11 +251,8 @@ void testGeoServerInfoMetadatamapWithCogSettings() { cogSettings.setRangeReaderSettings(RangeReaderType.S3); cogSettings.setUseCachingStream(true); - Patch patch = - testConfigInfoModifyEventNoEquals( - global, - gs -> gs.getMetadata().put("cogSettings", cogSettings), - geoserver::save); + Patch patch = testConfigInfoModifyEventNoEquals( + global, gs -> gs.getMetadata().put("cogSettings", cogSettings), geoserver::save); Map md = (Map) patch.get("metadata").orElseThrow().getValue(); CogSettings settings = (CogSettings) md.get("cogSettings"); diff --git a/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/LifecycleRemoteApplicationEventsIT.java b/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/LifecycleRemoteApplicationEventsIT.java index 2fe691964..b173dfc46 100644 --- a/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/LifecycleRemoteApplicationEventsIT.java +++ b/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/LifecycleRemoteApplicationEventsIT.java @@ -6,6 +6,7 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.util.function.Consumer; import org.geoserver.cloud.event.lifecycle.LifecycleEvent; import org.geoserver.cloud.event.lifecycle.ReloadEvent; import org.geoserver.cloud.event.lifecycle.ResetEvent; @@ -14,8 +15,6 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; -import java.util.function.Consumer; - class LifecycleRemoteApplicationEventsIT extends BusAmqpIntegrationTests { @BeforeAll @@ -27,7 +26,11 @@ static void handleGsExtensions() { @Test void testGeoServerHasExecutedReset() { - this.eventsCaptor.stop().clear().captureLifecycleEventsOf(LifecycleEvent.class).start(); + this.eventsCaptor + .stop() + .clear() + .captureLifecycleEventsOf(LifecycleEvent.class) + .start(); Consumer modifier = GeoServer::reset; modifier.accept(geoserver); @@ -39,16 +42,19 @@ void testGeoServerHasExecutedReset() { @Test void testGeoServerHasExecutedReload() { - this.eventsCaptor.stop().clear().captureLifecycleEventsOf(LifecycleEvent.class).start(); + this.eventsCaptor + .stop() + .clear() + .captureLifecycleEventsOf(LifecycleEvent.class) + .start(); - Consumer modifier = - geoServer -> { - try { - geoServer.reload(); - } catch (Exception e) { - throw new RuntimeException(e); - } - }; + Consumer modifier = geoServer -> { + try { + geoServer.reload(); + } catch (Exception e) { + throw new RuntimeException(e); + } + }; modifier.accept(geoserver); eventsCaptor.local().expectOneLifecycleEvent(ReloadEvent.class); diff --git a/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/RemoteGeoServerEventsConfigurationTest.java b/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/RemoteGeoServerEventsConfigurationTest.java index 56a0c006a..179e56d69 100644 --- a/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/RemoteGeoServerEventsConfigurationTest.java +++ b/src/catalog/event-bus/src/test/java/org/geoserver/cloud/event/bus/RemoteGeoServerEventsConfigurationTest.java @@ -31,26 +31,23 @@ class RemoteGeoServerEventsConfigurationTest { private final GeoServer mockGeoserver = mock(GeoServer.class); private final UpdateSequence updateSequence = mock(UpdateSequence.class); - private ApplicationContextRunner runner = - new ApplicationContextRunner() - .withBean(ServiceMatcher.class, () -> mockServiceMatcher) - .withBean(BusBridge.class, () -> mockBusBridge) - .withBean(UpdateSequence.class, () -> updateSequence) - .withBean("rawCatalog", Catalog.class, () -> mockCatalog) - .withBean("Geoserver", GeoServer.class, () -> mockGeoserver) - .withConfiguration(AutoConfigurations.of(BusAutoConfiguration.class)) - .withConfiguration( - UserConfigurations.of(RemoteGeoServerEventsConfiguration.class)); + private ApplicationContextRunner runner = new ApplicationContextRunner() + .withBean(ServiceMatcher.class, () -> mockServiceMatcher) + .withBean(BusBridge.class, () -> mockBusBridge) + .withBean(UpdateSequence.class, () -> updateSequence) + .withBean("rawCatalog", Catalog.class, () -> mockCatalog) + .withBean("Geoserver", GeoServer.class, () -> mockGeoserver) + .withConfiguration(AutoConfigurations.of(BusAutoConfiguration.class)) + .withConfiguration(UserConfigurations.of(RemoteGeoServerEventsConfiguration.class)); @Test void enabledByDefault() { - runner.run( - context -> { - assertThat(context).hasSingleBean(GeoServerCatalogModule.class); - assertThat(context).hasSingleBean(GeoServerConfigModule.class); - assertThat(context).hasSingleBean(InfoEventResolver.class); - assertThat(context).hasSingleBean(RemoteGeoServerEventMapper.class); - assertThat(context).hasSingleBean(RemoteGeoServerEventBridge.class); - }); + runner.run(context -> { + assertThat(context).hasSingleBean(GeoServerCatalogModule.class); + assertThat(context).hasSingleBean(GeoServerConfigModule.class); + assertThat(context).hasSingleBean(InfoEventResolver.class); + assertThat(context).hasSingleBean(RemoteGeoServerEventMapper.class); + assertThat(context).hasSingleBean(RemoteGeoServerEventBridge.class); + }); } } diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/autoconfigure/catalog/event/ConditionalOnCatalogEvents.java b/src/catalog/events/src/main/java/org/geoserver/cloud/autoconfigure/catalog/event/ConditionalOnCatalogEvents.java index d18c8bcc5..ea8700988 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/autoconfigure/catalog/event/ConditionalOnCatalogEvents.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/autoconfigure/catalog/event/ConditionalOnCatalogEvents.java @@ -4,19 +4,15 @@ */ package org.geoserver.cloud.autoconfigure.catalog.event; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) @Documented -@ConditionalOnProperty( - value = "geoserver.catalog.events.enabled", - havingValue = "true", - matchIfMissing = true) +@ConditionalOnProperty(value = "geoserver.catalog.events.enabled", havingValue = "true", matchIfMissing = true) public @interface ConditionalOnCatalogEvents {} diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/autoconfigure/catalog/event/UpdateSequenceController.java b/src/catalog/events/src/main/java/org/geoserver/cloud/autoconfigure/catalog/event/UpdateSequenceController.java index c90d907cb..6631efa8d 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/autoconfigure/catalog/event/UpdateSequenceController.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/autoconfigure/catalog/event/UpdateSequenceController.java @@ -4,11 +4,11 @@ */ package org.geoserver.cloud.autoconfigure.catalog.event; +import javax.annotation.security.RolesAllowed; import lombok.Data; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.experimental.Accessors; - import org.geoserver.cloud.event.UpdateSequenceEvent; import org.geoserver.config.GeoServer; import org.geoserver.platform.config.UpdateSequence; @@ -18,8 +18,6 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; -import javax.annotation.security.RolesAllowed; - /** * @since 1.0 */ diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/config/catalog/events/CatalogApplicationEventPublisher.java b/src/catalog/events/src/main/java/org/geoserver/cloud/config/catalog/events/CatalogApplicationEventPublisher.java index 3ba36015b..a9f516692 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/config/catalog/events/CatalogApplicationEventPublisher.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/config/catalog/events/CatalogApplicationEventPublisher.java @@ -5,10 +5,19 @@ package org.geoserver.cloud.config.catalog.events; import com.google.common.annotations.VisibleForTesting; - +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.UUID; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.function.Consumer; +import java.util.function.Supplier; +import javax.annotation.Nullable; +import javax.annotation.PostConstruct; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogException; import org.geoserver.catalog.Info; @@ -39,19 +48,6 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEvent; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Consumer; -import java.util.function.Supplier; - -import javax.annotation.Nullable; -import javax.annotation.PostConstruct; - /** * Adapts the listener pattern used by {@link Catalog#addListener Catalog} and {@link * GeoServer#addListener GeoServer} used to notify configuration events, as regular spring {@link @@ -203,10 +199,7 @@ private void publish(InfoEvent event) { } private void preparePreModify( - @NonNull String id, - List propertyNames, - List oldValues, - List newValues) { + @NonNull String id, List propertyNames, List oldValues, List newValues) { PropertyDiff diff = PropertyDiff.valueOf(propertyNames, oldValues, newValues); Patch patch = diff.clean().toPatch(); @@ -220,10 +213,7 @@ private void publishPostModify(@NonNull String id, @NonNull Info info) { @Override public void handleGlobalChange( - GeoServerInfo global, - List propertyNames, - List oldValues, - List newValues) { + GeoServerInfo global, List propertyNames, List oldValues, List newValues) { String id = InfoEvent.resolveId(global); preparePreModify(id, propertyNames, oldValues, newValues); } @@ -242,8 +232,7 @@ public void handlePostGlobalChange(GeoServerInfo global) { publish(ConfigInfoAdded.createLocal(incrementSequence(), global)); } else { // already called pop() - ConfigInfoModified event = - ConfigInfoModified.createLocal(incrementSequence(), global, patch); + ConfigInfoModified event = ConfigInfoModified.createLocal(incrementSequence(), global, patch); publish(event); } } @@ -255,10 +244,7 @@ public void handleSettingsAdded(SettingsInfo settings) { @Override public void handleSettingsModified( - SettingsInfo settings, - List propertyNames, - List oldValues, - List newValues) { + SettingsInfo settings, List propertyNames, List oldValues, List newValues) { if (settings.getId() == null) { // shouldn't happen, but can happen. GeoServerImpl doesn't check for it OwsUtils.set(settings, "id", UUID.randomUUID().toString()); @@ -279,10 +265,7 @@ public void handleSettingsRemoved(SettingsInfo settings) { @Override public void handleLoggingChange( - LoggingInfo logging, - List propertyNames, - List oldValues, - List newValues) { + LoggingInfo logging, List propertyNames, List oldValues, List newValues) { // LoggingInfo has no-id preparePreModify(InfoEvent.resolveId(logging), propertyNames, oldValues, newValues); } @@ -303,10 +286,7 @@ public void handlePostLoggingChange(LoggingInfo logging) { @Override public void handleServiceChange( - ServiceInfo service, - List propertyNames, - List oldValues, - List newValues) { + ServiceInfo service, List propertyNames, List oldValues, List newValues) { preparePreModify(service.getId(), propertyNames, oldValues, newValues); } diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/config/catalog/events/CatalogApplicationEventsConfiguration.java b/src/catalog/events/src/main/java/org/geoserver/cloud/config/catalog/events/CatalogApplicationEventsConfiguration.java index 604431f7e..d7f5c7717 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/config/catalog/events/CatalogApplicationEventsConfiguration.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/config/catalog/events/CatalogApplicationEventsConfiguration.java @@ -4,6 +4,8 @@ */ package org.geoserver.cloud.config.catalog.events; +import java.util.function.Consumer; +import java.util.function.Supplier; import org.geoserver.catalog.Catalog; import org.geoserver.cloud.event.info.InfoEvent; import org.geoserver.cloud.event.lifecycle.LifecycleEvent; @@ -14,9 +16,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import java.util.function.Consumer; -import java.util.function.Supplier; - @Configuration(proxyBeanMethods = false) public class CatalogApplicationEventsConfiguration { @@ -30,8 +29,7 @@ CatalogApplicationEventPublisher localApplicationEventPublisher( // Consumer publisher = localContextPublisher::publishEvent; Supplier updateSequenceIncrementor = updateSequence::nextValue; - return new CatalogApplicationEventPublisher( - publisher, catalog, geoServer, updateSequenceIncrementor); + return new CatalogApplicationEventPublisher(publisher, catalog, geoServer, updateSequenceIncrementor); } @Bean diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/config/catalog/events/GeoServerLifecycleEventPublisher.java b/src/catalog/events/src/main/java/org/geoserver/cloud/config/catalog/events/GeoServerLifecycleEventPublisher.java index 838fcce28..847300564 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/config/catalog/events/GeoServerLifecycleEventPublisher.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/config/catalog/events/GeoServerLifecycleEventPublisher.java @@ -4,10 +4,10 @@ */ package org.geoserver.cloud.config.catalog.events; +import java.util.function.Consumer; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.Catalog; import org.geoserver.cloud.event.lifecycle.LifecycleEvent; import org.geoserver.cloud.event.lifecycle.ReloadEvent; @@ -17,8 +17,6 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEvent; -import java.util.function.Consumer; - /** * Implements the {@link GeoServerLifecycleHandler} interface to notify lifecycle events * (reload/reset) as regular spring {@link ApplicationEvent application events}, and publishes them diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/GeoServerEvent.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/GeoServerEvent.java index 27f5390be..70192b600 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/GeoServerEvent.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/GeoServerEvent.java @@ -7,11 +7,11 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; - +import java.io.Serializable; +import java.util.Optional; import lombok.Getter; import lombok.NonNull; import lombok.Setter; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.Info; import org.geoserver.cloud.event.info.ConfigInfoType; @@ -20,20 +20,16 @@ import org.geoserver.config.LoggingInfo; import org.springframework.core.style.ToStringCreator; -import java.io.Serializable; -import java.util.Optional; - @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) -@JsonSubTypes({ - @JsonSubTypes.Type(value = UpdateSequenceEvent.class), - @JsonSubTypes.Type(value = LifecycleEvent.class) -}) +@JsonSubTypes({@JsonSubTypes.Type(value = UpdateSequenceEvent.class), @JsonSubTypes.Type(value = LifecycleEvent.class)}) @SuppressWarnings("serial") public abstract class GeoServerEvent implements Serializable { - @JsonIgnore private @Setter boolean remote; + @JsonIgnore + private @Setter boolean remote; - @JsonIgnore private @Setter @Getter String origin; + @JsonIgnore + private @Setter @Getter String origin; /** System time when the event happened. */ private @Getter long timestamp; diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/UpdateSequenceEvent.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/UpdateSequenceEvent.java index b39d3adba..a2d259305 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/UpdateSequenceEvent.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/UpdateSequenceEvent.java @@ -7,9 +7,7 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.Getter; - import org.geoserver.cloud.event.info.InfoEvent; import org.geoserver.cloud.event.security.SecurityConfigChanged; import org.geoserver.config.GeoServerInfo; @@ -18,10 +16,7 @@ import org.springframework.security.core.context.SecurityContextHolder; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) -@JsonSubTypes({ - @JsonSubTypes.Type(value = InfoEvent.class), - @JsonSubTypes.Type(value = SecurityConfigChanged.class) -}) +@JsonSubTypes({@JsonSubTypes.Type(value = InfoEvent.class), @JsonSubTypes.Type(value = SecurityConfigChanged.class)}) @JsonTypeName("UpdateSequence") @SuppressWarnings("serial") public class UpdateSequenceEvent extends GeoServerEvent implements Comparable { @@ -64,7 +59,6 @@ public int compareTo(UpdateSequenceEvent o) { public String toShortString() { String originService = getOrigin(); String type = getClass().getSimpleName(); - return "%s[origin: %s, updateSequence: %s]" - .formatted(type, originService, getUpdateSequence()); + return "%s[origin: %s, updateSequence: %s]".formatted(type, originService, getUpdateSequence()); } } diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/CatalogInfoAdded.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/CatalogInfoAdded.java index 1ffcbb77d..381ae40bc 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/CatalogInfoAdded.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/CatalogInfoAdded.java @@ -6,15 +6,12 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - +import java.util.Optional; import lombok.NonNull; - import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.event.CatalogAddEvent; import org.geoserver.cloud.event.info.InfoAdded; -import java.util.Optional; - @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonTypeName("CatalogInfoAdded") @SuppressWarnings("serial") @@ -32,8 +29,7 @@ public Optional remote() { return super.remote(); } - public static CatalogInfoAdded createLocal( - long updateSequence, @NonNull CatalogAddEvent event) { + public static CatalogInfoAdded createLocal(long updateSequence, @NonNull CatalogAddEvent event) { return createLocal(updateSequence, event.getSource()); } diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/CatalogInfoModified.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/CatalogInfoModified.java index 55d5f85a5..8dbb113bd 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/CatalogInfoModified.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/CatalogInfoModified.java @@ -8,10 +8,10 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.google.common.annotations.VisibleForTesting; - +import java.util.Objects; +import java.util.Optional; import lombok.Getter; import lombok.NonNull; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.NamespaceInfo; @@ -25,9 +25,6 @@ import org.geoserver.cloud.event.info.ConfigInfoType; import org.geoserver.cloud.event.info.InfoModified; -import java.util.Objects; -import java.util.Optional; - @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonTypeName("CatalogInfoModified") @JsonSubTypes({ @@ -63,12 +60,10 @@ public Optional remote() { } @VisibleForTesting - public static CatalogInfoModified createLocal( - long updateSequence, @NonNull CatalogInfo modProxy) { + public static CatalogInfoModified createLocal(long updateSequence, @NonNull CatalogInfo modProxy) { ModificationProxy proxy = - Objects.requireNonNull( - ModificationProxy.handler(modProxy), "Argument is not a ModificationProxy"); + Objects.requireNonNull(ModificationProxy.handler(modProxy), "Argument is not a ModificationProxy"); PropertyDiff diff = PropertyDiff.valueOf(proxy); Patch patch = diff.toPatch(); @@ -93,16 +88,11 @@ public static CatalogInfoModified createLocal( return new CatalogInfoModified(updateSequence, id, prefixedName, oldName, type, patch); } - public static CatalogInfoModified createLocal( - long updateSequence, @NonNull CatalogPostModifyEvent event) { + public static CatalogInfoModified createLocal(long updateSequence, @NonNull CatalogPostModifyEvent event) { final CatalogInfo info = event.getSource(); - PropertyDiff diff = - PropertyDiff.valueOf( - event.getPropertyNames(), - event.getOldValues(), - event.getNewValues()) - .clean(); + PropertyDiff diff = PropertyDiff.valueOf(event.getPropertyNames(), event.getOldValues(), event.getNewValues()) + .clean(); final Patch patch = diff.toPatch(); if (!patch.isEmpty() && info instanceof Catalog) { diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/CatalogInfoRemoved.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/CatalogInfoRemoved.java index b0cb28e6c..21d30918e 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/CatalogInfoRemoved.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/CatalogInfoRemoved.java @@ -6,15 +6,12 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - +import java.util.Objects; +import java.util.Optional; import lombok.NonNull; - import org.geoserver.catalog.CatalogInfo; import org.geoserver.cloud.event.info.InfoRemoved; -import java.util.Objects; -import java.util.Optional; - @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonTypeName("CatalogInfoRemoved") @SuppressWarnings("serial") diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/DefaultDataStoreSet.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/DefaultDataStoreSet.java index feb481641..efab84495 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/DefaultDataStoreSet.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/DefaultDataStoreSet.java @@ -6,11 +6,10 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - +import java.util.Objects; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; - import org.geoserver.catalog.DataStoreInfo; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.event.CatalogPostModifyEvent; @@ -22,8 +21,6 @@ import org.springframework.core.style.ToStringCreator; import org.springframework.lang.Nullable; -import java.util.Objects; - @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonTypeName("DefaultDataStoreSet") @EqualsAndHashCode(callSuper = true) @@ -54,24 +51,15 @@ protected DefaultDataStoreSet() {} } protected @Override ToStringCreator toStringBuilder() { - return super.toStringBuilder() - .append("workspace", getWorkspaceId()) - .append("store", getDefaultDataStoreId()); + return super.toStringBuilder().append("workspace", getWorkspaceId()).append("store", getDefaultDataStoreId()); } - public static DefaultDataStoreSet createLocal( - long updateSequence, @NonNull CatalogPostModifyEvent event) { - - PropertyDiff diff = - PropertyDiff.valueOf( - event.getPropertyNames(), event.getOldValues(), event.getNewValues()); - - final Change change = - diff.get("defaultDataStore") - .orElseThrow( - () -> - new IllegalArgumentException( - "defaultDataStore is not in the change list")); + public static DefaultDataStoreSet createLocal(long updateSequence, @NonNull CatalogPostModifyEvent event) { + + PropertyDiff diff = PropertyDiff.valueOf(event.getPropertyNames(), event.getOldValues(), event.getNewValues()); + + final Change change = diff.get("defaultDataStore") + .orElseThrow(() -> new IllegalArgumentException("defaultDataStore is not in the change list")); final DataStoreInfo newStore = (DataStoreInfo) change.getNewValue(); final String newDefaultStoreId = resolveNullableId(newStore); diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/DefaultNamespaceSet.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/DefaultNamespaceSet.java index 2666d0e68..971a4c1b1 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/DefaultNamespaceSet.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/DefaultNamespaceSet.java @@ -6,10 +6,8 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.Getter; import lombok.NonNull; - import org.geoserver.catalog.NamespaceInfo; import org.geoserver.catalog.plugin.Patch; import org.geoserver.cloud.event.info.ConfigInfoType; @@ -26,8 +24,7 @@ public class DefaultNamespaceSet extends CatalogInfoModified { protected DefaultNamespaceSet() {} - DefaultNamespaceSet( - long updateSequence, @Nullable String newNamespaceId, @NonNull Patch patch) { + DefaultNamespaceSet(long updateSequence, @Nullable String newNamespaceId, @NonNull Patch patch) { super( updateSequence, InfoEvent.CATALOG_ID, @@ -42,8 +39,7 @@ protected DefaultNamespaceSet() {} return super.toStringBuilder().append("namespace", getNewNamespaceId()); } - public static DefaultNamespaceSet createLocal( - long updateSequence, NamespaceInfo defaultNamespace) { + public static DefaultNamespaceSet createLocal(long updateSequence, NamespaceInfo defaultNamespace) { String namespaceId = resolveNullableId(defaultNamespace); Patch patch = new Patch(); diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/DefaultWorkspaceSet.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/DefaultWorkspaceSet.java index cca73bdda..5b0da1a07 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/DefaultWorkspaceSet.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/catalog/DefaultWorkspaceSet.java @@ -6,10 +6,8 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.Getter; import lombok.NonNull; - import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.plugin.Patch; import org.geoserver.cloud.event.info.ConfigInfoType; @@ -44,8 +42,7 @@ protected DefaultWorkspaceSet() { return super.toStringBuilder().append("workspace", getNewWorkspaceId()); } - public static DefaultWorkspaceSet createLocal( - long updateSequence, WorkspaceInfo defaultWorkspace) { + public static DefaultWorkspaceSet createLocal(long updateSequence, WorkspaceInfo defaultWorkspace) { String workspaceId = resolveNullableId(defaultWorkspace); Patch patch = new Patch(); diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ConfigInfoAdded.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ConfigInfoAdded.java index 104323c1d..44b141dfa 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ConfigInfoAdded.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ConfigInfoAdded.java @@ -6,9 +6,7 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; - import lombok.NonNull; - import org.geoserver.catalog.Info; import org.geoserver.cloud.event.info.ConfigInfoType; import org.geoserver.cloud.event.info.InfoAdded; @@ -25,8 +23,7 @@ @JsonSubTypes.Type(value = SettingsAdded.class), }) @SuppressWarnings("serial") -public abstract class ConfigInfoAdded extends InfoAdded - implements ConfigInfoEvent { +public abstract class ConfigInfoAdded extends InfoAdded implements ConfigInfoEvent { protected ConfigInfoAdded() { // default constructor, needed for deserialization @@ -37,14 +34,12 @@ protected ConfigInfoAdded(long updateSequence, I object) { } @SuppressWarnings("unchecked") - public static @NonNull ConfigInfoAdded createLocal( - long updateSequence, @NonNull I info) { + public static @NonNull ConfigInfoAdded createLocal(long updateSequence, @NonNull I info) { final ConfigInfoType type = ConfigInfoType.valueOf(info); return (ConfigInfoAdded) switch (type) { - case GEOSERVER -> GeoServerInfoSet.createLocal( - updateSequence, (GeoServerInfo) info); + case GEOSERVER -> GeoServerInfoSet.createLocal(updateSequence, (GeoServerInfo) info); case SERVICE -> ServiceAdded.createLocal(updateSequence, (ServiceInfo) info); case SETTINGS -> SettingsAdded.createLocal(updateSequence, (SettingsInfo) info); case LOGGING -> LoggingInfoSet.createLocal(updateSequence, (LoggingInfo) info); diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ConfigInfoModified.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ConfigInfoModified.java index d35038cff..1eac92b9a 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ConfigInfoModified.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ConfigInfoModified.java @@ -6,9 +6,7 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; - import lombok.NonNull; - import org.geoserver.catalog.Info; import org.geoserver.catalog.plugin.Patch; import org.geoserver.cloud.event.info.ConfigInfoType; @@ -67,8 +65,7 @@ private static ServiceModified service(long updateSequence, ServiceInfo info, Pa return ServiceModified.createLocal(updateSequence, info, patch); } - private static GeoServerInfoModified geoserver( - long updateSequence, GeoServerInfo info, Patch patch) { + private static GeoServerInfoModified geoserver(long updateSequence, GeoServerInfo info, Patch patch) { return GeoServerInfoModified.createLocal(updateSequence, info, patch); } } diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ConfigInfoRemoved.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ConfigInfoRemoved.java index f1dc7edeb..72b95d2e6 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ConfigInfoRemoved.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ConfigInfoRemoved.java @@ -6,9 +6,7 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; - import lombok.NonNull; - import org.geoserver.catalog.Info; import org.geoserver.cloud.event.info.ConfigInfoType; import org.geoserver.cloud.event.info.InfoRemoved; @@ -28,15 +26,11 @@ protected ConfigInfoRemoved() { } protected ConfigInfoRemoved( - long updateSequence, - @NonNull String objectId, - @NonNull String prefixedName, - @NonNull ConfigInfoType type) { + long updateSequence, @NonNull String objectId, @NonNull String prefixedName, @NonNull ConfigInfoType type) { super(updateSequence, objectId, prefixedName, type); } - public static @NonNull ConfigInfoRemoved createLocal( - long updateSequence, @NonNull Info configInfo) { + public static @NonNull ConfigInfoRemoved createLocal(long updateSequence, @NonNull Info configInfo) { final ConfigInfoType type = ConfigInfoType.valueOf(configInfo); return switch (type) { diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/GeoServerInfoModified.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/GeoServerInfoModified.java index 05351c4a7..5937b230b 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/GeoServerInfoModified.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/GeoServerInfoModified.java @@ -6,10 +6,8 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.EqualsAndHashCode; import lombok.NonNull; - import org.geoserver.catalog.plugin.Patch; import org.geoserver.config.GeoServerInfo; @@ -23,13 +21,11 @@ protected GeoServerInfoModified() { // default constructor, needed for deserialization } - protected GeoServerInfoModified( - long updateSequence, @NonNull GeoServerInfo info, @NonNull Patch patch) { + protected GeoServerInfoModified(long updateSequence, @NonNull GeoServerInfo info, @NonNull Patch patch) { super(updateSequence, resolveId(info), prefixedName(info), typeOf(info), patch); } - public static GeoServerInfoModified createLocal( - long updateSequence, GeoServerInfo info, @NonNull Patch patch) { + public static GeoServerInfoModified createLocal(long updateSequence, GeoServerInfo info, @NonNull Patch patch) { return new GeoServerInfoModified(updateSequence, info, patch); } diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/GeoServerInfoSet.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/GeoServerInfoSet.java index c4328e0e7..70aa2c1bd 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/GeoServerInfoSet.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/GeoServerInfoSet.java @@ -6,7 +6,6 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - import org.geoserver.config.GeoServer; import org.geoserver.config.GeoServerInfo; diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/LoggingInfoModified.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/LoggingInfoModified.java index f7a994dc5..920dc51ff 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/LoggingInfoModified.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/LoggingInfoModified.java @@ -6,10 +6,8 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.EqualsAndHashCode; import lombok.NonNull; - import org.geoserver.catalog.plugin.Patch; import org.geoserver.config.LoggingInfo; @@ -28,8 +26,7 @@ protected LoggingInfoModified(long updateSequence, LoggingInfo info, @NonNull Pa super(updateSequence, resolveId(info), prefixedName(info), typeOf(info), patch); } - public static LoggingInfoModified createLocal( - long updateSequence, LoggingInfo info, @NonNull Patch patch) { + public static LoggingInfoModified createLocal(long updateSequence, LoggingInfo info, @NonNull Patch patch) { return new LoggingInfoModified(updateSequence, info, patch); } diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/LoggingInfoSet.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/LoggingInfoSet.java index bb5a01429..a338789b1 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/LoggingInfoSet.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/LoggingInfoSet.java @@ -6,7 +6,6 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - import org.geoserver.config.GeoServer; import org.geoserver.config.LoggingInfo; diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ServiceAdded.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ServiceAdded.java index cc0be30cf..f46c9f3e6 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ServiceAdded.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ServiceAdded.java @@ -6,9 +6,7 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.EqualsAndHashCode; - import org.geoserver.config.GeoServer; import org.geoserver.config.ServiceInfo; diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ServiceModified.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ServiceModified.java index c73fb1ee2..932a844e4 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ServiceModified.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ServiceModified.java @@ -6,18 +6,15 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - +import java.util.Objects; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; - import org.geoserver.catalog.plugin.Patch; import org.geoserver.cloud.event.info.InfoEvent; import org.geoserver.config.ServiceInfo; import org.springframework.core.style.ToStringCreator; -import java.util.Objects; - @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonTypeName("ServiceModified") @EqualsAndHashCode(callSuper = true) @@ -31,10 +28,7 @@ protected ServiceModified() { } protected ServiceModified( - long updateSequence, - @NonNull ServiceInfo info, - @NonNull Patch patch, - String workspaceId) { + long updateSequence, @NonNull ServiceInfo info, @NonNull Patch patch, String workspaceId) { super(updateSequence, resolveId(info), prefixedName(info), typeOf(info), patch); this.workspaceId = workspaceId; @@ -50,8 +44,7 @@ public String getObjectName() { return super.toStringBuilder().append("workspace", getWorkspaceId()); } - public static ServiceModified createLocal( - long updateSequence, @NonNull ServiceInfo service, @NonNull Patch patch) { + public static ServiceModified createLocal(long updateSequence, @NonNull ServiceInfo service, @NonNull Patch patch) { final String workspaceId = InfoEvent.resolveNullableId(service.getWorkspace()); return new ServiceModified(updateSequence, service, patch, workspaceId); } diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ServiceRemoved.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ServiceRemoved.java index 2f01d9847..40ec98443 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ServiceRemoved.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/ServiceRemoved.java @@ -6,11 +6,9 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; - import org.geoserver.config.ServiceInfo; import org.springframework.lang.Nullable; @@ -26,8 +24,7 @@ protected ServiceRemoved() { // default constructor, needed for deserialization } - protected ServiceRemoved( - long updateSequence, @NonNull ServiceInfo info, @Nullable String workspaceId) { + protected ServiceRemoved(long updateSequence, @NonNull ServiceInfo info, @Nullable String workspaceId) { super(updateSequence, resolveId(info), prefixedName(info), typeOf(info)); this.workspaceId = workspaceId; diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/SettingsAdded.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/SettingsAdded.java index f5c306a6d..4b62a3685 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/SettingsAdded.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/SettingsAdded.java @@ -6,9 +6,7 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.EqualsAndHashCode; - import org.geoserver.config.GeoServer; import org.geoserver.config.SettingsInfo; diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/SettingsModified.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/SettingsModified.java index 0086cd92a..8ec70a23e 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/SettingsModified.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/SettingsModified.java @@ -6,11 +6,9 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NonNull; - import org.geoserver.catalog.plugin.Patch; import org.geoserver.cloud.event.info.InfoEvent; import org.geoserver.config.SettingsInfo; @@ -29,10 +27,7 @@ protected SettingsModified() { } public SettingsModified( - long updateSequence, - @NonNull SettingsInfo settings, - @NonNull Patch patch, - @NonNull String workspaceId) { + long updateSequence, @NonNull SettingsInfo settings, @NonNull Patch patch, @NonNull String workspaceId) { super(updateSequence, resolveId(settings), prefixedName(settings), typeOf(settings), patch); this.workspaceId = workspaceId; diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/SettingsRemoved.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/SettingsRemoved.java index e70e8d5fb..50225bbe5 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/SettingsRemoved.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/config/SettingsRemoved.java @@ -6,10 +6,8 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.Getter; import lombok.NonNull; - import org.geoserver.config.SettingsInfo; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) @@ -23,8 +21,7 @@ protected SettingsRemoved() { // default constructor, needed for deserialization } - protected SettingsRemoved( - long updateSequence, @NonNull SettingsInfo info, @NonNull String workspaceId) { + protected SettingsRemoved(long updateSequence, @NonNull SettingsInfo info, @NonNull String workspaceId) { super(updateSequence, resolveId(info), prefixedName(info), typeOf(info)); this.workspaceId = workspaceId; diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/ConfigInfoType.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/ConfigInfoType.java index b2847f66b..29787e79d 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/ConfigInfoType.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/ConfigInfoType.java @@ -8,7 +8,6 @@ import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CoverageInfo; import org.geoserver.catalog.CoverageStoreInfo; diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/InfoAdded.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/InfoAdded.java index fbb212cef..c368df21a 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/InfoAdded.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/InfoAdded.java @@ -6,11 +6,9 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; - import lombok.Getter; import lombok.NonNull; import lombok.Setter; - import org.geoserver.catalog.Info; import org.geoserver.cloud.event.catalog.CatalogInfoAdded; import org.geoserver.cloud.event.config.ConfigInfoAdded; diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/InfoEvent.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/InfoEvent.java index 42bf758bc..7ada67d2c 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/InfoEvent.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/InfoEvent.java @@ -6,10 +6,9 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; - +import java.util.Optional; import lombok.Getter; import lombok.NonNull; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.Info; import org.geoserver.catalog.LayerGroupInfo; @@ -27,8 +26,6 @@ import org.springframework.core.style.ToStringCreator; import org.springframework.lang.Nullable; -import java.util.Optional; - @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonSubTypes({ @JsonSubTypes.Type(value = InfoAdded.class), @@ -85,8 +82,7 @@ public String toShortString() { String originService = getOrigin(); String type = getClass().getSimpleName(); return "%s[origin: %s, updateSequence: %s, object: %s(%s)]" - .formatted( - type, originService, getUpdateSequence(), getObjectType(), getObjectId()); + .formatted(type, originService, getUpdateSequence(), getObjectType(), getObjectId()); } @Nullable diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/InfoModified.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/InfoModified.java index 504243a6c..92ae9f2c8 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/InfoModified.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/InfoModified.java @@ -6,19 +6,16 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; - +import java.util.stream.Collectors; import lombok.Getter; import lombok.NonNull; import lombok.Setter; - import org.geoserver.catalog.Info; import org.geoserver.catalog.plugin.Patch; import org.geoserver.cloud.event.catalog.CatalogInfoModified; import org.geoserver.cloud.event.config.ConfigInfoModified; import org.springframework.core.style.ToStringCreator; -import java.util.stream.Collectors; - @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonSubTypes({ @JsonSubTypes.Type(value = CatalogInfoModified.class), @@ -50,8 +47,6 @@ protected InfoModified( protected @Override ToStringCreator toStringBuilder() { return super.toStringBuilder() - .append( - "changes", - getPatch().getPropertyNames().stream().collect(Collectors.joining(","))); + .append("changes", getPatch().getPropertyNames().stream().collect(Collectors.joining(","))); } } diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/InfoRemoved.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/InfoRemoved.java index 2100a8156..6f4b74144 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/InfoRemoved.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/info/InfoRemoved.java @@ -6,9 +6,7 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; - import lombok.NonNull; - import org.geoserver.cloud.event.catalog.CatalogInfoRemoved; import org.geoserver.cloud.event.config.ConfigInfoRemoved; @@ -23,10 +21,7 @@ public abstract class InfoRemoved extends InfoEvent { protected InfoRemoved() {} protected InfoRemoved( - long updateSequence, - @NonNull String objectId, - @NonNull String prefixedName, - @NonNull ConfigInfoType type) { + long updateSequence, @NonNull String objectId, @NonNull String prefixedName, @NonNull ConfigInfoType type) { super(updateSequence, objectId, prefixedName, type); } } diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/lifecycle/LifecycleEvent.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/lifecycle/LifecycleEvent.java index aa4f5365f..107d34f2d 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/lifecycle/LifecycleEvent.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/lifecycle/LifecycleEvent.java @@ -6,14 +6,10 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; - import org.geoserver.cloud.event.GeoServerEvent; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) -@JsonSubTypes({ - @JsonSubTypes.Type(value = ReloadEvent.class), - @JsonSubTypes.Type(value = ResetEvent.class) -}) +@JsonSubTypes({@JsonSubTypes.Type(value = ReloadEvent.class), @JsonSubTypes.Type(value = ResetEvent.class)}) @SuppressWarnings("serial") public abstract class LifecycleEvent extends GeoServerEvent { diff --git a/src/catalog/events/src/main/java/org/geoserver/cloud/event/security/SecurityConfigChanged.java b/src/catalog/events/src/main/java/org/geoserver/cloud/event/security/SecurityConfigChanged.java index be23b98fb..d5c9a892f 100644 --- a/src/catalog/events/src/main/java/org/geoserver/cloud/event/security/SecurityConfigChanged.java +++ b/src/catalog/events/src/main/java/org/geoserver/cloud/event/security/SecurityConfigChanged.java @@ -6,10 +6,8 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.Getter; import lombok.NonNull; - import org.geoserver.cloud.event.UpdateSequenceEvent; import org.geoserver.security.GeoServerSecurityManager; import org.springframework.core.style.ToStringCreator; diff --git a/src/catalog/events/src/test/java/org/geoserver/cloud/config/catalog/events/CatalogApplicationEventsConfigurationTest.java b/src/catalog/events/src/test/java/org/geoserver/cloud/config/catalog/events/CatalogApplicationEventsConfigurationTest.java index 6ffcb1973..94b9421ac 100644 --- a/src/catalog/events/src/test/java/org/geoserver/cloud/config/catalog/events/CatalogApplicationEventsConfigurationTest.java +++ b/src/catalog/events/src/test/java/org/geoserver/cloud/config/catalog/events/CatalogApplicationEventsConfigurationTest.java @@ -7,8 +7,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.*; +import java.util.List; +import java.util.Optional; +import java.util.function.Consumer; import lombok.NonNull; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.CatalogTestData; @@ -42,15 +44,7 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; -import java.util.List; -import java.util.Optional; -import java.util.function.Consumer; - -@SpringBootTest( - classes = { - TestConfigurationAutoConfiguration.class, - ApplicationEventCapturingListener.class - }) +@SpringBootTest(classes = {TestConfigurationAutoConfiguration.class, ApplicationEventCapturingListener.class}) @EnableAutoConfiguration class CatalogApplicationEventsConfigurationTest { @@ -74,15 +68,9 @@ class CatalogApplicationEventsConfigurationTest { @Test void testCatalogEventBroadcasterHasSetUpItself() { - Optional publisherListener = - catalog.getListeners().stream() - .filter( - l -> - l - instanceof - CatalogApplicationEventPublisher - .LocalCatalogEventPublisher) - .findFirst(); + Optional publisherListener = catalog.getListeners().stream() + .filter(l -> l instanceof CatalogApplicationEventPublisher.LocalCatalogEventPublisher) + .findFirst(); assertTrue(publisherListener.isPresent()); } @@ -123,15 +111,9 @@ void testGSLifeCycleDispatchOnReload() throws Exception { @Test void testConfigEventBroadcasterHasSetUpItself() { - Optional publisherListener = - geoserver.getListeners().stream() - .filter( - l -> - l - instanceof - CatalogApplicationEventPublisher - .LocalConfigEventPublisher) - .findFirst(); + Optional publisherListener = geoserver.getListeners().stream() + .filter(l -> l instanceof CatalogApplicationEventPublisher.LocalConfigEventPublisher) + .findFirst(); assertTrue(publisherListener.isPresent()); } @@ -343,8 +325,7 @@ void testConfigRemoveEvents() { testRemove(service, geoserver::remove, ServiceRemoved.class); } - private void testRemove( - T info, Consumer remover, Class eventType) { + private void testRemove(T info, Consumer remover, Class eventType) { listener.clear(); listener.start(); remover.accept(info); @@ -359,8 +340,7 @@ private void testModify( @NonNull Consumer modifier, @NonNull Consumer saver, @NonNull Class postEventType) { - if (null == ModificationProxy.handler(info)) - throw new IllegalArgumentException("Expected a ModificationProxy"); + if (null == ModificationProxy.handler(info)) throw new IllegalArgumentException("Expected a ModificationProxy"); Class type = (Class) ConfigInfoType.valueOf(info).getType(); @@ -380,7 +360,8 @@ private void testModify( modifier.accept(info); saver.accept(info); - Patch expected = PropertyDiff.valueOf(propertyNames, oldValues, newValues).toPatch(); + Patch expected = + PropertyDiff.valueOf(propertyNames, oldValues, newValues).toPatch(); InfoModified post = listener.expectOne(postEventType); assertThat(post.getObjectId()).isEqualTo(InfoEvent.resolveId(info)); assertThat(post.getPatch()).isEqualTo(expected); @@ -400,8 +381,7 @@ private void testModify(CatalogInfo objectChanged, String propertyName, CatalogI } @SuppressWarnings({"rawtypes"}) - private void testAddEvent( - T info, Consumer addOp, Class eventType) { + private void testAddEvent(T info, Consumer addOp, Class eventType) { listener.clear(); addOp.accept(info); InfoAdded event = listener.expectOne(eventType); diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/CatalogInfoDeserializer.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/CatalogInfoDeserializer.java index 350d3e51b..609113624 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/CatalogInfoDeserializer.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/CatalogInfoDeserializer.java @@ -7,14 +7,12 @@ import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; - +import java.io.IOException; import org.geoserver.catalog.CatalogInfo; import org.geoserver.jackson.databind.catalog.dto.CatalogInfoDto; import org.geoserver.jackson.databind.catalog.mapper.CatalogInfoMapper; import org.mapstruct.factory.Mappers; -import java.io.IOException; - public class CatalogInfoDeserializer extends JsonDeserializer { private static final CatalogInfoMapper mapper = Mappers.getMapper(CatalogInfoMapper.class); diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/CatalogInfoSerializer.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/CatalogInfoSerializer.java index 8086bc0ec..d68fcc674 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/CatalogInfoSerializer.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/CatalogInfoSerializer.java @@ -10,14 +10,12 @@ import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.ser.std.StdSerializer; - +import java.io.IOException; import org.geoserver.catalog.CatalogInfo; import org.geoserver.jackson.databind.catalog.dto.CatalogInfoDto; import org.geoserver.jackson.databind.catalog.mapper.CatalogInfoMapper; import org.mapstruct.factory.Mappers; -import java.io.IOException; - public class CatalogInfoSerializer extends StdSerializer { private static final long serialVersionUID = -4772839273787523779L; @@ -31,21 +29,18 @@ protected CatalogInfoSerializer(Class infoType) { } @Override - public void serialize(CatalogInfo info, JsonGenerator gen, SerializerProvider provider) - throws IOException { + public void serialize(CatalogInfo info, JsonGenerator gen, SerializerProvider provider) throws IOException { CatalogInfoDto dto = mapper.map(info); gen.writeObject(dto); } @Override - public void serializeWithType( - I value, JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) + public void serializeWithType(I value, JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { WritableTypeId typeIdDef = - typeSer.writeTypePrefix( - gen, typeSer.typeId(value, infoType, JsonToken.VALUE_STRING)); + typeSer.writeTypePrefix(gen, typeSer.typeId(value, infoType, JsonToken.VALUE_STRING)); serialize(value, gen, null); diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/GeoServerCatalogModule.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/GeoServerCatalogModule.java index bec5023ec..165ae9ebf 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/GeoServerCatalogModule.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/GeoServerCatalogModule.java @@ -7,9 +7,9 @@ import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; - +import java.util.Arrays; +import java.util.function.Function; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.AttributeTypeInfo; import org.geoserver.catalog.AuthorityURLInfo; import org.geoserver.catalog.CatalogInfo; @@ -48,9 +48,6 @@ import org.geotools.jdbc.VirtualTable; import org.mapstruct.factory.Mappers; -import java.util.Arrays; -import java.util.function.Function; - /** * Jackson {@link com.fasterxml.jackson.databind.Module} to handle GeoServer {@link CatalogInfo} * bindings. @@ -82,8 +79,7 @@ public class GeoServerCatalogModule extends SimpleModule { private static final long serialVersionUID = -8756800180255446679L; static final PatchMapper PATCH_MAPPER = Mappers.getMapper(PatchMapper.class); - static final GeoServerValueObjectsMapper VALUE_MAPPER = - Mappers.getMapper(GeoServerValueObjectsMapper.class); + static final GeoServerValueObjectsMapper VALUE_MAPPER = Mappers.getMapper(GeoServerValueObjectsMapper.class); public GeoServerCatalogModule() { super(GeoServerCatalogModule.class.getSimpleName(), new Version(1, 0, 0, null, null, null)); @@ -104,11 +100,10 @@ protected void registerCatalogInfoCodecs() { .map(c -> (Class) c) .distinct() .sorted((c1, c2) -> c1.getSimpleName().compareTo(c2.getSimpleName())) - .forEach( - c -> { - this.addSerializer(c); - this.addDeserializer(c); - }); + .forEach(c -> { + this.addSerializer(c); + this.addDeserializer(c); + }); } private void addSerializer(Class clazz) { @@ -126,24 +121,18 @@ private void addDeserializer(Class clazz) { * @param DTO type */ private void addMapperSerializer( - Class type, - Function serializerMapper, - Class dtoType, - Function deserializerMapper) { + Class type, Function serializerMapper, Class dtoType, Function deserializerMapper) { MapperSerializer serializer = new MapperSerializer<>(type, serializerMapper); - MapperDeserializer deserializer = - new MapperDeserializer<>(dtoType, deserializerMapper); + MapperDeserializer deserializer = new MapperDeserializer<>(dtoType, deserializerMapper); super.addSerializer(type, serializer); super.addDeserializer(type, deserializer); } private void registerValueMappers() { - addMapperSerializer( - Patch.class, PATCH_MAPPER::patchToDto, PatchDto.class, PATCH_MAPPER::dtoToPatch); + addMapperSerializer(Patch.class, PATCH_MAPPER::patchToDto, PatchDto.class, PATCH_MAPPER::dtoToPatch); - addMapperSerializer( - KeywordInfo.class, VALUE_MAPPER::keyword, Keyword.class, VALUE_MAPPER::keyword); + addMapperSerializer(KeywordInfo.class, VALUE_MAPPER::keyword, Keyword.class, VALUE_MAPPER::keyword); addMapperSerializer( VirtualTable.class, @@ -151,56 +140,28 @@ private void registerValueMappers() { VirtualTableDto.class, VALUE_MAPPER::dtoToVirtualTable); addMapperSerializer( - MetadataLinkInfo.class, - VALUE_MAPPER::infoToDto, - MetadataLink.class, - VALUE_MAPPER::dtoToInfo); - addMapperSerializer( - LegendInfo.class, VALUE_MAPPER::infoToDto, Legend.class, VALUE_MAPPER::dtoToInfo); + MetadataLinkInfo.class, VALUE_MAPPER::infoToDto, MetadataLink.class, VALUE_MAPPER::dtoToInfo); + addMapperSerializer(LegendInfo.class, VALUE_MAPPER::infoToDto, Legend.class, VALUE_MAPPER::dtoToInfo); addMapperSerializer( - LayerIdentifierInfo.class, - VALUE_MAPPER::infoToDto, - LayerIdentifier.class, - VALUE_MAPPER::dtoToInfo); + LayerIdentifierInfo.class, VALUE_MAPPER::infoToDto, LayerIdentifier.class, VALUE_MAPPER::dtoToInfo); + addMapperSerializer(DataLinkInfo.class, VALUE_MAPPER::infoToDto, DataLink.class, VALUE_MAPPER::dtoToInfo); + addMapperSerializer(DimensionInfo.class, VALUE_MAPPER::infoToDto, Dimension.class, VALUE_MAPPER::dtoToInfo); addMapperSerializer( - DataLinkInfo.class, - VALUE_MAPPER::infoToDto, - DataLink.class, - VALUE_MAPPER::dtoToInfo); + CoverageDimensionInfo.class, VALUE_MAPPER::infoToDto, CoverageDimension.class, VALUE_MAPPER::dtoToInfo); addMapperSerializer( - DimensionInfo.class, - VALUE_MAPPER::infoToDto, - Dimension.class, - VALUE_MAPPER::dtoToInfo); - addMapperSerializer( - CoverageDimensionInfo.class, - VALUE_MAPPER::infoToDto, - CoverageDimension.class, - VALUE_MAPPER::dtoToInfo); - addMapperSerializer( - AuthorityURLInfo.class, - VALUE_MAPPER::infoToDto, - AuthorityURL.class, - VALUE_MAPPER::dtoToInfo); + AuthorityURLInfo.class, VALUE_MAPPER::infoToDto, AuthorityURL.class, VALUE_MAPPER::dtoToInfo); addMapperSerializer( GridGeometry.class, VALUE_MAPPER::gridGeometry2DToDto, GridGeometryDto.class, VALUE_MAPPER::dtoToGridGeometry2D); - addMapperSerializer( - Query.class, VALUE_MAPPER::queryToDto, QueryDto.class, VALUE_MAPPER::dtoToQuery); + addMapperSerializer(Query.class, VALUE_MAPPER::queryToDto, QueryDto.class, VALUE_MAPPER::dtoToQuery); addMapperSerializer( - AttributeTypeInfo.class, - VALUE_MAPPER::infoToDto, - AttributeType.class, - VALUE_MAPPER::dtoToInfo); + AttributeTypeInfo.class, VALUE_MAPPER::infoToDto, AttributeType.class, VALUE_MAPPER::dtoToInfo); addMapperSerializer( - MetadataMap.class, - VALUE_MAPPER::metadataMap, - MetadataMapDto.class, - VALUE_MAPPER::metadataMap); + MetadataMap.class, VALUE_MAPPER::metadataMap, MetadataMapDto.class, VALUE_MAPPER::metadataMap); } } diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/AttributeType.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/AttributeType.java index 077ef9aa9..8f9d61bee 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/AttributeType.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/AttributeType.java @@ -4,10 +4,9 @@ */ package org.geoserver.jackson.databind.catalog.dto; -import lombok.Data; - import java.io.Serializable; import java.util.Map; +import lombok.Data; @Data public class AttributeType { diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/CatalogInfoDto.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/CatalogInfoDto.java index 9b2f1f3d2..047b75057 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/CatalogInfoDto.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/CatalogInfoDto.java @@ -5,12 +5,10 @@ package org.geoserver.jackson.databind.catalog.dto; import com.fasterxml.jackson.annotation.JsonSubTypes; - +import java.util.Date; import lombok.Data; import lombok.EqualsAndHashCode; -import java.util.Date; - @JsonSubTypes({ @JsonSubTypes.Type(value = Workspace.class), @JsonSubTypes.Type(value = Namespace.class), diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Coverage.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Coverage.java index 6be8588d8..6bb0749a9 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Coverage.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Coverage.java @@ -5,13 +5,11 @@ package org.geoserver.jackson.databind.catalog.dto; import com.fasterxml.jackson.annotation.JsonTypeName; - -import lombok.Data; -import lombok.EqualsAndHashCode; - import java.io.Serializable; import java.util.List; import java.util.Map; +import lombok.Data; +import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = true) diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/CoverageDimension.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/CoverageDimension.java index 3c907e351..0cdaf70b6 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/CoverageDimension.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/CoverageDimension.java @@ -4,13 +4,11 @@ */ package org.geoserver.jackson.databind.catalog.dto; +import java.util.List; import lombok.Data; - import org.geoserver.catalog.impl.CoverageDimensionImpl; import org.geotools.jackson.databind.dto.NumberRangeDto; -import java.util.List; - /** * @see CoverageDimensionImpl */ diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/CoverageStore.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/CoverageStore.java index ce5047366..9c919db04 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/CoverageStore.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/CoverageStore.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog.dto; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.Data; import lombok.EqualsAndHashCode; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/DataStore.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/DataStore.java index 4affa7649..2caad62de 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/DataStore.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/DataStore.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog.dto; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.Data; import lombok.EqualsAndHashCode; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Dimension.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Dimension.java index 3df40a393..53be389cc 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Dimension.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Dimension.java @@ -4,14 +4,12 @@ */ package org.geoserver.jackson.databind.catalog.dto; +import java.math.BigDecimal; import lombok.Data; - import org.geoserver.catalog.DimensionDefaultValueSetting; import org.geoserver.catalog.DimensionInfo; import org.geoserver.catalog.DimensionPresentation; -import java.math.BigDecimal; - /** DTO for {@link DimensionInfo} */ @Data public class Dimension { diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/FeatureType.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/FeatureType.java index 20228993b..fa107c9ab 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/FeatureType.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/FeatureType.java @@ -5,12 +5,10 @@ package org.geoserver.jackson.databind.catalog.dto; import com.fasterxml.jackson.annotation.JsonTypeName; - +import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; -import java.util.List; - @Data @EqualsAndHashCode(callSuper = true) @JsonTypeName("FeatureTypeInfo") diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/GridGeometryDto.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/GridGeometryDto.java index 09d497e8e..83867f5df 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/GridGeometryDto.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/GridGeometryDto.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog.dto; import lombok.Data; - import org.geoserver.config.util.XStreamPersister; import org.geotools.coverage.grid.GridGeometry2D; import org.geotools.jackson.databind.dto.CRS; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/HTTPStore.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/HTTPStore.java index 01fb5985e..cba1cd5c4 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/HTTPStore.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/HTTPStore.java @@ -5,14 +5,10 @@ package org.geoserver.jackson.databind.catalog.dto; import com.fasterxml.jackson.annotation.JsonSubTypes; - import lombok.Data; import lombok.EqualsAndHashCode; -@JsonSubTypes({ - @JsonSubTypes.Type(value = WMSStore.class), - @JsonSubTypes.Type(value = WMTSStore.class) -}) +@JsonSubTypes({@JsonSubTypes.Type(value = WMSStore.class), @JsonSubTypes.Type(value = WMTSStore.class)}) @Data @EqualsAndHashCode(callSuper = true) public abstract class HTTPStore extends Store { diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/InfoDto.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/InfoDto.java index 4be0f8307..c4a9c1df2 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/InfoDto.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/InfoDto.java @@ -6,16 +6,11 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; - import lombok.Data; - import org.geoserver.jackson.databind.config.dto.ConfigInfoDto; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY) -@JsonSubTypes({ - @JsonSubTypes.Type(value = CatalogInfoDto.class), - @JsonSubTypes.Type(value = ConfigInfoDto.class) -}) +@JsonSubTypes({@JsonSubTypes.Type(value = CatalogInfoDto.class), @JsonSubTypes.Type(value = ConfigInfoDto.class)}) @Data public abstract class InfoDto { private String id; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/InfoReference.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/InfoReference.java index 7c176593b..43df15008 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/InfoReference.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/InfoReference.java @@ -8,7 +8,6 @@ import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; - import org.geoserver.catalog.impl.ClassMappings; @Data diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Layer.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Layer.java index c51dea019..cdf7f194b 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Layer.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Layer.java @@ -5,12 +5,10 @@ package org.geoserver.jackson.databind.catalog.dto; import com.fasterxml.jackson.annotation.JsonTypeName; - +import java.util.Set; import lombok.Data; import lombok.EqualsAndHashCode; -import java.util.Set; - @Data @EqualsAndHashCode(callSuper = true) @JsonTypeName("LayerInfo") diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/LayerGroup.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/LayerGroup.java index ce9ff5dbf..6d6b81d6a 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/LayerGroup.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/LayerGroup.java @@ -5,15 +5,12 @@ package org.geoserver.jackson.databind.catalog.dto; import com.fasterxml.jackson.annotation.JsonTypeName; - +import java.util.List; +import java.util.Map; import lombok.Data; import lombok.EqualsAndHashCode; - import org.geotools.jackson.databind.dto.Envelope; -import java.util.List; -import java.util.Map; - @Data @EqualsAndHashCode(callSuper = true) @JsonTypeName("LayerGroupInfo") diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/LayerGroupStyle.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/LayerGroupStyle.java index 80338933b..5f7d9c1bc 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/LayerGroupStyle.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/LayerGroupStyle.java @@ -4,10 +4,9 @@ */ package org.geoserver.jackson.databind.catalog.dto; -import lombok.Data; - import java.util.List; import java.util.Map; +import lombok.Data; /** * DTO for {@link org.geoserver.catalog.impl.LayerGroupStyle} diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Map.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Map.java index 697367880..5c9fe15e6 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Map.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Map.java @@ -5,12 +5,10 @@ package org.geoserver.jackson.databind.catalog.dto; import com.fasterxml.jackson.annotation.JsonTypeName; - +import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; -import java.util.List; - @Data @EqualsAndHashCode(callSuper = true) @JsonTypeName("MapInfo") diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/MetadataMapDto.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/MetadataMapDto.java index 0b7de9955..c60956c2e 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/MetadataMapDto.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/MetadataMapDto.java @@ -6,10 +6,8 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - -import org.geotools.jackson.databind.filter.dto.Literal; - import java.util.LinkedHashMap; +import org.geotools.jackson.databind.filter.dto.Literal; /** * @since 1.0 diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Namespace.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Namespace.java index 110aaeaf5..6d6b237e7 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Namespace.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Namespace.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog.dto; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.Data; import lombok.EqualsAndHashCode; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/PatchDto.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/PatchDto.java index aa123cb94..07a6fd221 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/PatchDto.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/PatchDto.java @@ -6,13 +6,10 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - -import lombok.Data; - -import org.geotools.jackson.databind.filter.dto.Literal; - import java.util.ArrayList; import java.util.List; +import lombok.Data; +import org.geotools.jackson.databind.filter.dto.Literal; /** DTO for {@link org.geoserver.catalog.plugin.Patch} */ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Published.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Published.java index 8727ea758..2d27d79c9 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Published.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Published.java @@ -5,16 +5,11 @@ package org.geoserver.jackson.databind.catalog.dto; import com.fasterxml.jackson.annotation.JsonSubTypes; - +import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; -import java.util.List; - -@JsonSubTypes({ - @JsonSubTypes.Type(value = Layer.class), - @JsonSubTypes.Type(value = LayerGroup.class) -}) +@JsonSubTypes({@JsonSubTypes.Type(value = Layer.class), @JsonSubTypes.Type(value = LayerGroup.class)}) @Data @EqualsAndHashCode(callSuper = true) public abstract class Published extends CatalogInfoDto { diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/QueryDto.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/QueryDto.java index 867959c2a..1b1a1c603 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/QueryDto.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/QueryDto.java @@ -4,18 +4,16 @@ */ package org.geoserver.jackson.databind.catalog.dto; +import java.util.ArrayList; +import java.util.List; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.catalog.plugin.Query; import org.geotools.api.filter.Filter; import org.geotools.api.filter.sort.SortBy; -import java.util.ArrayList; -import java.util.List; - /** DTO for {@link Query} */ @NoArgsConstructor @RequiredArgsConstructor diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Resource.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Resource.java index 566bea14b..5c766c039 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Resource.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Resource.java @@ -5,16 +5,13 @@ package org.geoserver.jackson.databind.catalog.dto; import com.fasterxml.jackson.annotation.JsonSubTypes; - +import java.util.List; +import java.util.Map; import lombok.Data; import lombok.EqualsAndHashCode; - import org.geotools.jackson.databind.dto.CRS; import org.geotools.jackson.databind.dto.Envelope; -import java.util.List; -import java.util.Map; - @JsonSubTypes({ @JsonSubTypes.Type(value = Coverage.class), @JsonSubTypes.Type(value = FeatureType.class), diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Store.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Store.java index 5fb6ea39c..955432a84 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Store.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Store.java @@ -5,12 +5,10 @@ package org.geoserver.jackson.databind.catalog.dto; import com.fasterxml.jackson.annotation.JsonSubTypes; - -import lombok.Data; -import lombok.EqualsAndHashCode; - import java.io.Serializable; import java.util.Map; +import lombok.Data; +import lombok.EqualsAndHashCode; @JsonSubTypes({ @JsonSubTypes.Type(value = CoverageStore.class), diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Style.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Style.java index b22641ef7..b34afe756 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Style.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Style.java @@ -5,10 +5,8 @@ package org.geoserver.jackson.databind.catalog.dto; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.Data; import lombok.EqualsAndHashCode; - import org.geotools.jackson.databind.dto.VersionDto; @Data diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/VirtualTableDto.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/VirtualTableDto.java index 9ec1623f7..dfc7d7bef 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/VirtualTableDto.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/VirtualTableDto.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog.dto; import lombok.Data; - import org.geotools.jdbc.VirtualTable; /** DTO type for {@link VirtualTable} */ diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/WMSLayer.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/WMSLayer.java index a659ed5bd..8bd64301a 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/WMSLayer.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/WMSLayer.java @@ -5,12 +5,10 @@ package org.geoserver.jackson.databind.catalog.dto; import com.fasterxml.jackson.annotation.JsonTypeName; - +import java.util.List; import lombok.Data; import lombok.EqualsAndHashCode; -import java.util.List; - @Data @EqualsAndHashCode(callSuper = true) @JsonTypeName("WMSLayerInfo") diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/WMSStore.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/WMSStore.java index a3f297191..12a1ef10e 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/WMSStore.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/WMSStore.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog.dto; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.Data; import lombok.EqualsAndHashCode; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/WMTSLayer.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/WMTSLayer.java index 35eaea3bf..5b50cde4f 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/WMTSLayer.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/WMTSLayer.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog.dto; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.Data; import lombok.EqualsAndHashCode; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/WMTSStore.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/WMTSStore.java index b340f2ec1..e8011c596 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/WMTSStore.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/WMTSStore.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog.dto; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.Data; import lombok.EqualsAndHashCode; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Workspace.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Workspace.java index 48005b6f2..6184a305a 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Workspace.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/dto/Workspace.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog.dto; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.Data; import lombok.EqualsAndHashCode; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/CatalogInfoMapper.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/CatalogInfoMapper.java index 9310a5bd7..9c51f50f3 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/CatalogInfoMapper.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/CatalogInfoMapper.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog.mapper; import lombok.Generated; - import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.MapInfo; import org.geoserver.catalog.NamespaceInfo; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/GeoServerValueObjectsMapper.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/GeoServerValueObjectsMapper.java index 0711e7234..7f83b2ed6 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/GeoServerValueObjectsMapper.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/GeoServerValueObjectsMapper.java @@ -4,8 +4,10 @@ */ package org.geoserver.jackson.databind.catalog.mapper; +import java.awt.geom.AffineTransform; +import java.io.Serializable; +import java.util.Optional; import lombok.Generated; - import org.geoserver.catalog.AttributeTypeInfo; import org.geoserver.catalog.AttributionInfo; import org.geoserver.catalog.AuthorityURLInfo; @@ -55,10 +57,6 @@ import org.mapstruct.ReportingPolicy; import org.mapstruct.factory.Mappers; -import java.awt.geom.AffineTransform; -import java.io.Serializable; -import java.util.Optional; - @Mapper( componentModel = "default", unmappedTargetPolicy = ReportingPolicy.ERROR, @@ -77,11 +75,9 @@ public interface GeoServerValueObjectsMapper { */ default GridGeometry dtoToGridGeometry2D(GridGeometryDto value) { if (value == null) return null; - CoordinateReferenceSystem crs = - Mappers.getMapper( - org.geotools.jackson.databind.filter.mapper.GeoToolsValueMappers - .class) - .crs(value.getCrs()); + CoordinateReferenceSystem crs = Mappers.getMapper( + org.geotools.jackson.databind.filter.mapper.GeoToolsValueMappers.class) + .crs(value.getCrs()); int[] high = value.getHigh(); int[] low = value.getLow(); MathTransform gridToCRS = affineTransform(value.getTransform()); @@ -105,11 +101,8 @@ default GridGeometryDto gridGeometry2DToDto(GridGeometry value) { } dto.setTransform(affineTransform(g.getGridToCRS())); - CRS crs = - Mappers.getMapper( - org.geotools.jackson.databind.filter.mapper.GeoToolsValueMappers - .class) - .crs(g.getCoordinateReferenceSystem()); + CRS crs = Mappers.getMapper(org.geotools.jackson.databind.filter.mapper.GeoToolsValueMappers.class) + .crs(g.getCoordinateReferenceSystem()); dto.setCrs(crs); return dto; } @@ -188,22 +181,20 @@ default VirtualTable dtoToVirtualTable(VirtualTableDto dto) { default MetadataMapDto metadataMap(MetadataMap md) { if (md == null) return null; MetadataMapDto dto = new MetadataMapDto(); - md.forEach( - (k, v) -> { - Literal l = Literal.valueOf(v); - dto.put(k, l); - }); + md.forEach((k, v) -> { + Literal l = Literal.valueOf(v); + dto.put(k, l); + }); return dto; } default MetadataMap metadataMap(MetadataMapDto dto) { if (dto == null) return null; MetadataMap md = new MetadataMap(); - dto.forEach( - (k, l) -> { - Object v = l.getValue(); - md.put(k, (Serializable) v); - }); + dto.forEach((k, l) -> { + Object v = l.getValue(); + md.put(k, (Serializable) v); + }); return md; } diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/MapMapper.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/MapMapper.java index 3d0bc12bf..5d584532b 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/MapMapper.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/MapMapper.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog.mapper; import lombok.Generated; - import org.geoserver.catalog.MapInfo; import org.geoserver.jackson.databind.catalog.dto.Map; import org.mapstruct.AnnotateWith; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/NamespaceMapper.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/NamespaceMapper.java index 6ca18ec75..0913e2f47 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/NamespaceMapper.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/NamespaceMapper.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog.mapper; import lombok.Generated; - import org.geoserver.catalog.NamespaceInfo; import org.geoserver.jackson.databind.catalog.dto.Namespace; import org.mapstruct.AnnotateWith; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/ObjectFacotries.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/ObjectFacotries.java index ceac98515..c95ca58ef 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/ObjectFacotries.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/ObjectFacotries.java @@ -4,6 +4,7 @@ */ package org.geoserver.jackson.databind.catalog.mapper; +import java.util.function.Supplier; import org.geoserver.catalog.AttributeTypeInfo; import org.geoserver.catalog.AttributionInfo; import org.geoserver.catalog.AuthorityURLInfo; @@ -75,26 +76,21 @@ import org.mapstruct.ObjectFactory; import org.mapstruct.TargetType; -import java.util.function.Supplier; - /** * Auto-wired object factory for Catalog info interfaces, so the mapstruct code-generated mappers * know how to instantiate them */ public class ObjectFacotries { - public @ObjectFactory WorkspaceInfo workspaceInfo( - Workspace source, @TargetType Class type) { + public @ObjectFactory WorkspaceInfo workspaceInfo(Workspace source, @TargetType Class type) { return create(source.getId(), WorkspaceInfoImpl::new); } - public @ObjectFactory NamespaceInfo namespaceInfo( - Namespace source, @TargetType Class type) { + public @ObjectFactory NamespaceInfo namespaceInfo(Namespace source, @TargetType Class type) { return create(source.getId(), NamespaceInfoImpl::new); } - public @ObjectFactory DataStoreInfo dataStoreInfo( - DataStore source, @TargetType Class type) { + public @ObjectFactory DataStoreInfo dataStoreInfo(DataStore source, @TargetType Class type) { return create(source.getId(), () -> new DataStoreInfoImpl((Catalog) null)); } @@ -103,33 +99,27 @@ public class ObjectFacotries { return create(source.getId(), () -> new CoverageStoreInfoImpl((Catalog) null)); } - public @ObjectFactory WMSStoreInfo wmsStoreInfo( - WMSStore source, @TargetType Class type) { + public @ObjectFactory WMSStoreInfo wmsStoreInfo(WMSStore source, @TargetType Class type) { return create(source.getId(), () -> new WMSStoreInfoImpl((Catalog) null)); } - public @ObjectFactory WMTSStoreInfo wmtsStoreInfo( - WMTSStore source, @TargetType Class type) { + public @ObjectFactory WMTSStoreInfo wmtsStoreInfo(WMTSStore source, @TargetType Class type) { return create(source.getId(), () -> new WMTSStoreInfoImpl((Catalog) null)); } - public @ObjectFactory FeatureTypeInfo featureTypeInfo( - FeatureType source, @TargetType Class type) { + public @ObjectFactory FeatureTypeInfo featureTypeInfo(FeatureType source, @TargetType Class type) { return create(source.getId(), () -> new FeatureTypeInfoImpl((Catalog) null)); } - public @ObjectFactory CoverageInfo coverageInfo( - Coverage source, @TargetType Class type) { + public @ObjectFactory CoverageInfo coverageInfo(Coverage source, @TargetType Class type) { return create(source.getId(), () -> new CoverageInfoImpl((Catalog) null)); } - public @ObjectFactory WMSLayerInfo wmsLayerInfo( - WMSLayer source, @TargetType Class type) { + public @ObjectFactory WMSLayerInfo wmsLayerInfo(WMSLayer source, @TargetType Class type) { return create(source.getId(), () -> new WMSLayerInfoImpl((Catalog) null)); } - public @ObjectFactory WMTSLayerInfo wmtsLayerInfo( - WMTSLayer source, @TargetType Class type) { + public @ObjectFactory WMTSLayerInfo wmtsLayerInfo(WMTSLayer source, @TargetType Class type) { return create(source.getId(), () -> new WMTSLayerInfoImpl((Catalog) null)); } @@ -137,8 +127,7 @@ public class ObjectFacotries { return create(source.getId(), LayerInfoImpl::new); } - public @ObjectFactory LayerGroupInfo layerGroupInfo( - LayerGroup source, @TargetType Class type) { + public @ObjectFactory LayerGroupInfo layerGroupInfo(LayerGroup source, @TargetType Class type) { return create(source.getId(), LayerGroupInfoImpl::new); } diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/PublishedMapper.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/PublishedMapper.java index 946468e19..71e76b75b 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/PublishedMapper.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/PublishedMapper.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog.mapper; import lombok.Generated; - import org.geoserver.catalog.LayerGroupInfo; import org.geoserver.catalog.LayerInfo; import org.geoserver.catalog.PublishedInfo; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/ResourceMapper.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/ResourceMapper.java index 4c21d1d06..623de5aae 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/ResourceMapper.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/ResourceMapper.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog.mapper; import lombok.Generated; - import org.geoserver.catalog.CoverageInfo; import org.geoserver.catalog.FeatureTypeInfo; import org.geoserver.catalog.ResourceInfo; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/StoreMapper.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/StoreMapper.java index 8bddc00d3..d03b1e317 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/StoreMapper.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/StoreMapper.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog.mapper; import lombok.Generated; - import org.geoserver.catalog.CoverageStoreInfo; import org.geoserver.catalog.DataStoreInfo; import org.geoserver.catalog.StoreInfo; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/StyleMapper.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/StyleMapper.java index 9f228b918..a69818b29 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/StyleMapper.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/StyleMapper.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog.mapper; import lombok.Generated; - import org.geoserver.catalog.StyleInfo; import org.geoserver.jackson.databind.catalog.dto.Style; import org.mapstruct.AnnotateWith; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/WorkspaceMapper.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/WorkspaceMapper.java index 4451c7522..113e784e1 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/WorkspaceMapper.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/WorkspaceMapper.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog.mapper; import lombok.Generated; - import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.jackson.databind.catalog.dto.Workspace; import org.mapstruct.AnnotateWith; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/ConfigInfoDeserializer.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/ConfigInfoDeserializer.java index d873dc7df..71dc312f2 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/ConfigInfoDeserializer.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/ConfigInfoDeserializer.java @@ -5,18 +5,15 @@ package org.geoserver.jackson.databind.config; import lombok.NonNull; - import org.geoserver.catalog.Info; import org.geoserver.jackson.databind.catalog.dto.InfoDto; import org.geoserver.jackson.databind.config.dto.mapper.GeoServerConfigMapper; import org.geotools.jackson.databind.util.MapperDeserializer; import org.mapstruct.factory.Mappers; -public class ConfigInfoDeserializer - extends MapperDeserializer { +public class ConfigInfoDeserializer extends MapperDeserializer { - private static final GeoServerConfigMapper mapper = - Mappers.getMapper(GeoServerConfigMapper.class); + private static final GeoServerConfigMapper mapper = Mappers.getMapper(GeoServerConfigMapper.class); public ConfigInfoDeserializer(@NonNull Class from) { super(from, mapper::toInfo); diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/ConfigInfoSerializer.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/ConfigInfoSerializer.java index a04c3de3c..e40508368 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/ConfigInfoSerializer.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/ConfigInfoSerializer.java @@ -13,8 +13,7 @@ public class ConfigInfoSerializer extends MapperSerializer { private static final long serialVersionUID = -4772839273787523779L; - private static final GeoServerConfigMapper mapper = - Mappers.getMapper(GeoServerConfigMapper.class); + private static final GeoServerConfigMapper mapper = Mappers.getMapper(GeoServerConfigMapper.class); public ConfigInfoSerializer(Class type) { super(type, mapper::toDto); diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/GeoServerConfigModule.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/GeoServerConfigModule.java index b7b054025..16b5dedd9 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/GeoServerConfigModule.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/GeoServerConfigModule.java @@ -7,9 +7,8 @@ import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; - +import java.util.function.Function; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.Info; import org.geoserver.cog.CogSettings; import org.geoserver.cog.CogSettingsStore; @@ -41,8 +40,6 @@ import org.geotools.jackson.databind.util.MapperSerializer; import org.mapstruct.factory.Mappers; -import java.util.function.Function; - /** * Jackson {@link com.fasterxml.jackson.databind.Module} to handle GeoServer configuration objects * ({@link GeoServerInfo} and related) bindings. @@ -71,8 +68,7 @@ @Slf4j(topic = "org.geoserver.jackson.databind.config") public class GeoServerConfigModule extends SimpleModule { private static final long serialVersionUID = -8756800180255446679L; - static final GeoServerConfigMapper VALUE_MAPPER = - Mappers.getMapper(GeoServerConfigMapper.class); + static final GeoServerConfigMapper VALUE_MAPPER = Mappers.getMapper(GeoServerConfigMapper.class); public GeoServerConfigModule() { super(GeoServerConfigModule.class.getSimpleName(), new Version(1, 0, 0, null, null, null)); @@ -116,20 +112,12 @@ protected void registerValueSerializers() { CoverageAccess.class, VALUE_MAPPER::coverageAccessInfo); - addMapperSerializer( - JAIInfo.class, VALUE_MAPPER::jaiInfo, JaiDto.class, VALUE_MAPPER::jaiInfo); + addMapperSerializer(JAIInfo.class, VALUE_MAPPER::jaiInfo, JaiDto.class, VALUE_MAPPER::jaiInfo); - addMapperSerializer( - ContactInfo.class, - VALUE_MAPPER::contactInfo, - Contact.class, - VALUE_MAPPER::contactInfo); + addMapperSerializer(ContactInfo.class, VALUE_MAPPER::contactInfo, Contact.class, VALUE_MAPPER::contactInfo); addMapperSerializer( - CogSettings.class, - VALUE_MAPPER::cogSettings, - CogSettingsDto.class, - VALUE_MAPPER::cogSettings); + CogSettings.class, VALUE_MAPPER::cogSettings, CogSettingsDto.class, VALUE_MAPPER::cogSettings); addMapperSerializer( CogSettingsStore.class, VALUE_MAPPER::cogSettingsStore, @@ -142,14 +130,10 @@ protected void registerValueSerializers() { * @param DTO type */ private void addMapperSerializer( - Class type, - Function serializerMapper, - Class dtoType, - Function deserializerMapper) { + Class type, Function serializerMapper, Class dtoType, Function deserializerMapper) { MapperSerializer serializer = new MapperSerializer<>(type, serializerMapper); - MapperDeserializer deserializer = - new MapperDeserializer<>(dtoType, deserializerMapper); + MapperDeserializer deserializer = new MapperDeserializer<>(dtoType, deserializerMapper); super.addSerializer(type, serializer); super.addDeserializer(type, deserializer); } @@ -159,8 +143,7 @@ private void addSerializer(Class configInfoType) { super.addSerializer(configInfoType, serializer(configInfoType)); } - private void addDeserializer( - Class infoType, Class dtoType) { + private void addDeserializer(Class infoType, Class dtoType) { log.trace("registering deserializer for {}", infoType.getSimpleName()); super.addDeserializer(infoType, deserializer(dtoType)); } @@ -169,8 +152,7 @@ private ConfigInfoSerializer serializer(Class configInfoT return new ConfigInfoSerializer<>(configInfoType); } - private ConfigInfoDeserializer deserializer( - Class dtoType) { + private ConfigInfoDeserializer deserializer(Class dtoType) { return new ConfigInfoDeserializer<>(dtoType); } } diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/CogSettingsDto.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/CogSettingsDto.java index a6d60c499..90f29440f 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/CogSettingsDto.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/CogSettingsDto.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.config.dto; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.Data; /** */ diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/CogSettingsStoreDto.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/CogSettingsStoreDto.java index b504495cc..f6e814012 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/CogSettingsStoreDto.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/CogSettingsStoreDto.java @@ -6,7 +6,6 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.Data; import lombok.EqualsAndHashCode; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/ConfigInfoDto.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/ConfigInfoDto.java index a54e25d56..bb707646c 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/ConfigInfoDto.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/ConfigInfoDto.java @@ -6,7 +6,6 @@ import lombok.Data; import lombok.EqualsAndHashCode; - import org.geoserver.jackson.databind.catalog.dto.InfoDto; @EqualsAndHashCode(callSuper = true) diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/Contact.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/Contact.java index e0e3952b3..f8bf53df9 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/Contact.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/Contact.java @@ -4,12 +4,10 @@ */ package org.geoserver.jackson.databind.config.dto; +import java.util.Map; import lombok.Data; - import org.geoserver.config.ContactInfo; -import java.util.Map; - /** DTO for {@link ContactInfo} */ @Data public class Contact { diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/CoverageAccess.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/CoverageAccess.java index f9d2e0cb0..14b0d362f 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/CoverageAccess.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/CoverageAccess.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.config.dto; import lombok.Data; - import org.geoserver.config.CoverageAccessInfo; /** DTO for {@link CoverageAccessInfo} */ diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/GeoServer.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/GeoServer.java index e3717d004..139fcd653 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/GeoServer.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/GeoServer.java @@ -5,10 +5,8 @@ package org.geoserver.jackson.databind.config.dto; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.Data; import lombok.EqualsAndHashCode; - import org.geoserver.config.GeoServerInfo; import org.geoserver.jackson.databind.catalog.dto.MetadataMapDto; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/JaiDto.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/JaiDto.java index 1132ed512..11304aa1d 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/JaiDto.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/JaiDto.java @@ -4,12 +4,10 @@ */ package org.geoserver.jackson.databind.config.dto; +import java.util.Set; import lombok.Data; - import org.geoserver.config.JAIInfo; -import java.util.Set; - /** DTO for {@link JAIInfo} */ @Data public class JaiDto { diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/Logging.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/Logging.java index 1b59c6d3c..d7a42d3bb 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/Logging.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/Logging.java @@ -5,10 +5,8 @@ package org.geoserver.jackson.databind.config.dto; import com.fasterxml.jackson.annotation.JsonTypeName; - import lombok.Data; import lombok.EqualsAndHashCode; - import org.geoserver.config.LoggingInfo; /** DTO for {@link LoggingInfo} */ diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/Service.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/Service.java index 1b4138a18..b7b1212c6 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/Service.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/Service.java @@ -6,10 +6,13 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeName; - +import java.util.HashSet; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Set; import lombok.Data; import lombok.EqualsAndHashCode; - import org.geoserver.catalog.LayerInfo.WMSInterpolation; import org.geoserver.catalog.impl.AuthorityURL; import org.geoserver.catalog.impl.LayerIdentifier; @@ -29,12 +32,6 @@ import org.geotools.coverage.grid.io.OverviewPolicy; import org.geotools.jackson.databind.dto.NameDto; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Set; - /** DTO for {@link ServiceInfo} */ @JsonSubTypes({ @JsonSubTypes.Type(value = Service.WmsService.class), diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/Settings.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/Settings.java index c0fb295b5..212f0a7a7 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/Settings.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/Settings.java @@ -5,15 +5,12 @@ package org.geoserver.jackson.databind.config.dto; import com.fasterxml.jackson.annotation.JsonTypeName; - +import java.util.Locale; import lombok.Data; import lombok.EqualsAndHashCode; - import org.geoserver.config.SettingsInfo; import org.geoserver.jackson.databind.catalog.dto.MetadataMapDto; -import java.util.Locale; - /** DTO for {@link SettingsInfo} */ @EqualsAndHashCode(callSuper = true) @JsonTypeName("SettingsInfo") diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/mapper/GeoServerConfigMapper.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/mapper/GeoServerConfigMapper.java index 9041d7dbd..8da411064 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/mapper/GeoServerConfigMapper.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/mapper/GeoServerConfigMapper.java @@ -6,8 +6,9 @@ import static java.util.stream.Collectors.toCollection; +import java.util.ArrayList; +import java.util.List; import lombok.Generated; - import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.Info; import org.geoserver.cog.CogSettings; @@ -49,9 +50,6 @@ import org.mapstruct.Mapping; import org.mapstruct.factory.Mappers; -import java.util.ArrayList; -import java.util.List; - /** Mapper to/from GeoServer config objects and their respective DTO representations */ @Mapper(config = ConfigInfoMapperConfig.class) @AnnotateWith(value = Generated.class) @@ -156,9 +154,7 @@ default Service toDto(ServiceInfo info) { * {@code List} as is */ default List stringListToVersionList(List list) { - return list == null - ? null - : list.stream().map(Version::new).collect(toCollection(ArrayList::new)); + return list == null ? null : list.stream().map(Version::new).collect(toCollection(ArrayList::new)); } @Mapping(target = "clientProperties", ignore = true) diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/mapper/ObjectFacotries.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/mapper/ObjectFacotries.java index 627c954aa..09c19d389 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/mapper/ObjectFacotries.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/mapper/ObjectFacotries.java @@ -4,6 +4,7 @@ */ package org.geoserver.jackson.databind.config.dto.mapper; +import java.util.function.Supplier; import org.geoserver.catalog.Info; import org.geoserver.config.ContactInfo; import org.geoserver.config.CoverageAccessInfo; @@ -26,8 +27,6 @@ import org.mapstruct.ObjectFactory; import org.springframework.stereotype.Component; -import java.util.function.Supplier; - /** * Auto-wired object factory for config info interfaces, so the mapstruct code-generated mappers * know how to instantiate them diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/mapper/WPSMapper.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/mapper/WPSMapper.java index 9ba00fbb3..5742efd8f 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/mapper/WPSMapper.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/config/dto/mapper/WPSMapper.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.config.dto.mapper; import lombok.Generated; - import org.geoserver.jackson.databind.catalog.mapper.GeoServerValueObjectsMapper; import org.geoserver.jackson.databind.config.dto.Service; import org.geoserver.jackson.databind.config.dto.Service.WpsService.ProcessGroup; diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/mapper/InfoReferenceMapper.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/mapper/InfoReferenceMapper.java index 6e16a3034..31d2d6d36 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/mapper/InfoReferenceMapper.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/mapper/InfoReferenceMapper.java @@ -4,9 +4,9 @@ */ package org.geoserver.jackson.databind.mapper; +import java.util.Objects; import lombok.Generated; import lombok.NonNull; - import org.geoserver.catalog.CoverageStoreInfo; import org.geoserver.catalog.DataStoreInfo; import org.geoserver.catalog.FeatureTypeInfo; @@ -31,8 +31,6 @@ import org.mapstruct.Mapper; import org.mapstruct.Named; -import java.util.Objects; - @Mapper @AnnotateWith(value = Generated.class) public abstract class InfoReferenceMapper { @@ -113,11 +111,9 @@ public InfoReference infoToReference(final T info) { if (ClassMappings.STYLE.equals(type)) { StyleInfo s = (StyleInfo) info; MetadataMap metadata = s.getMetadata(); - boolean isRemoteStyle = - metadata != null - && Boolean.valueOf( - metadata.getOrDefault(StyleInfoImpl.IS_REMOTE, "false") - .toString()); + boolean isRemoteStyle = metadata != null + && Boolean.valueOf(metadata.getOrDefault(StyleInfoImpl.IS_REMOTE, "false") + .toString()); if (isRemoteStyle) { return null; } diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/mapper/PatchMapper.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/mapper/PatchMapper.java index 62f8db7cf..8c1775120 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/mapper/PatchMapper.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/mapper/PatchMapper.java @@ -4,9 +4,12 @@ */ package org.geoserver.jackson.databind.mapper; +import java.util.Collection; +import java.util.Map; +import java.util.function.Function; +import java.util.function.UnaryOperator; import lombok.Generated; import lombok.NonNull; - import org.geoserver.catalog.Info; import org.geoserver.catalog.plugin.Patch; import org.geoserver.catalog.plugin.PropertyDiff; @@ -24,11 +27,6 @@ import org.mapstruct.ReportingPolicy; import org.mapstruct.factory.Mappers; -import java.util.Collection; -import java.util.Map; -import java.util.function.Function; -import java.util.function.UnaryOperator; - @Mapper( unmappedTargetPolicy = ReportingPolicy.ERROR, uses = { @@ -93,8 +91,7 @@ private R valueToDto(final V value) { return dto; } - private Map copyOf( - Map fromMap, UnaryOperator valueMapper) { + private Map copyOf(Map fromMap, UnaryOperator valueMapper) { // create a Map of a type compatible with the original collection return PropertyDiff.PropertyDiffBuilder.copyOf(fromMap, valueMapper); } diff --git a/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/GeoServerCatalogModuleTest.java b/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/GeoServerCatalogModuleTest.java index 40cfff429..d4dee55e0 100644 --- a/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/GeoServerCatalogModuleTest.java +++ b/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/GeoServerCatalogModuleTest.java @@ -14,9 +14,15 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; - +import java.io.Serializable; +import java.lang.reflect.Proxy; +import java.util.Arrays; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.AttributeTypeInfo; import org.geoserver.catalog.AuthorityURLInfo; import org.geoserver.catalog.Catalog; @@ -83,18 +89,8 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; - import si.uom.SI; -import java.io.Serializable; -import java.lang.reflect.Proxy; -import java.util.Arrays; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; - /** * Verifies that all {@link CatalogInfo} can be sent over the wire and parsed back using jackson, * thanks to {@link GeoServerCatalogModule} jackcon-databind module @@ -134,8 +130,7 @@ protected void print(String logmsg, Object... args) { protected abstract ObjectMapper newObjectMapper(); @SuppressWarnings("unchecked") - private T catalogInfoRoundtripTest(final T orig) - throws JsonProcessingException { + private T catalogInfoRoundtripTest(final T orig) throws JsonProcessingException { ObjectWriter writer = objectMapper.writer(); writer = writer.withDefaultPrettyPrinter(); @@ -152,12 +147,9 @@ private T catalogInfoRoundtripTest(final T orig) CatalogInfo asCatalogInfo = objectMapper.readValue(encoded, CatalogInfo.class); assertNotNull(asCatalogInfo); // and also as its direct super-type, if it not CatalogInfo - if (orig instanceof StoreInfo) - assertNotNull(objectMapper.readValue(encoded, StoreInfo.class)); - if (orig instanceof ResourceInfo) - assertNotNull(objectMapper.readValue(encoded, ResourceInfo.class)); - if (orig instanceof PublishedInfo) - assertNotNull(objectMapper.readValue(encoded, PublishedInfo.class)); + if (orig instanceof StoreInfo) assertNotNull(objectMapper.readValue(encoded, StoreInfo.class)); + if (orig instanceof ResourceInfo) assertNotNull(objectMapper.readValue(encoded, ResourceInfo.class)); + if (orig instanceof PublishedInfo) assertNotNull(objectMapper.readValue(encoded, PublishedInfo.class)); // This is the client code's responsibility, the Deserializer returns "resolving proxy" // proxies for Info references @@ -242,26 +234,15 @@ void testFeatureType() throws Exception { ft.setTitle("Title"); ft.setAbstract("abstract"); - ft.setInternationalTitle( - data.faker() - .internationalString( - Locale.ENGLISH, - "english title", - Locale.CANADA_FRENCH, - "titre anglais")); - ft.setInternationalAbstract( - data.faker() - .internationalString( - Locale.ENGLISH, - "english abstract", - Locale.CANADA_FRENCH, - "résumé anglais")); + ft.setInternationalTitle(data.faker() + .internationalString(Locale.ENGLISH, "english title", Locale.CANADA_FRENCH, "titre anglais")); + ft.setInternationalAbstract(data.faker() + .internationalString(Locale.ENGLISH, "english abstract", Locale.CANADA_FRENCH, "résumé anglais")); catalogInfoRoundtripTest(ft); } - private List createTestAttributes(FeatureTypeInfo info) - throws SchemaException { + private List createTestAttributes(FeatureTypeInfo info) throws SchemaException { String typeSpec = "name:string,id:String,polygonProperty:Polygon:srid=32615,centroid:Point,url:java.net.URL,uuid:UUID"; SimpleFeatureType ft = DataUtilities.createType("TestType", typeSpec); @@ -307,36 +288,19 @@ void testLayerGroup() throws Exception { LayerGroupInfo lg = data.layerGroup1; lg.setTitle("LG Title"); lg.setAbstract("LG abstract"); - lg.setInternationalTitle( - data.faker() - .internationalString( - Locale.ENGLISH, - "english title", - Locale.CANADA_FRENCH, - "titre anglais")); - lg.setInternationalAbstract( - data.faker() - .internationalString( - Locale.ENGLISH, - "english abstract", - Locale.CANADA_FRENCH, - "résumé anglais")); + lg.setInternationalTitle(data.faker() + .internationalString(Locale.ENGLISH, "english title", Locale.CANADA_FRENCH, "titre anglais")); + lg.setInternationalAbstract(data.faker() + .internationalString(Locale.ENGLISH, "english abstract", Locale.CANADA_FRENCH, "résumé anglais")); LayerGroupStyle lgs = new LayerGroupStyleImpl(); lgs.setId("lgsid"); lgs.setTitle("Lgs Title"); lgs.setAbstract("Lgs Abstract"); lgs.setInternationalTitle( - data.faker() - .internationalString( - Locale.ITALIAN, "Italian title", Locale.FRENCH, "French title")); + data.faker().internationalString(Locale.ITALIAN, "Italian title", Locale.FRENCH, "French title")); lgs.setInternationalAbstract( - data.faker() - .internationalString( - Locale.ITALIAN, - "Italian abstract", - Locale.FRENCH, - "French abstract")); + data.faker().internationalString(Locale.ITALIAN, "Italian abstract", Locale.FRENCH, "French abstract")); lgs.setLayers(Arrays.asList(data.createLayer(data.coverageA, data.style1))); lgs.setStyles(Arrays.asList(data.createStyle("test-style"))); @@ -426,7 +390,8 @@ void testFilterWithModificationProxyInfoLiterals() throws JsonProcessingExceptio @SuppressWarnings("unchecked") private T forceModificationProxy(T info) { if (!Proxy.isProxyClass(info.getClass())) { - Class iface = ClassMappings.fromImpl(info.getClass()).getInterface(); + Class iface = + ClassMappings.fromImpl(info.getClass()).getInterface(); return (T) ModificationProxy.create(info, iface); } return info; @@ -544,8 +509,7 @@ void testValueCoordinateReferenceSystemCustomCRS() throws Exception { testValueCoordinateReferenceSystem(crs); } - private void testValueCoordinateReferenceSystem(CoordinateReferenceSystem crs) - throws Exception { + private void testValueCoordinateReferenceSystem(CoordinateReferenceSystem crs) throws Exception { CoordinateReferenceSystem decoded = roundTrip(crs, CoordinateReferenceSystem.class); assertTrue(CRS.equalsIgnoreMetadata(crs, decoded)); decoded = testFilterLiteral(crs); @@ -573,9 +537,7 @@ private void testValueWithEquals(final T value, Class type) throws Except void testValueNumberRange() throws Exception { testValueWithEquals(NumberRange.create(Double.MIN_VALUE, 0d), NumberRange.class); testValueWithEquals(NumberRange.create(0L, false, Long.MAX_VALUE, true), NumberRange.class); - testValueWithEquals( - NumberRange.create(Integer.MIN_VALUE, true, Integer.MAX_VALUE, false), - NumberRange.class); + testValueWithEquals(NumberRange.create(Integer.MIN_VALUE, true, Integer.MAX_VALUE, false), NumberRange.class); } @Test @@ -589,10 +551,8 @@ void testValueReferencedEnvelope() throws Exception { CoordinateReferenceSystem wgs84LatLon = CRS.decode("EPSG:4326", false); CoordinateReferenceSystem wgs84LonLat = CRS.decode("EPSG:4326", true); - testValueWithEquals( - new ReferencedEnvelope(-180, 180, -90, 90, wgs84LonLat), ReferencedEnvelope.class); - testValueWithEquals( - new ReferencedEnvelope(-90, 90, -180, 180, wgs84LatLon), ReferencedEnvelope.class); + testValueWithEquals(new ReferencedEnvelope(-180, 180, -90, 90, wgs84LonLat), ReferencedEnvelope.class); + testValueWithEquals(new ReferencedEnvelope(-90, 90, -180, 180, wgs84LatLon), ReferencedEnvelope.class); } @Test @@ -709,16 +669,14 @@ private void testQuery(Class clazz) { Query parsed = testValue(query, Query.class); assertNotNull(parsed); assertQueryEquals(query, parsed); - Filter filter = - equals("some.property.name", Arrays.asList("some literal 1", "some literal 2")); - query = - Query.valueOf( - type, - filter, - 2000, - 1000, - ff.sort("name", SortOrder.ASCENDING), - ff.sort("type", SortOrder.DESCENDING)); + Filter filter = equals("some.property.name", Arrays.asList("some literal 1", "some literal 2")); + query = Query.valueOf( + type, + filter, + 2000, + 1000, + ff.sort("name", SortOrder.ASCENDING), + ff.sort("type", SortOrder.DESCENDING)); parsed = testValue(query, Query.class); assertNotNull(parsed); assertQueryEquals(query, parsed); diff --git a/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/GeoServerCatalogModule_JsonTest.java b/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/GeoServerCatalogModule_JsonTest.java index 51a4b898b..05206ca3d 100644 --- a/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/GeoServerCatalogModule_JsonTest.java +++ b/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/GeoServerCatalogModule_JsonTest.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog; import com.fasterxml.jackson.databind.ObjectMapper; - import org.geotools.jackson.databind.util.ObjectMapperUtil; /** diff --git a/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/GeoServerCatalogModule_YamlTest.java b/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/GeoServerCatalogModule_YamlTest.java index 2beb43464..ef7e33176 100644 --- a/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/GeoServerCatalogModule_YamlTest.java +++ b/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/GeoServerCatalogModule_YamlTest.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog; import com.fasterxml.jackson.databind.ObjectMapper; - import org.geotools.jackson.databind.util.ObjectMapperUtil; /** diff --git a/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/PatchSerializationTest.java b/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/PatchSerializationTest.java index c33d66edc..b497ea619 100644 --- a/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/PatchSerializationTest.java +++ b/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/PatchSerializationTest.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog; import static com.google.common.collect.Lists.newArrayList; - import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -16,9 +15,16 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; - +import java.util.Arrays; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.function.Supplier; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.AttributeTypeInfo; import org.geoserver.catalog.AttributionInfo; import org.geoserver.catalog.Catalog; @@ -84,19 +90,8 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; - import si.uom.SI; -import java.util.Arrays; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.function.Supplier; - /** * Verifies that {@link Patch patches} can be JSON round-tripped. As a reference, it should cover as * much of {@link SharedMappers}, {@link GeoServerValueObjectsMapper}, {@link @@ -134,8 +129,7 @@ protected void print(String logmsg, Object... args) { protected abstract ObjectMapper newObjectMapper(); - private List createTestAttributes(FeatureTypeInfo info) - throws SchemaException { + private List createTestAttributes(FeatureTypeInfo info) throws SchemaException { String typeSpec = "name:string,id:String,polygonProperty:Polygon:srid=32615,centroid:Point,url:java.net.URL,uuid:UUID"; SimpleFeatureType ft = DataUtilities.createType("TestType", typeSpec); @@ -171,9 +165,7 @@ void arrayTypes_scalar() throws Exception { @Test void arrayTypes_non_scalar() throws Exception { - testPatch( - "ns_array", - new NamespaceInfo[] {data.namespaceA, data.namespaceB, data.namespaceC}); + testPatch("ns_array", new NamespaceInfo[] {data.namespaceA, data.namespaceB, data.namespaceC}); } @Test @@ -249,10 +241,7 @@ void layerInfo_references() throws Exception { layer.getStyles().add(s2); catalog.save(layer); - final Patch patch = - new Patch() - .with("styles", layer.getStyles()) - .with("defaultStyle", layer.getDefaultStyle()); + final Patch patch = new Patch().with("styles", layer.getStyles()).with("defaultStyle", layer.getDefaultStyle()); final Patch resolved = testPatch(patch); Set styles = resolved.get("styles").orElseThrow().value(); @@ -282,12 +271,11 @@ void layerInfo_value_object_properties() throws Exception { layer.getIdentifiers().add(data.faker().layerIdentifierInfo()); layer.getIdentifiers().add(data.faker().layerIdentifierInfo()); - Patch patch = - new Patch() - .with("legend", layer.getLegend()) - .with("attribution", layer.getAttribution()) - .with("authorityURLs", layer.getAuthorityURLs()) - .with("identifiers", layer.getIdentifiers()); + Patch patch = new Patch() + .with("legend", layer.getLegend()) + .with("attribution", layer.getAttribution()) + .with("authorityURLs", layer.getAuthorityURLs()) + .with("identifiers", layer.getIdentifiers()); final Patch roundtripped = roundtrip(patch); LegendInfo legend = roundtripped.get("legend").orElseThrow().value(); @@ -385,11 +373,7 @@ void version() throws Exception { @Test void version_list() throws Exception { - testPatch( - "version", - List.of( - new org.geotools.util.Version("1.0.1"), - new org.geotools.util.Version("1.0.2"))); + testPatch("version", List.of(new org.geotools.util.Version("1.0.1"), new org.geotools.util.Version("1.0.2"))); } @Test @@ -408,8 +392,9 @@ void coordinateReferenceSystem() throws Exception { CoordinateReferenceSystem crs = CRS.decode("EPSG:3857", longitudeFirst); Patch resolved = testPatchNoEquals(patch("crs", crs)); assertEquals(List.of("crs"), resolved.getPropertyNames()); - CoordinateReferenceSystem roundtripped = - resolved.getValue("crs").map(CoordinateReferenceSystem.class::cast).orElseThrow(); + CoordinateReferenceSystem roundtripped = resolved.getValue("crs") + .map(CoordinateReferenceSystem.class::cast) + .orElseThrow(); assertTrue(CRS.equalsIgnoreMetadata(crs, roundtripped)); } @@ -484,9 +469,7 @@ void modificationProxy_wmsInfo() throws Exception { @Test void modificationProxy_settingsInfo() throws Exception { - testPatch( - "settings", - forceProxy(data.faker().settingsInfo(data.workspaceA), SettingsInfo.class)); + testPatch("settings", forceProxy(data.faker().settingsInfo(data.workspaceA), SettingsInfo.class)); } /** Though ContactInfo is a value object, webui will save a ModificationProxy */ @@ -500,7 +483,8 @@ void modificationProxy_settingsInfo_with_proxy_contact_info() throws Exception { settingsProxy.setContact(contactProxy); final Patch sent = patch("settings", settingsProxy); - final SettingsInfo received = testPatchNoEquals(sent).get("settings").orElseThrow().value(); + final SettingsInfo received = + testPatchNoEquals(sent).get("settings").orElseThrow().value(); assertModificationProxy(workspaceProxy, received.getWorkspace()); ContactInfo contact = received.getContact(); assertNotAProxy(contact); @@ -709,8 +693,7 @@ void metadataMapWithCogSettings() throws Exception { metadataMapWithCogSettings(cog, cogs); } - protected void metadataMapWithCogSettings(CogSettings cog, CogSettingsStore cogs) - throws JsonProcessingException { + protected void metadataMapWithCogSettings(CogSettings cog, CogSettingsStore cogs) throws JsonProcessingException { MetadataMap mdm = new MetadataMap(Map.of("cogSettings", cog, "cogSettingsStore", cogs)); @@ -721,8 +704,7 @@ protected void metadataMapWithCogSettings(CogSettings cog, CogSettingsStore cogs (Map) patch.get("metadata").orElseThrow().getValue(); assertThat(decoded.get("cogSettings"), CoreMatchers.instanceOf(CogSettings.class)); - assertThat( - decoded.get("cogSettingsStore"), CoreMatchers.instanceOf(CogSettingsStore.class)); + assertThat(decoded.get("cogSettingsStore"), CoreMatchers.instanceOf(CogSettingsStore.class)); var c = (CogSettings) decoded.get("cogSettings"); var s = (CogSettingsStore) decoded.get("cogSettingsStore"); assertNotNull(c); @@ -790,11 +772,10 @@ private Patch roundtrip(Patch patch) throws JsonProcessingException { if (encodeByReference) { String typeName = typeName(roundtrippedValue); Class type = ProxyUtils.referenceTypeOf(patchValue).orElseThrow(); - Supplier desc = - () -> { - return "Patch value of type %s shall be encoded as reference, got value %s" - .formatted(type.getCanonicalName(), typeName); - }; + Supplier desc = () -> { + return "Patch value of type %s shall be encoded as reference, got value %s" + .formatted(type.getCanonicalName(), typeName); + }; assertThat(typeName).as(desc).isEqualTo("ResolvingProxy"); } else { assertNotAProxy(roundtrippedValue); @@ -832,26 +813,17 @@ private void assertCatalogSet(Info value) { protected void assertNotAProxy(Object value) { if (value instanceof Info info) { assertThat(ProxyUtils.isResolvingProxy(info)) - .as( - () -> - "%s should not be a ResolvingProxy: %s" - .formatted(info.getId(), typeName(info))) + .as(() -> "%s should not be a ResolvingProxy: %s".formatted(info.getId(), typeName(info))) .isFalse(); assertThat(ProxyUtils.isModificationProxy(info)) - .as( - () -> - "%s should not be a ModificationProxy: %s" - .formatted(info.getId(), typeName(info))) + .as(() -> "%s should not be a ModificationProxy: %s".formatted(info.getId(), typeName(info))) .isFalse(); } } protected I assertModificationProxy(I info) { assertThat(ProxyUtils.isModificationProxy(info)) - .as( - () -> - "%s should be a ModificationProxy, got %s" - .formatted(info.getId(), typeName(info))) + .as(() -> "%s should be a ModificationProxy, got %s".formatted(info.getId(), typeName(info))) .isTrue(); I real = ModificationProxy.unwrap(info); @@ -868,19 +840,14 @@ protected I assertModificationProxy(I expected, I actual) { protected void assertResolvingProxy(Info info) { assertThat(ProxyUtils.isResolvingProxy(info)) - .as( - () -> - "%s should be a ResolvingProxy, got %s" - .formatted(info.getId(), typeName(info))) + .as(() -> "%s should be a ResolvingProxy, got %s".formatted(info.getId(), typeName(info))) .isTrue(); } private void assertValueObject(Object valueObject, Class valueType) { if (valueObject instanceof Info info) { - Supplier msg = - () -> - "expected pure value object of type %s, got %s" - .formatted(valueType.getCanonicalName(), typeName(valueObject)); + Supplier msg = () -> "expected pure value object of type %s, got %s" + .formatted(valueType.getCanonicalName(), typeName(valueObject)); assertThat(ProxyUtils.isResolvingProxy(info)).as(msg).isFalse(); assertThat(ProxyUtils.isModificationProxy(info)).as(msg).isFalse(); } diff --git a/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/PatchSerialization_JsonTest.java b/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/PatchSerialization_JsonTest.java index 683fe0592..77d1c9738 100644 --- a/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/PatchSerialization_JsonTest.java +++ b/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/PatchSerialization_JsonTest.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog; import com.fasterxml.jackson.databind.ObjectMapper; - import org.geotools.jackson.databind.util.ObjectMapperUtil; class PatchSerialization_JsonTest extends PatchSerializationTest { diff --git a/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/PatchSerialization_YamlTest.java b/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/PatchSerialization_YamlTest.java index dee7b02ae..f25dfb47c 100644 --- a/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/PatchSerialization_YamlTest.java +++ b/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/catalog/PatchSerialization_YamlTest.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.catalog; import com.fasterxml.jackson.databind.ObjectMapper; - import org.geotools.jackson.databind.util.ObjectMapperUtil; class PatchSerialization_YamlTest extends PatchSerializationTest { diff --git a/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/config/GeoServerConfigModuleTest.java b/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/config/GeoServerConfigModuleTest.java index c6058116f..d1b29445e 100644 --- a/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/config/GeoServerConfigModuleTest.java +++ b/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/config/GeoServerConfigModuleTest.java @@ -9,10 +9,9 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectWriter; - +import java.util.Optional; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogTestData; import org.geoserver.catalog.Info; @@ -34,8 +33,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Optional; - /** * Verifies that all GeoServer config ({@link GeoServerInfo}, etc) object types can be sent over the * wire and parsed back using jackson, thanks to {@link GeoServerConfigModule} jackcon-databind @@ -68,15 +65,13 @@ protected void print(String logmsg, Object... args) { objectMapper = newObjectMapper(); catalog = new CatalogPlugin(); geoserver = new GeoServerImpl(); - testData = - CatalogTestData.initialized(() -> catalog, () -> geoserver) - .initConfig(false) - .initialize(); + testData = CatalogTestData.initialized(() -> catalog, () -> geoserver) + .initConfig(false) + .initialize(); proxyResolver = new ProxyUtils(() -> catalog, Optional.of(geoserver)); } - private void roundtripTest(@NonNull final T orig) - throws JsonProcessingException { + private void roundtripTest(@NonNull final T orig) throws JsonProcessingException { ObjectWriter writer = objectMapper.writer(); writer = writer.withDefaultPrettyPrinter(); String encoded = writer.writeValueAsString(orig); diff --git a/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/config/GeoSeververConfigModule_JsonTest.java b/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/config/GeoSeververConfigModule_JsonTest.java index fc81bba4c..e70ed9aa0 100644 --- a/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/config/GeoSeververConfigModule_JsonTest.java +++ b/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/config/GeoSeververConfigModule_JsonTest.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.config; import com.fasterxml.jackson.databind.ObjectMapper; - import org.geotools.jackson.databind.util.ObjectMapperUtil; /** diff --git a/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/config/GeoSeververConfigModule_YamlTest.java b/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/config/GeoSeververConfigModule_YamlTest.java index a2b4a0a79..1e44b8e78 100644 --- a/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/config/GeoSeververConfigModule_YamlTest.java +++ b/src/catalog/jackson-bindings/geoserver/src/test/java/org/geoserver/jackson/databind/config/GeoSeververConfigModule_YamlTest.java @@ -5,7 +5,6 @@ package org.geoserver.jackson.databind.config; import com.fasterxml.jackson.databind.ObjectMapper; - import org.geotools.jackson.databind.util.ObjectMapperUtil; /** diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/dto/NumberRangeDto.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/dto/NumberRangeDto.java index 1c68a32a0..9697417c4 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/dto/NumberRangeDto.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/dto/NumberRangeDto.java @@ -5,7 +5,6 @@ package org.geotools.jackson.databind.dto; import lombok.Data; - import org.geotools.util.NumberRange; /** diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/GeoToolsFilterModule.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/GeoToolsFilterModule.java index ac6c7effc..7174022a0 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/GeoToolsFilterModule.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/GeoToolsFilterModule.java @@ -9,9 +9,10 @@ import com.fasterxml.jackson.databind.JsonSerializer; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; - +import java.util.Locale; +import java.util.Map; +import java.util.function.Function; import lombok.extern.slf4j.Slf4j; - import org.geotools.api.filter.Filter; import org.geotools.api.filter.capability.FunctionName; import org.geotools.api.filter.expression.Expression; @@ -36,10 +37,6 @@ import org.locationtech.jts.geom.Geometry; import org.mapstruct.factory.Mappers; -import java.util.Locale; -import java.util.Map; -import java.util.function.Function; - /** * Jackson {@link com.fasterxml.jackson.databind.Module} to handle GeoTools {@link Filter} and * {@link Expression} bindings. @@ -76,8 +73,7 @@ public class GeoToolsFilterModule extends SimpleModule { private static final FilterMapper FILTERS = Mappers.getMapper(FilterMapper.class); private static final ExpressionMapper EXPRESSIONS = Mappers.getMapper(ExpressionMapper.class); - private static final GeoToolsValueMappers VALUES = - Mappers.getMapper(GeoToolsValueMappers.class); + private static final GeoToolsValueMappers VALUES = Mappers.getMapper(GeoToolsValueMappers.class); public GeoToolsFilterModule() { super(GeoToolsFilterModule.class.getSimpleName(), new Version(1, 0, 0, null, null, null)); @@ -93,16 +89,10 @@ public GeoToolsFilterModule() { addSerializer(Literal.class, new LiteralSerializer(), new LiteralDeserializer()); addMapperSerializer( - Filter.class, - FILTERS::map, - org.geotools.jackson.databind.filter.dto.Filter.class, - FILTERS::map); + Filter.class, FILTERS::map, org.geotools.jackson.databind.filter.dto.Filter.class, FILTERS::map); addMapperSerializer( - SortBy.class, - FILTERS::map, - org.geotools.jackson.databind.filter.dto.SortBy.class, - FILTERS::map); + SortBy.class, FILTERS::map, org.geotools.jackson.databind.filter.dto.SortBy.class, FILTERS::map); addMapperSerializer( FunctionName.class, @@ -113,8 +103,7 @@ public GeoToolsFilterModule() { addCustomLiteralValueSerializers(); } - private GeoToolsFilterModule addSerializer( - Class type, JsonSerializer ser, JsonDeserializer deser) { + private GeoToolsFilterModule addSerializer(Class type, JsonSerializer ser, JsonDeserializer deser) { super.addSerializer(type, ser); super.addDeserializer(type, deser); return this; @@ -123,34 +112,20 @@ private GeoToolsFilterModule addSerializer( /** */ private void addCustomLiteralValueSerializers() { addMapperSerializer( - CoordinateReferenceSystem.class, - VALUES::crs, - org.geotools.jackson.databind.dto.CRS.class, - VALUES::crs); + CoordinateReferenceSystem.class, VALUES::crs, org.geotools.jackson.databind.dto.CRS.class, VALUES::crs); addMapperSerializer( - CoordinateReferenceSystem.class, - VALUES::crs, - org.geotools.jackson.databind.dto.CRS.class, - VALUES::crs); + CoordinateReferenceSystem.class, VALUES::crs, org.geotools.jackson.databind.dto.CRS.class, VALUES::crs); addMapperSerializer( ReferencedEnvelope.class, VALUES::referencedEnvelope, org.geotools.jackson.databind.dto.Envelope.class, VALUES::referencedEnvelope); - addMapperSerializer( - java.awt.Color.class, - VALUES::awtColorToString, - String.class, - VALUES::stringToAwtColor); - addMapperSerializer( - org.geotools.api.feature.type.Name.class, VALUES::map, NameDto.class, VALUES::map); + addMapperSerializer(java.awt.Color.class, VALUES::awtColorToString, String.class, VALUES::stringToAwtColor); + addMapperSerializer(org.geotools.api.feature.type.Name.class, VALUES::map, NameDto.class, VALUES::map); addMapperSerializer( - org.geotools.util.Version.class, - VALUES::versionToDto, - VersionDto.class, - VALUES::dtoToVersion); + org.geotools.util.Version.class, VALUES::versionToDto, VersionDto.class, VALUES::dtoToVersion); addMapperSerializer( InternationalString.class, @@ -159,14 +134,9 @@ private void addCustomLiteralValueSerializers() { VALUES::dtoToInternationalString); addMapperSerializer( - NumberRange.class, - VALUES::numberRangeToDto, - NumberRangeDto.class, - VALUES::dtoToNumberRange); - addMapperSerializer( - Measure.class, VALUES::measureToString, String.class, VALUES::stringToMeasure); - addMapperSerializer( - Locale.class, VALUES::localeToString, String.class, VALUES::stringToLocale); + NumberRange.class, VALUES::numberRangeToDto, NumberRangeDto.class, VALUES::dtoToNumberRange); + addMapperSerializer(Measure.class, VALUES::measureToString, String.class, VALUES::stringToMeasure); + addMapperSerializer(Locale.class, VALUES::localeToString, String.class, VALUES::stringToLocale); } /** @@ -175,14 +145,10 @@ private void addCustomLiteralValueSerializers() { * @return */ private GeoToolsFilterModule addMapperSerializer( - Class type, - Function serializerMapper, - Class dtoType, - Function deserializerMapper) { + Class type, Function serializerMapper, Class dtoType, Function deserializerMapper) { MapperSerializer serializer = new MapperSerializer<>(type, serializerMapper); - MapperDeserializer deserializer = - new MapperDeserializer<>(dtoType, deserializerMapper); + MapperDeserializer deserializer = new MapperDeserializer<>(dtoType, deserializerMapper); return addSerializer(type, serializer, deserializer); } } diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/Expression.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/Expression.java index d41941bbc..2f3afacc8 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/Expression.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/Expression.java @@ -7,16 +7,14 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; - +import java.util.ArrayList; +import java.util.List; +import java.util.Map; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import lombok.experimental.Accessors; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonSubTypes({ @JsonSubTypes.Type(value = Expression.PropertyName.class, name = "PropertyName"), diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/Filter.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/Filter.java index 0275e894f..e2b65270c 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/Filter.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/Filter.java @@ -6,16 +6,14 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; - +import java.util.Date; +import java.util.List; +import java.util.Set; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.ToString; import lombok.experimental.Accessors; -import java.util.Date; -import java.util.List; -import java.util.Set; - @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonSubTypes({ @JsonSubTypes.Type(value = Filter.Id.class, name = "Id"), @@ -176,21 +174,15 @@ public static class PropertyIsLike extends MultiValuedFilter { } @JsonSubTypes({ - @JsonSubTypes.Type( - value = BinaryComparisonOperator.PropertyIsEqualTo.class, - name = "PropertyIsEqualTo"), - @JsonSubTypes.Type( - value = BinaryComparisonOperator.PropertyIsNotEqualTo.class, - name = "PropertyIsNotEqualTo"), + @JsonSubTypes.Type(value = BinaryComparisonOperator.PropertyIsEqualTo.class, name = "PropertyIsEqualTo"), + @JsonSubTypes.Type(value = BinaryComparisonOperator.PropertyIsNotEqualTo.class, name = "PropertyIsNotEqualTo"), @JsonSubTypes.Type( value = BinaryComparisonOperator.PropertyIsGreaterThan.class, name = "PropertyIsGreaterThan"), @JsonSubTypes.Type( value = BinaryComparisonOperator.PropertyIsGreaterThanOrEqualTo.class, name = "PropertyIsGreaterThanOrEqualTo"), - @JsonSubTypes.Type( - value = BinaryComparisonOperator.PropertyIsLessThan.class, - name = "PropertyIsLessThan"), + @JsonSubTypes.Type(value = BinaryComparisonOperator.PropertyIsLessThan.class, name = "PropertyIsLessThan"), @JsonSubTypes.Type( value = BinaryComparisonOperator.PropertyIsLessThanOrEqualTo.class, name = "PropertyIsLessThanOrEqualTo") @@ -232,9 +224,7 @@ public static class PropertyIsNotEqualTo extends BinaryComparisonOperator {} @JsonSubTypes.Type(value = Filter.BinarySpatialOperator.Crosses.class, name = "Crosses"), @JsonSubTypes.Type(value = Filter.BinarySpatialOperator.Disjoint.class, name = "Disjoint"), @JsonSubTypes.Type(value = Filter.BinarySpatialOperator.Equals.class, name = "Equals"), - @JsonSubTypes.Type( - value = Filter.BinarySpatialOperator.Intersects.class, - name = "Intersects"), + @JsonSubTypes.Type(value = Filter.BinarySpatialOperator.Intersects.class, name = "Intersects"), @JsonSubTypes.Type(value = Filter.BinarySpatialOperator.Overlaps.class, name = "Overlaps"), @JsonSubTypes.Type(value = Filter.BinarySpatialOperator.Touches.class, name = "Touches"), @JsonSubTypes.Type(value = Filter.BinarySpatialOperator.Within.class, name = "Within"), @@ -282,9 +272,7 @@ public static class Touches extends BinarySpatialOperator {} public static class Within extends BinarySpatialOperator {} @JsonSubTypes({ - @JsonSubTypes.Type( - value = Filter.BinarySpatialOperator.DWithin.class, - name = "DWithin"), + @JsonSubTypes.Type(value = Filter.BinarySpatialOperator.DWithin.class, name = "DWithin"), @JsonSubTypes.Type(value = Filter.BinarySpatialOperator.Beyond.class, name = "Beyond") }) @Data @@ -305,9 +293,7 @@ public static class DWithin extends DistanceBufferOperator {} @JsonSubTypes({ @JsonSubTypes.Type(value = Filter.BinaryTemporalOperator.After.class, name = "After"), - @JsonSubTypes.Type( - value = Filter.BinaryTemporalOperator.AnyInteracts.class, - name = "AnyInteracts"), + @JsonSubTypes.Type(value = Filter.BinaryTemporalOperator.AnyInteracts.class, name = "AnyInteracts"), @JsonSubTypes.Type(value = BinaryTemporalOperator.Before.class, name = "Before"), @JsonSubTypes.Type(value = BinaryTemporalOperator.Begins.class, name = "Begins"), @JsonSubTypes.Type(value = BinaryTemporalOperator.BegunBy.class, name = "BegunBy"), @@ -316,9 +302,7 @@ public static class DWithin extends DistanceBufferOperator {} @JsonSubTypes.Type(value = BinaryTemporalOperator.Ends.class, name = "Ends"), @JsonSubTypes.Type(value = BinaryTemporalOperator.Meets.class, name = "Meets"), @JsonSubTypes.Type(value = BinaryTemporalOperator.MetBy.class, name = "MetBy"), - @JsonSubTypes.Type( - value = BinaryTemporalOperator.OverlappedBy.class, - name = "OverlappedBy"), + @JsonSubTypes.Type(value = BinaryTemporalOperator.OverlappedBy.class, name = "OverlappedBy"), @JsonSubTypes.Type(value = BinaryTemporalOperator.TContains.class, name = "TContains"), @JsonSubTypes.Type(value = BinaryTemporalOperator.TOverlaps.class, name = "TOverlaps"), @JsonSubTypes.Type(value = BinaryTemporalOperator.TEquals.class, name = "TEquals") diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/Literal.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/Literal.java index 9bce6a7f6..5d0b4f937 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/Literal.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/Literal.java @@ -4,11 +4,10 @@ */ package org.geotools.jackson.databind.filter.dto; -import lombok.Data; -import lombok.experimental.Accessors; - import java.util.Arrays; import java.util.Objects; +import lombok.Data; +import lombok.experimental.Accessors; /** * @see LiteralSerializer @@ -53,8 +52,7 @@ public static boolean valueEquals(final Object v1, final Object v2) { case "long" -> Arrays.equals((long[]) v1, (long[]) v2); case "float" -> Arrays.equals((float[]) v1, (float[]) v2); case "double" -> Arrays.equals((double[]) v1, (double[]) v2); - default -> throw new IllegalArgumentException( - "Unexpected value: %s".formatted(componentType)); + default -> throw new IllegalArgumentException("Unexpected value: %s".formatted(componentType)); }; } else { Object[] a1 = (Object[]) v1; diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/LiteralDeserializer.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/LiteralDeserializer.java index bb6ef89fc..ac8adbb54 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/LiteralDeserializer.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/LiteralDeserializer.java @@ -4,20 +4,15 @@ */ package org.geotools.jackson.databind.filter.dto; +import static java.util.Objects.requireNonNull; import static org.geotools.jackson.databind.filter.dto.LiteralSerializer.COLLECTION_CONTENT_TYPE_KEY; import static org.geotools.jackson.databind.filter.dto.LiteralSerializer.TYPE_KEY; import static org.geotools.jackson.databind.filter.dto.LiteralSerializer.VALUE_KEY; -import static java.util.Objects.requireNonNull; - import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; - -import org.geotools.jackson.databind.filter.mapper.GeoToolsValueMappers; -import org.mapstruct.factory.Mappers; - import java.io.IOException; import java.lang.reflect.Array; import java.util.ArrayList; @@ -28,6 +23,8 @@ import java.util.List; import java.util.Map; import java.util.Set; +import org.geotools.jackson.databind.filter.mapper.GeoToolsValueMappers; +import org.mapstruct.factory.Mappers; /** * @@ -106,8 +103,7 @@ private Object readMap(JsonParser parser, DeserializationContext ctxt) throws IO } private Collection readCollection( - Class type, Class contentType, JsonParser parser, DeserializationContext ctxt) - throws IOException { + Class type, Class contentType, JsonParser parser, DeserializationContext ctxt) throws IOException { JsonToken nextToken = parser.nextToken(); expect(nextToken, JsonToken.START_ARRAY); @@ -118,8 +114,7 @@ private Collection readCollection( return value; } - private Object readArray(Class arrayType, JsonParser parser, DeserializationContext ctxt) - throws IOException { + private Object readArray(Class arrayType, JsonParser parser, DeserializationContext ctxt) throws IOException { JsonToken nextToken = parser.nextToken(); Object value; if (byte[].class.equals(arrayType)) { @@ -142,8 +137,7 @@ private Object readArray(Class arrayType, JsonParser parser, DeserializationC } @SuppressWarnings("unchecked") - private List readList( - Class contentType, JsonParser parser, DeserializationContext ctxt) + private List readList(Class contentType, JsonParser parser, DeserializationContext ctxt) throws IOException { JsonToken nextToken = parser.currentToken(); @@ -180,8 +174,7 @@ private Class readType(JsonParser parser) throws IOException { } nextToken = parser.nextToken(); if (JsonToken.END_OBJECT != nextToken) { - throw new IllegalArgumentException( - "Expected END_OBJECT, got %s".formatted(nextToken)); + throw new IllegalArgumentException("Expected END_OBJECT, got %s".formatted(nextToken)); } return null; } @@ -198,15 +191,13 @@ private Class readType(JsonParser parser) throws IOException { */ private void expectFieldName(String value, String expected) { if (!expected.equals(value)) - throw new IllegalStateException( - "Expected field name '%s', got '%s'".formatted(expected, value)); + throw new IllegalStateException("Expected field name '%s', got '%s'".formatted(expected, value)); } private void expect(JsonToken current, JsonToken... expectedOneOf) { for (JsonToken expected : expectedOneOf) { if (current == expected) return; } - throw new IllegalStateException( - "Expected one of %s got %s".formatted(Arrays.toString(expectedOneOf), current)); + throw new IllegalStateException("Expected one of %s got %s".formatted(Arrays.toString(expectedOneOf), current)); } } diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/LiteralSerializer.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/LiteralSerializer.java index eef51a182..3d8d6fa43 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/LiteralSerializer.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/dto/LiteralSerializer.java @@ -15,12 +15,6 @@ import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.ser.std.StdSerializer; import com.fasterxml.jackson.databind.type.TypeFactory; - -import lombok.NonNull; - -import org.geotools.jackson.databind.filter.mapper.GeoToolsValueMappers; -import org.mapstruct.factory.Mappers; - import java.io.IOException; import java.lang.reflect.Array; import java.util.Collection; @@ -29,6 +23,9 @@ import java.util.Objects; import java.util.Set; import java.util.function.UnaryOperator; +import lombok.NonNull; +import org.geotools.jackson.databind.filter.mapper.GeoToolsValueMappers; +import org.mapstruct.factory.Mappers; /** * @@ -58,33 +55,28 @@ public class LiteralSerializer extends StdSerializer { private static final long serialVersionUID = 1L; - private transient GeoToolsValueMappers classNameMapper = - Mappers.getMapper(GeoToolsValueMappers.class); + private transient GeoToolsValueMappers classNameMapper = Mappers.getMapper(GeoToolsValueMappers.class); public LiteralSerializer() { super(Literal.class); } private GeoToolsValueMappers classNameMapper() { - if (classNameMapper == null) - classNameMapper = Mappers.getMapper(GeoToolsValueMappers.class); + if (classNameMapper == null) classNameMapper = Mappers.getMapper(GeoToolsValueMappers.class); return classNameMapper; } @Override - public void serializeWithType( - Literal value, JsonGenerator g, SerializerProvider provider, TypeSerializer typeSer) + public void serializeWithType(Literal value, JsonGenerator g, SerializerProvider provider, TypeSerializer typeSer) throws IOException { - WritableTypeId typeIdDef = - typeSer.writeTypePrefix(g, typeSer.typeId(value, JsonToken.VALUE_STRING)); + WritableTypeId typeIdDef = typeSer.writeTypePrefix(g, typeSer.typeId(value, JsonToken.VALUE_STRING)); serialize(value, g, provider); typeSer.writeTypeSuffix(g, typeIdDef); } @Override - public void serialize(Literal literal, JsonGenerator gen, SerializerProvider serializers) - throws IOException { + public void serialize(Literal literal, JsonGenerator gen, SerializerProvider serializers) throws IOException { final Object value = literal.getValue(); @@ -93,8 +85,7 @@ public void serialize(Literal literal, JsonGenerator gen, SerializerProvider ser gen.writeEndObject(); } - protected void writeValue(final Object value, JsonGenerator gen, SerializerProvider provider) - throws IOException { + protected void writeValue(final Object value, JsonGenerator gen, SerializerProvider provider) throws IOException { if (value == null) { gen.writeNullField(VALUE_KEY); } else { @@ -102,8 +93,7 @@ protected void writeValue(final Object value, JsonGenerator gen, SerializerProvi } } - private void writeNonNullValue( - final @NonNull Object value, JsonGenerator gen, SerializerProvider provider) + private void writeNonNullValue(final @NonNull Object value, JsonGenerator gen, SerializerProvider provider) throws IOException { Class type = value.getClass(); @@ -119,10 +109,7 @@ private void writeNonNullValue( } private void serializeNonCollectionObject( - final @NonNull Object value, - JsonGenerator gen, - SerializerProvider provider, - Class type) + final @NonNull Object value, JsonGenerator gen, SerializerProvider provider, Class type) throws IOException { if (type.isAnonymousClass()) { @@ -130,22 +117,20 @@ private void serializeNonCollectionObject( if (enclosingClass.isEnum()) { type = enclosingClass; } else { - throw new IllegalArgumentException( - "Unable to encode anonymous class %s".formatted(type.getName())); + throw new IllegalArgumentException("Unable to encode anonymous class %s".formatted(type.getName())); } } JsonSerializer valueSerializer = findValueSerializer(provider, type); final Class handledType = valueSerializer.handledType(); - String typeName = - classNameMapper().classToCanonicalName(type.isEnum() ? type : handledType); + String typeName = classNameMapper().classToCanonicalName(type.isEnum() ? type : handledType); gen.writeStringField(TYPE_KEY, typeName); gen.writeFieldName(VALUE_KEY); valueSerializer.serialize(value, gen, provider); } - protected JsonSerializer findValueSerializer( - SerializerProvider provider, final Class type) throws JsonMappingException { + protected JsonSerializer findValueSerializer(SerializerProvider provider, final Class type) + throws JsonMappingException { TypeFactory typeFactory = provider.getTypeFactory(); JavaType javaType = typeFactory.constructType(type); return provider.findValueSerializer(javaType); @@ -164,8 +149,7 @@ private void writeMap(Map value, JsonGenerator gen) throws IOException { gen.writeEndObject(); } - private void writeArray(Object array, JsonGenerator gen, SerializerProvider provider) - throws IOException { + private void writeArray(Object array, JsonGenerator gen, SerializerProvider provider) throws IOException { // e.g. int[], java.lang.String[], etc. final String arrayTypeStr = classNameMapper().classToCanonicalName(array.getClass()); gen.writeStringField(TYPE_KEY, arrayTypeStr); @@ -186,8 +170,7 @@ private void writeArray(Object array, JsonGenerator gen, SerializerProvider prov } } - private void writeCollection( - Collection collection, JsonGenerator gen, SerializerProvider provider) + private void writeCollection(Collection collection, JsonGenerator gen, SerializerProvider provider) throws IOException { final Class contentType = findContentType(collection, provider); @@ -195,8 +178,7 @@ private void writeCollection( final UnaryOperator valueMapper = Literal.class.equals(contentType) ? Literal::valueOf : UnaryOperator.identity(); - gen.writeStringField( - TYPE_KEY, classNameMapper().classToCanonicalName(collectionType(collection))); + gen.writeStringField(TYPE_KEY, classNameMapper().classToCanonicalName(collectionType(collection))); if (null != contentType) { String singleContentTypeValue = classNameMapper.classToCanonicalName(contentType); @@ -214,12 +196,11 @@ private void writeCollection( private Class findContentType(Collection collection, SerializerProvider provider) throws JsonMappingException { - List types = - collection.stream() - .filter(Objects::nonNull) - .map(Object::getClass) - .distinct() - .toList(); + List types = collection.stream() + .filter(Objects::nonNull) + .map(Object::getClass) + .distinct() + .toList(); if (types.isEmpty()) return null; // all null values or empty collection if (types.size() == 1) { diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/DtoToFilterMapper.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/DtoToFilterMapper.java index 1e75fa626..fc32c605c 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/DtoToFilterMapper.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/DtoToFilterMapper.java @@ -4,8 +4,13 @@ */ package org.geotools.jackson.databind.filter.mapper; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Collections; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; import lombok.Generated; - import org.geotools.api.filter.And; import org.geotools.api.filter.ExcludeFilter; import org.geotools.api.filter.FilterFactory; @@ -90,13 +95,6 @@ import org.mapstruct.Mapper; import org.mapstruct.factory.Mappers; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Collections; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - @Mapper(config = FilterMapperConfig.class) @AnnotateWith(value = Generated.class) abstract class DtoToFilterMapper { @@ -216,8 +214,7 @@ Identifier toIdentifier(Filter.Id.FeatureId dto) { } private T toBinaryOperator( - Filter.BinaryOperator dto, - TriFunction factory) { + Filter.BinaryOperator dto, TriFunction factory) { Expression e1 = exp(dto.getExpression1()); Expression e2 = exp(dto.getExpression2()); @@ -225,10 +222,9 @@ private T toBinaryOperator( return factory.apply(e1, e2, matchAction); } - private - T toBinaryComparisonOperator( - Filter.BinaryComparisonOperator dto, - QuadFunction factory) { + private T toBinaryComparisonOperator( + Filter.BinaryComparisonOperator dto, + QuadFunction factory) { Expression e1 = exp(dto.getExpression1()); Expression e2 = exp(dto.getExpression2()); @@ -290,60 +286,42 @@ public DWithin toFilter(Filter.BinarySpatialOperator.DWithin dto) { private static class PropertyEquals extends IsEqualsToImpl { public PropertyEquals( - Expression expression1, - Expression expression2, - boolean matchCase, - MatchAction matchAction) { + Expression expression1, Expression expression2, boolean matchCase, MatchAction matchAction) { super(expression1, expression2, matchCase, matchAction); } } private static class PropertyNotEquals extends IsNotEqualToImpl { public PropertyNotEquals( - Expression expression1, - Expression expression2, - boolean matchCase, - MatchAction matchAction) { + Expression expression1, Expression expression2, boolean matchCase, MatchAction matchAction) { super(expression1, expression2, matchCase, matchAction); } } private static class PropertyLessThan extends IsLessThenImpl { public PropertyLessThan( - Expression expression1, - Expression expression2, - boolean matchCase, - MatchAction matchAction) { + Expression expression1, Expression expression2, boolean matchCase, MatchAction matchAction) { super(expression1, expression2, matchCase, matchAction); } } private static class PropertyLessThanOrEquals extends IsLessThenOrEqualToImpl { public PropertyLessThanOrEquals( - Expression expression1, - Expression expression2, - boolean matchCase, - MatchAction matchAction) { + Expression expression1, Expression expression2, boolean matchCase, MatchAction matchAction) { super(expression1, expression2, matchCase, matchAction); } } private static class PropertyGreaterThan extends IsGreaterThanImpl { public PropertyGreaterThan( - Expression expression1, - Expression expression2, - boolean matchCase, - MatchAction matchAction) { + Expression expression1, Expression expression2, boolean matchCase, MatchAction matchAction) { super(expression1, expression2, matchAction); } } private static class PropertyGreaterThanOrEqual extends IsGreaterThanOrEqualToImpl { public PropertyGreaterThanOrEqual( - Expression expression1, - Expression expression2, - boolean matchCase, - MatchAction matchAction) { + Expression expression1, Expression expression2, boolean matchCase, MatchAction matchAction) { super(expression1, expression2, matchCase, matchAction); } } @@ -356,8 +334,7 @@ public PropertyIsNotEqualTo toFilter(Filter.BinaryComparisonOperator.PropertyIsN return toBinaryComparisonOperator(dto, PropertyNotEquals::new); } - public PropertyIsLessThanOrEqualTo toFilter( - Filter.BinaryComparisonOperator.PropertyIsLessThanOrEqualTo dto) { + public PropertyIsLessThanOrEqualTo toFilter(Filter.BinaryComparisonOperator.PropertyIsLessThanOrEqualTo dto) { return toBinaryComparisonOperator(dto, PropertyLessThanOrEquals::new); } @@ -365,13 +342,11 @@ public PropertyIsLessThan toFilter(Filter.BinaryComparisonOperator.PropertyIsLes return toBinaryComparisonOperator(dto, PropertyLessThan::new); } - public PropertyIsGreaterThanOrEqualTo toFilter( - Filter.BinaryComparisonOperator.PropertyIsGreaterThanOrEqualTo dto) { + public PropertyIsGreaterThanOrEqualTo toFilter(Filter.BinaryComparisonOperator.PropertyIsGreaterThanOrEqualTo dto) { return toBinaryComparisonOperator(dto, PropertyGreaterThanOrEqual::new); } - public PropertyIsGreaterThan toFilter( - Filter.BinaryComparisonOperator.PropertyIsGreaterThan dto) { + public PropertyIsGreaterThan toFilter(Filter.BinaryComparisonOperator.PropertyIsGreaterThan dto) { return toBinaryComparisonOperator(dto, PropertyGreaterThan::new); } diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/ExpressionFactory.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/ExpressionFactory.java index 03bf2f633..a07dd1e25 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/ExpressionFactory.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/ExpressionFactory.java @@ -16,8 +16,7 @@ public class ExpressionFactory { private final FilterFactory factory = CommonFactoryFinder.getFilterFactory(); - public @ObjectFactory org.geotools.api.filter.expression.PropertyName propertyName( - PropertyName source) { + public @ObjectFactory org.geotools.api.filter.expression.PropertyName propertyName(PropertyName source) { GeoToolsValueMappers values = Mappers.getMapper(GeoToolsValueMappers.class); String localName = source.getPropertyName(); NamespaceSupport namespaceSupport = values.map(source.getNamespaceContext()); diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/ExpressionMapper.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/ExpressionMapper.java index fece6ce9a..a6766900e 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/ExpressionMapper.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/ExpressionMapper.java @@ -4,8 +4,8 @@ */ package org.geotools.jackson.databind.filter.mapper; +import java.util.List; import lombok.Generated; - import org.geotools.api.filter.expression.ExpressionVisitor; import org.geotools.api.filter.expression.NilExpression; import org.geotools.factory.CommonFactoryFinder; @@ -25,8 +25,6 @@ import org.mapstruct.ObjectFactory; import org.mapstruct.ReportingPolicy; -import java.util.List; - @Mapper( componentModel = "default", unmappedTargetPolicy = ReportingPolicy.ERROR, @@ -36,57 +34,48 @@ public abstract class ExpressionMapper { private final org.geotools.api.filter.FilterFactory ff = CommonFactoryFinder.getFilterFactory(); - private final ExpressionVisitor visitor = - new ExpressionVisitor() { - - @Override - public Subtract visit( - org.geotools.api.filter.expression.Subtract expression, Object extraData) { - return map(expression); - } - - @Override - public PropertyName visit( - org.geotools.api.filter.expression.PropertyName expression, - Object extraData) { - return map(expression); - } - - @Override - public Multiply visit( - org.geotools.api.filter.expression.Multiply expression, Object extraData) { - return map(expression); - } - - @Override - public Literal visit( - org.geotools.api.filter.expression.Literal expression, Object extraData) { - return map(expression); - } - - @Override - public Function visit( - org.geotools.api.filter.expression.Function expression, Object extraData) { - return map(expression); - } - - @Override - public Divide visit( - org.geotools.api.filter.expression.Divide expression, Object extraData) { - return map(expression); - } - - @Override - public Add visit( - org.geotools.api.filter.expression.Add expression, Object extraData) { - return map(expression); - } - - @Override - public Expression visit(NilExpression expression, Object extraData) { - return map(expression); - } - }; + private final ExpressionVisitor visitor = new ExpressionVisitor() { + + @Override + public Subtract visit(org.geotools.api.filter.expression.Subtract expression, Object extraData) { + return map(expression); + } + + @Override + public PropertyName visit(org.geotools.api.filter.expression.PropertyName expression, Object extraData) { + return map(expression); + } + + @Override + public Multiply visit(org.geotools.api.filter.expression.Multiply expression, Object extraData) { + return map(expression); + } + + @Override + public Literal visit(org.geotools.api.filter.expression.Literal expression, Object extraData) { + return map(expression); + } + + @Override + public Function visit(org.geotools.api.filter.expression.Function expression, Object extraData) { + return map(expression); + } + + @Override + public Divide visit(org.geotools.api.filter.expression.Divide expression, Object extraData) { + return map(expression); + } + + @Override + public Add visit(org.geotools.api.filter.expression.Add expression, Object extraData) { + return map(expression); + } + + @Override + public Expression visit(NilExpression expression, Object extraData) { + return map(expression); + } + }; public Expression map(org.geotools.api.filter.expression.Expression source) { return (Expression) source.accept(visitor, null); @@ -101,17 +90,14 @@ public org.geotools.api.filter.expression.Expression map(Expression source) { if (source instanceof Multiply multiply) return map(multiply); if (source instanceof Divide divide) return map(divide); if (source instanceof Function function) return map(function); - throw new IllegalArgumentException( - "Unrecognized expression type %s: %s" - .formatted(source.getClass().getName(), source)); + throw new IllegalArgumentException("Unrecognized expression type %s: %s" + .formatted(source.getClass().getName(), source)); } - public @ObjectFactory org.geotools.api.filter.capability.FunctionName functionName( - Expression.FunctionName dto) { + public @ObjectFactory org.geotools.api.filter.capability.FunctionName functionName(Expression.FunctionName dto) { FunctionFinder finder = new FunctionFinder(null); String functionName = dto.getName(); - org.geotools.api.filter.capability.FunctionName name = - finder.findFunctionDescription(functionName); + org.geotools.api.filter.capability.FunctionName name = finder.findFunctionDescription(functionName); if (name == null) { int argumentCount = dto.getArgumentCount(); List argumentNames = dto.getArgumentNames(); @@ -152,11 +138,9 @@ protected org.geotools.api.filter.expression.Function map(Function dto) { return ff.function(dto.getName(), parameters); } - protected abstract org.geotools.api.filter.expression.Expression[] dtoListToExpressionList( - List list); + protected abstract org.geotools.api.filter.expression.Expression[] dtoListToExpressionList(List list); - protected abstract Expression.Function map( - org.geotools.api.filter.expression.Function expression); + protected abstract Expression.Function map(org.geotools.api.filter.expression.Function expression); protected abstract Add map(org.geotools.api.filter.expression.Add expression); diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/FilterMapper.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/FilterMapper.java index 3ce3a611d..d82b14313 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/FilterMapper.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/FilterMapper.java @@ -5,7 +5,6 @@ package org.geotools.jackson.databind.filter.mapper; import lombok.Generated; - import org.geotools.api.filter.expression.PropertyName; import org.geotools.api.filter.sort.SortOrder; import org.geotools.filter.SortByImpl; @@ -19,8 +18,7 @@ @AnnotateWith(value = Generated.class) public class FilterMapper { - public org.geotools.jackson.databind.filter.dto.Filter map( - org.geotools.api.filter.Filter filter) { + public org.geotools.jackson.databind.filter.dto.Filter map(org.geotools.api.filter.Filter filter) { return Mappers.getMapper(FilterToDtoMapper.class).map(filter); } @@ -28,38 +26,29 @@ public org.geotools.api.filter.Filter map(org.geotools.jackson.databind.filter.d return Mappers.getMapper(DtoToFilterMapper.class).map(dto); } - public org.geotools.api.filter.sort.SortBy map( - org.geotools.jackson.databind.filter.dto.SortBy dto) { + public org.geotools.api.filter.sort.SortBy map(org.geotools.jackson.databind.filter.dto.SortBy dto) { if (dto == null) return null; - PropertyName propertyName = - Mappers.getMapper(ExpressionMapper.class).map(dto.getPropertyName()); + PropertyName propertyName = Mappers.getMapper(ExpressionMapper.class).map(dto.getPropertyName()); SortOrder sortOrder = map(dto.getSortOrder()); return new SortByImpl(propertyName, sortOrder); } - public org.geotools.jackson.databind.filter.dto.SortBy map( - org.geotools.api.filter.sort.SortBy sortBy) { + public org.geotools.jackson.databind.filter.dto.SortBy map(org.geotools.api.filter.sort.SortBy sortBy) { if (sortBy == null) return null; Expression.PropertyName propertyName = Mappers.getMapper(ExpressionMapper.class).map(sortBy.getPropertyName()); - org.geotools.jackson.databind.filter.dto.SortBy.SortOrder sortOrder = - map(sortBy.getSortOrder()); + org.geotools.jackson.databind.filter.dto.SortBy.SortOrder sortOrder = map(sortBy.getSortOrder()); return new SortBy(propertyName, sortOrder); } public SortOrder map(org.geotools.jackson.databind.filter.dto.SortBy.SortOrder order) { - return order == null - || order - == org.geotools.jackson.databind.filter.dto.SortBy.SortOrder - .ASCENDING + return order == null || order == org.geotools.jackson.databind.filter.dto.SortBy.SortOrder.ASCENDING ? SortOrder.ASCENDING : SortOrder.DESCENDING; } public org.geotools.jackson.databind.filter.dto.SortBy.SortOrder map(SortOrder order) { - return order == null || SortOrder.ASCENDING == order - ? SortBy.SortOrder.ASCENDING - : SortBy.SortOrder.DESCENDING; + return order == null || SortOrder.ASCENDING == order ? SortBy.SortOrder.ASCENDING : SortBy.SortOrder.DESCENDING; } } diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/FilterMapperConfig.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/FilterMapperConfig.java index 53bd70121..124870a22 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/FilterMapperConfig.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/FilterMapperConfig.java @@ -10,10 +10,5 @@ @MapperConfig( componentModel = "default", unmappedTargetPolicy = ReportingPolicy.ERROR, - uses = { - ExpressionFactory.class, - FilterFactory.class, - GeoToolsValueMappers.class, - ExpressionMapper.class - }) + uses = {ExpressionFactory.class, FilterFactory.class, GeoToolsValueMappers.class, ExpressionMapper.class}) public class FilterMapperConfig {} diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/FilterToDtoMapper.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/FilterToDtoMapper.java index 29199a08f..9a53be8cd 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/FilterToDtoMapper.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/FilterToDtoMapper.java @@ -5,7 +5,6 @@ package org.geotools.jackson.databind.filter.mapper; import lombok.Generated; - import org.geotools.api.filter.And; import org.geotools.api.filter.ExcludeFilter; import org.geotools.api.filter.Id; @@ -105,8 +104,7 @@ default Filter map(org.geotools.api.filter.Filter filter) { BinaryComparisonOperator.PropertyIsLessThan toDto(PropertyIsLessThan filter); - BinaryComparisonOperator.PropertyIsGreaterThanOrEqualTo toDto( - PropertyIsGreaterThanOrEqualTo filter); + BinaryComparisonOperator.PropertyIsGreaterThanOrEqualTo toDto(PropertyIsGreaterThanOrEqualTo filter); BinaryComparisonOperator.PropertyIsGreaterThan toDto(PropertyIsGreaterThan filter); @@ -135,8 +133,7 @@ default Filter.Id.FeatureId map(org.geotools.api.filter.identity.Identifier id) fid = new Filter.Id.FeatureId(); } else { throw new IllegalArgumentException( - "Identifier type not supported: %s" - .formatted(id.getClass().getCanonicalName())); + "Identifier type not supported: %s".formatted(id.getClass().getCanonicalName())); } fid.setId(((FeatureId) id).getID()); fid.setPreviousRid(((FeatureId) id).getPreviousRid()); diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/GeoToolsValueMappers.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/GeoToolsValueMappers.java index 7eeeda744..8fe1b1f35 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/GeoToolsValueMappers.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/GeoToolsValueMappers.java @@ -4,9 +4,14 @@ */ package org.geotools.jackson.databind.filter.mapper; +import java.util.Collections; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.Set; +import java.util.function.Function; import lombok.Generated; import lombok.extern.slf4j.Slf4j; - import org.apache.commons.lang3.ClassUtils; import org.geotools.api.feature.type.Name; import org.geotools.api.referencing.FactoryException; @@ -34,13 +39,6 @@ import org.slf4j.LoggerFactory; import org.xml.sax.helpers.NamespaceSupport; -import java.util.Collections; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.Set; -import java.util.function.Function; - @Mapper(componentModel = "default", unmappedTargetPolicy = ReportingPolicy.ERROR) @AnnotateWith(value = Generated.class) @Slf4j @@ -51,11 +49,9 @@ public abstract class GeoToolsValueMappers { private static final org.geotools.util.Converter measure2Str = new MeasureConverterFactory().createConverter(Measure.class, String.class, null); - public abstract MatchAction matchAction( - org.geotools.api.filter.MultiValuedFilter.MatchAction matchAction); + public abstract MatchAction matchAction(org.geotools.api.filter.MultiValuedFilter.MatchAction matchAction); - public abstract org.geotools.api.filter.MultiValuedFilter.MatchAction matchAction( - MatchAction matchAction); + public abstract org.geotools.api.filter.MultiValuedFilter.MatchAction matchAction(MatchAction matchAction); public NamespaceSupport map(Map map) { if (map == null) return null; @@ -188,8 +184,7 @@ public ReferencedEnvelope referencedEnvelope(Envelope source) { return env; } - public abstract org.geotools.jackson.databind.dto.NameDto map( - org.geotools.api.feature.type.Name name); + public abstract org.geotools.jackson.databind.dto.NameDto map(org.geotools.api.feature.type.Name name); public Name map(org.geotools.jackson.databind.dto.NameDto dto) { return new NameImpl(dto.getNamespaceURI(), dto.getLocalPart()); @@ -285,8 +280,7 @@ public NumberRange dtoToNumberRange(NumberRangeDto source) { if (min instanceof Long || max instanceof Long) return NumberRange.create(min.longValue(), minIncluded, max.longValue(), maxIncluded); if (min instanceof Double || max instanceof Double) - return NumberRange.create( - min.doubleValue(), minIncluded, max.doubleValue(), maxIncluded); + return NumberRange.create(min.doubleValue(), minIncluded, max.doubleValue(), maxIncluded); if (min instanceof Float || max instanceof Float) return NumberRange.create(min.floatValue(), minIncluded, max.floatValue(), maxIncluded); if (min instanceof Integer || max instanceof Integer) diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/MappingFilterVisitor.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/MappingFilterVisitor.java index 7ce41783d..979d013f0 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/MappingFilterVisitor.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/filter/mapper/MappingFilterVisitor.java @@ -5,7 +5,6 @@ package org.geotools.jackson.databind.filter.mapper; import lombok.NonNull; - import org.geotools.api.filter.And; import org.geotools.api.filter.ExcludeFilter; import org.geotools.api.filter.FilterVisitor; diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/geojson/GeoToolsGeoJsonModule.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/geojson/GeoToolsGeoJsonModule.java index ac83c2b5f..6f201c2d8 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/geojson/GeoToolsGeoJsonModule.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/geojson/GeoToolsGeoJsonModule.java @@ -7,9 +7,7 @@ import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.module.SimpleModule; - import lombok.extern.slf4j.Slf4j; - import org.geotools.jackson.databind.geojson.geometry.GeometryDeserializer; import org.geotools.jackson.databind.geojson.geometry.GeometrySerializer; import org.locationtech.jts.geom.Geometry; diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/geojson/geometry/GeometryDeserializer.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/geojson/geometry/GeometryDeserializer.java index ac13bf544..36b264c01 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/geojson/geometry/GeometryDeserializer.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/geojson/geometry/GeometryDeserializer.java @@ -13,7 +13,11 @@ import com.fasterxml.jackson.databind.node.NumericNode; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.TextNode; - +import java.io.IOException; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.IntStream; import org.locationtech.jts.geom.CoordinateSequence; import org.locationtech.jts.geom.CoordinateSequenceFactory; import org.locationtech.jts.geom.Geometry; @@ -28,18 +32,11 @@ import org.locationtech.jts.geom.Polygon; import org.locationtech.jts.geom.impl.PackedCoordinateSequenceFactory; -import java.io.IOException; -import java.util.Arrays; -import java.util.HashSet; -import java.util.Set; -import java.util.stream.IntStream; - public class GeometryDeserializer extends JsonDeserializer { private static final String COORDINATES_PROPERTY = "coordinates"; - private static final GeometryFactory DEFAULT_GF = - new GeometryFactory(new PackedCoordinateSequenceFactory()); + private static final GeometryFactory DEFAULT_GF = new GeometryFactory(new PackedCoordinateSequenceFactory()); private GeometryFactory geometryFactory; @@ -82,8 +79,7 @@ private Geometry readGeometry(ObjectNode geometryNode, int dimensions, boolean h case Geometry.TYPENAME_GEOMETRYCOLLECTION: return readGeometryCollection(geometryNode, dimensions, hasM); default: - throw new IllegalArgumentException( - "Unknown geometry node: %s".formatted(geometryNode)); + throw new IllegalArgumentException("Unknown geometry node: %s".formatted(geometryNode)); } } @@ -103,19 +99,17 @@ private boolean resolveHasM(ObjectNode geometryNode) { return false; } - private MultiLineString readMultiLineString( - ObjectNode geometryNode, int dimensions, boolean hasM) { + private MultiLineString readMultiLineString(ObjectNode geometryNode, int dimensions, boolean hasM) { ArrayNode coordinates = (ArrayNode) geometryNode.findValue(COORDINATES_PROPERTY); if (coordinates.isEmpty()) { return geometryFactory.createMultiLineString(); } - LineString[] lineStrings = - IntStream.range(0, coordinates.size()) - .mapToObj(i -> (ArrayNode) coordinates.get(i)) - .map(geomN -> readCoordinateSequence(geomN, dimensions, hasM)) - .map(geometryFactory::createLineString) - .toArray(LineString[]::new); + LineString[] lineStrings = IntStream.range(0, coordinates.size()) + .mapToObj(i -> (ArrayNode) coordinates.get(i)) + .map(geomN -> readCoordinateSequence(geomN, dimensions, hasM)) + .map(geometryFactory::createLineString) + .toArray(LineString[]::new); return geometryFactory.createMultiLineString(lineStrings); } @@ -125,16 +119,14 @@ private MultiPolygon readMultiPolygon(ObjectNode geometryNode, int dimensions, b if (coordinates.isEmpty()) { return geometryFactory.createMultiPolygon(); } - Polygon[] polygons = - IntStream.range(0, coordinates.size()) - .mapToObj(i -> (ArrayNode) coordinates.get(i)) - .map(array -> readPolygon(array, dimensions, hasM)) - .toArray(Polygon[]::new); + Polygon[] polygons = IntStream.range(0, coordinates.size()) + .mapToObj(i -> (ArrayNode) coordinates.get(i)) + .map(array -> readPolygon(array, dimensions, hasM)) + .toArray(Polygon[]::new); return geometryFactory.createMultiPolygon(polygons); } - private GeometryCollection readGeometryCollection( - ObjectNode geometryNode, int dimensions, boolean hasM) { + private GeometryCollection readGeometryCollection(ObjectNode geometryNode, int dimensions, boolean hasM) { ArrayNode geometries = (ArrayNode) geometryNode.findValue("geometries"); if (geometries.isEmpty()) { return geometryFactory.createGeometryCollection(); @@ -161,13 +153,7 @@ private Polygon readPolygon(ArrayNode coordinates, int dimensions, boolean hasM) if (coordinates.size() > 1) { holes = new LinearRing[coordinates.size() - 1]; IntStream.range(1, coordinates.size()) - .forEach( - i -> - holes[i - 1] = - readLinearRing( - (ArrayNode) coordinates.get(i), - dimensions, - hasM)); + .forEach(i -> holes[i - 1] = readLinearRing((ArrayNode) coordinates.get(i), dimensions, hasM)); } else { holes = null; } @@ -200,8 +186,7 @@ private MultiPoint readMultiPoint(ObjectNode geometryNode, int dimensions, boole return geometryFactory.createMultiPoint(coords); } - private CoordinateSequence readCoordinateSequence( - ArrayNode coordinates, int dimension, boolean hasM) { + private CoordinateSequence readCoordinateSequence(ArrayNode coordinates, int dimension, boolean hasM) { final int size = coordinates.size(); final int measures = hasM ? 1 : 0; CoordinateSequenceFactory sequenceFactory = geometryFactory.getCoordinateSequenceFactory(); @@ -235,16 +220,8 @@ public static boolean isGeometry(JsonNode value) { return typeNode instanceof TextNode textNode && isGeometry(textNode.asText()); } - private static final Set geomTypes = - new HashSet<>( - Arrays.asList( // - "Point", - "MultiPoint", - "LineString", - "MultiLineString", - "Polygon", - "MultiPolygon", - "GeometryCollection")); + private static final Set geomTypes = new HashSet<>(Arrays.asList( // + "Point", "MultiPoint", "LineString", "MultiLineString", "Polygon", "MultiPolygon", "GeometryCollection")); public static boolean isGeometry(String type) { return geomTypes.contains(type); diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/geojson/geometry/GeometrySerializer.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/geojson/geometry/GeometrySerializer.java index a26f4e4f5..69eb23328 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/geojson/geometry/GeometrySerializer.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/geojson/geometry/GeometrySerializer.java @@ -10,7 +10,8 @@ import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.ser.std.StdSerializer; - +import java.io.IOException; +import java.util.concurrent.atomic.AtomicReference; import org.locationtech.jts.geom.CoordinateSequence; import org.locationtech.jts.geom.CoordinateSequenceFilter; import org.locationtech.jts.geom.Geometry; @@ -22,9 +23,6 @@ import org.locationtech.jts.geom.Point; import org.locationtech.jts.geom.Polygon; -import java.io.IOException; -import java.util.concurrent.atomic.AtomicReference; - public class GeometrySerializer extends StdSerializer { private static final long serialVersionUID = 1L; @@ -34,14 +32,10 @@ public GeometrySerializer() { @Override public void serializeWithType( - Geometry value, - JsonGenerator gen, - SerializerProvider serializers, - TypeSerializer typeSer) + Geometry value, JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - WritableTypeId typeIdDef = - typeSer.writeTypePrefix(gen, typeSer.typeId(value, JsonToken.START_OBJECT)); + WritableTypeId typeIdDef = typeSer.writeTypePrefix(gen, typeSer.typeId(value, JsonToken.START_OBJECT)); serializeContent(value, gen, null); @@ -49,8 +43,7 @@ public void serializeWithType( } @Override - public void serialize(Geometry value, JsonGenerator gen, SerializerProvider serializers) - throws IOException { + public void serialize(Geometry value, JsonGenerator gen, SerializerProvider serializers) throws IOException { serialize(value, gen); } @@ -59,8 +52,7 @@ public void serialize(Geometry geometry, JsonGenerator generator) throws IOExcep serialize(geometry, generator, (String) null); } - public void serialize(Geometry geometry, JsonGenerator generator, String customNameProperty) - throws IOException { + public void serialize(Geometry geometry, JsonGenerator generator, String customNameProperty) throws IOException { if (geometry == null) { generator.writeNull(); return; @@ -70,8 +62,7 @@ public void serialize(Geometry geometry, JsonGenerator generator, String customN generator.writeEndObject(); } - private void serializeContent( - Geometry geometry, JsonGenerator generator, String customNameProperty) + private void serializeContent(Geometry geometry, JsonGenerator generator, String customNameProperty) throws IOException { generator.writeStringField("type", geometry.getGeometryType()); writeDimensions(geometry, generator); @@ -128,8 +119,7 @@ private void writeGeometry(Geometry geometry, JsonGenerator generator) throws IO } } - private void writeMultiGeom(GeometryCollection multi, JsonGenerator generator) - throws IOException { + private void writeMultiGeom(GeometryCollection multi, JsonGenerator generator) throws IOException { generator.writeStartArray(); for (int i = 0; i < multi.getNumGeometries(); i++) { writeGeometry(multi.getGeometryN(i), generator); @@ -157,26 +147,24 @@ private void writeSimpleGeom(Geometry geometry, JsonGenerator generator) throws } } - private void writeCoordinateSequence(Geometry simpleGeom, JsonGenerator generator) - throws IOException { + private void writeCoordinateSequence(Geometry simpleGeom, JsonGenerator generator) throws IOException { final AtomicReference seqRef = new AtomicReference<>(); - simpleGeom.apply( - new CoordinateSequenceFilter() { - @Override - public void filter(CoordinateSequence seq, int i) { - seqRef.set(seq); - } - - @Override - public boolean isGeometryChanged() { - return false; - } - - @Override - public boolean isDone() { - return true; - } - }); + simpleGeom.apply(new CoordinateSequenceFilter() { + @Override + public void filter(CoordinateSequence seq, int i) { + seqRef.set(seq); + } + + @Override + public boolean isGeometryChanged() { + return false; + } + + @Override + public boolean isDone() { + return true; + } + }); CoordinateSequence seq = seqRef.get(); int size = seq.size(); @@ -187,8 +175,7 @@ public boolean isDone() { generator.writeEndArray(); } - private void writeCoordinate(CoordinateSequence seq, int index, JsonGenerator generator) - throws IOException { + private void writeCoordinate(CoordinateSequence seq, int index, JsonGenerator generator) throws IOException { int dimension = seq.getDimension(); generator.writeStartArray(); for (int i = 0; i < dimension; i++) generator.writeNumber(seq.getOrdinate(index, i)); diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/util/MapperDeserializer.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/util/MapperDeserializer.java index aaea9e95e..d8f7699f7 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/util/MapperDeserializer.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/util/MapperDeserializer.java @@ -7,14 +7,12 @@ import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; - +import java.io.IOException; +import java.util.function.Function; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import java.io.IOException; -import java.util.function.Function; - /** * Generic {@link JsonDeserializer} that applies a function from an for-the-wire POJO type to the * the original object type after {@link JsonParser#readValueAs(Class)} reading it. diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/util/MapperSerializer.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/util/MapperSerializer.java index 7a561d76d..fac1add0d 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/util/MapperSerializer.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/util/MapperSerializer.java @@ -11,11 +11,9 @@ import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.jsontype.TypeSerializer; import com.fasterxml.jackson.databind.ser.std.StdSerializer; - -import lombok.extern.slf4j.Slf4j; - import java.io.IOException; import java.util.function.Function; +import lombok.extern.slf4j.Slf4j; /** * Generic {@link JsonSerializer} that applies a function from the original object type to the @@ -40,12 +38,10 @@ public MapperSerializer(Class type, java.util.function.Function seriali } @Override - public void serializeWithType( - I value, JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) + public void serializeWithType(I value, JsonGenerator gen, SerializerProvider serializers, TypeSerializer typeSer) throws IOException { - WritableTypeId typeIdDef = - typeSer.writeTypePrefix(gen, typeSer.typeId(value, type, JsonToken.VALUE_STRING)); + WritableTypeId typeIdDef = typeSer.writeTypePrefix(gen, typeSer.typeId(value, type, JsonToken.VALUE_STRING)); serialize(value, gen, null); @@ -53,8 +49,7 @@ public void serializeWithType( } @Override - public void serialize(I value, JsonGenerator gen, SerializerProvider provider) - throws IOException { + public void serialize(I value, JsonGenerator gen, SerializerProvider provider) throws IOException { D dto; try { diff --git a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/util/ObjectMapperUtil.java b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/util/ObjectMapperUtil.java index 8efdf2273..0f2c387b1 100644 --- a/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/util/ObjectMapperUtil.java +++ b/src/catalog/jackson-bindings/geotools/src/main/java/org/geotools/jackson/databind/util/ObjectMapperUtil.java @@ -10,9 +10,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.yaml.YAMLFactory; import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator; - import lombok.experimental.UtilityClass; - import org.yaml.snakeyaml.DumperOptions.Version; /** @@ -26,13 +24,12 @@ public static ObjectMapper newObjectMapper() { } public static ObjectMapper newYAMLObjectMapper() { - YAMLFactory yamlFactory = - YAMLFactory.builder() // - .yamlVersionToWrite(Version.V1_1) // - .disable(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID) // - .disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER) // - .enable(YAMLGenerator.Feature.MINIMIZE_QUOTES) // - .build(); + YAMLFactory yamlFactory = YAMLFactory.builder() // + .yamlVersionToWrite(Version.V1_1) // + .disable(YAMLGenerator.Feature.USE_NATIVE_TYPE_ID) // + .disable(YAMLGenerator.Feature.WRITE_DOC_START_MARKER) // + .enable(YAMLGenerator.Feature.MINIMIZE_QUOTES) // + .build(); return newObjectMapper(yamlFactory); } diff --git a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/ExpressionRoundtripTest.java b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/ExpressionRoundtripTest.java index e49605dde..1aa12301f 100644 --- a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/ExpressionRoundtripTest.java +++ b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/ExpressionRoundtripTest.java @@ -8,9 +8,22 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import java.awt.Color; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.sql.Date; +import java.time.Instant; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.IntStream; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; - import org.geotools.api.feature.type.Name; import org.geotools.api.filter.capability.FunctionName; import org.geotools.api.parameter.Parameter; @@ -34,24 +47,8 @@ import org.locationtech.jts.geom.MultiPolygon; import org.locationtech.jts.io.ParseException; import org.locationtech.jts.io.WKTReader; - import si.uom.SI; -import java.awt.Color; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.sql.Date; -import java.time.Instant; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.IntStream; - /** * Abstract test suite for {@link Expression} Data Transfer Objects or POJOS; to be used both for * testing serialization/deserialization and mapping to and from {@link @@ -67,8 +64,7 @@ protected void print(String logmsg, Object... args) { protected abstract E roundtripTest(E dto) throws Exception; - protected abstract Expression.FunctionName roundtripTest(Expression.FunctionName dto) - throws Exception; + protected abstract Expression.FunctionName roundtripTest(Expression.FunctionName dto) throws Exception; @Test void propertySimple() throws Exception { @@ -96,10 +92,7 @@ void propertyNameNamespaceContext() throws Exception { @Test void binaryExpressionAdd() throws Exception { - BinaryExpression dto = - new Add() - .setExpression1(propertyName("name")) - .setExpression2(literal(Long.MAX_VALUE)); + BinaryExpression dto = new Add().setExpression1(propertyName("name")).setExpression2(literal(Long.MAX_VALUE)); roundtripTest(dto); } @@ -112,8 +105,7 @@ void binaryExpressionSubtract() throws Exception { @Test void binaryExpressionDivide() throws Exception { - BinaryExpression dto = - new Divide().setExpression1(propertyName("name")).setExpression2(literal(1000)); + BinaryExpression dto = new Divide().setExpression1(propertyName("name")).setExpression2(literal(1000)); roundtripTest(dto); } @@ -151,22 +143,13 @@ void literalFloat() throws Exception { @Test void literalBigInteger() throws Exception { - roundtripTest( - literal( - BigInteger.valueOf(Long.MAX_VALUE) - .add(BigInteger.valueOf(Long.MAX_VALUE)))); - roundtripTest( - literal( - BigInteger.valueOf(Long.MIN_VALUE) - .subtract(BigInteger.valueOf(Long.MAX_VALUE)))); + roundtripTest(literal(BigInteger.valueOf(Long.MAX_VALUE).add(BigInteger.valueOf(Long.MAX_VALUE)))); + roundtripTest(literal(BigInteger.valueOf(Long.MIN_VALUE).subtract(BigInteger.valueOf(Long.MAX_VALUE)))); } @Test void literalBigDecimal() throws Exception { - roundtripTest( - literal( - BigDecimal.valueOf(Double.MAX_VALUE) - .add(BigDecimal.valueOf(Double.MAX_VALUE)))); + roundtripTest(literal(BigDecimal.valueOf(Double.MAX_VALUE).add(BigDecimal.valueOf(Double.MAX_VALUE)))); } @Test @@ -325,32 +308,28 @@ private Geometry sampleLineString() { void allAvailableFunctions() throws Exception { // build a list of ignored function names, due to inability to serialize/deserialize their // argument types - Set ignore = - new HashSet( - Arrays.asList( - "contrast", - "darken", - "desaturate", - "grayscale", - "lighten", - "mix", - "inArray", - "relatePattern", - "relate", - "rescaleToPixels", - "saturate", - "shade", - "spin", - "tint", - "Categorize")); + Set ignore = new HashSet(Arrays.asList( + "contrast", + "darken", + "desaturate", + "grayscale", + "lighten", + "mix", + "inArray", + "relatePattern", + "relate", + "rescaleToPixels", + "saturate", + "shade", + "spin", + "tint", + "Categorize")); FunctionFinder finder = new FunctionFinder(null); List allFunctionDescriptions = finder.getAllFunctionDescriptions(); for (FunctionName functionName : allFunctionDescriptions) { if (ignore.contains(functionName.getName())) { - print( - "Ignoring function {}, can't represent its arguments in JSON", - functionName.getName()); + print("Ignoring function {}, can't represent its arguments in JSON", functionName.getName()); continue; } testFunctionRoundtrip(functionName); @@ -360,10 +339,9 @@ void allAvailableFunctions() throws Exception { @Test void allAvailableFunctionNames() throws Exception { FunctionFinder finder = new FunctionFinder(null); - List allFunctionDescriptions = - finder.getAllFunctionDescriptions().stream() - .sorted((f1, f2) -> f1.getName().compareTo(f2.getName())) - .toList(); + List allFunctionDescriptions = finder.getAllFunctionDescriptions().stream() + .sorted((f1, f2) -> f1.getName().compareTo(f2.getName())) + .toList(); for (FunctionName functionName : allFunctionDescriptions) { testFunctionNameRoundtrip(functionName); } @@ -497,8 +475,7 @@ private Object sampleValue(Class type) { case "org.geotools.api.referencing.crs.CoordinateReferenceSystem" -> sampleCrs(); case "org.locationtech.jts.geom.Point" -> geom("POINT(1 1)"); default -> throw new UnsupportedOperationException( - "Unexpected parameter type, add a sample value: '%s'" - .formatted(type.getCanonicalName())); + "Unexpected parameter type, add a sample value: '%s'".formatted(type.getCanonicalName())); }; } diff --git a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/FilterRoundtripTest.java b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/FilterRoundtripTest.java index 13df5237a..d75f827a2 100644 --- a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/FilterRoundtripTest.java +++ b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/FilterRoundtripTest.java @@ -4,6 +4,13 @@ */ package org.geotools.jackson.databind.filter; +import java.time.LocalDate; +import java.util.Arrays; +import java.util.Date; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Supplier; import org.geotools.jackson.databind.filter.dto.Expression; import org.geotools.jackson.databind.filter.dto.Filter; import org.geotools.jackson.databind.filter.dto.Filter.BinaryComparisonOperator; @@ -24,14 +31,6 @@ import org.locationtech.jts.io.ParseException; import org.locationtech.jts.io.WKTReader; -import java.time.LocalDate; -import java.util.Arrays; -import java.util.Date; -import java.util.HashSet; -import java.util.List; -import java.util.Set; -import java.util.function.Supplier; - /** * Abstract test suite for {@link Filter} Data Transfer Objects or POJOS; to be used both for * testing serialization/deserialization and mapping to and from {@link @@ -41,8 +40,7 @@ public abstract class FilterRoundtripTest { protected abstract F roundtripTest(F dto) throws Exception; - protected abstract void roundtripTest(org.geotools.jackson.databind.filter.dto.SortBy dto) - throws Exception; + protected abstract void roundtripTest(org.geotools.jackson.databind.filter.dto.SortBy dto) throws Exception; @Test void include() throws Exception { @@ -83,18 +81,16 @@ void idFilter_FeatureId_FeatureVersion() throws Exception { @Test void idFilter_ResourceId_Date() throws Exception { Set identifiers = new HashSet<>(); - identifiers.add( - new Filter.Id.ResourceId() - .setStartTime(new Date()) - .setEndTime(new Date()) - // .setFeatureVersion("v1") - .setId("states.1")); - identifiers.add( - new Filter.Id.ResourceId() - .setStartTime(new Date()) - .setEndTime(new Date()) - // .setFeatureVersion("2") - .setId("states.2")); + identifiers.add(new Filter.Id.ResourceId() + .setStartTime(new Date()) + .setEndTime(new Date()) + // .setFeatureVersion("v1") + .setId("states.1")); + identifiers.add(new Filter.Id.ResourceId() + .setStartTime(new Date()) + .setEndTime(new Date()) + // .setFeatureVersion("2") + .setId("states.2")); Filter filter = new Filter.Id().setIdentifiers(identifiers); roundtripTest(filter); } @@ -124,41 +120,37 @@ void sortBy() throws Exception { } private PropertyIsNull isNullFilter() { - return new Filter.PropertyIsNull() - .setExpression(new Expression.PropertyName().setPropertyName("name")); + return new Filter.PropertyIsNull().setExpression(new Expression.PropertyName().setPropertyName("name")); } @Test void propertyIsNil() throws Exception { - Filter filter = - new Filter.PropertyIsNil() - .setExpression(new Expression.PropertyName().setPropertyName("name")) - .setNilReason("because"); + Filter filter = new Filter.PropertyIsNil() + .setExpression(new Expression.PropertyName().setPropertyName("name")) + .setNilReason("because"); roundtripTest(filter); } @Test void propertyIsLike() throws Exception { - MultiValuedFilter filter = - new Filter.PropertyIsLike() - .setExpression(propertyName("text")) - .setEscape("-") - .setLiteral("good thoughts") - .setMatchingCase(true) - .setSingleChar("?") - .setWildCard("*") - .setMatchAction(MatchAction.ONE); + MultiValuedFilter filter = new Filter.PropertyIsLike() + .setExpression(propertyName("text")) + .setEscape("-") + .setLiteral("good thoughts") + .setMatchingCase(true) + .setSingleChar("?") + .setWildCard("*") + .setMatchAction(MatchAction.ONE); roundtripTest(filter); } @Test void propertyIsBetween() throws Exception { - MultiValuedFilter dto = - new Filter.PropertyIsBetween() - .setExpression(propertyName("count")) - .setLowerBoundary(literal(1000)) - .setUpperBoundary(literal(2000)) - .setMatchAction(MatchAction.ANY); + MultiValuedFilter dto = new Filter.PropertyIsBetween() + .setExpression(propertyName("count")) + .setLowerBoundary(literal(1000)) + .setUpperBoundary(literal(2000)) + .setMatchAction(MatchAction.ANY); roundtripTest(dto); } @@ -181,15 +173,12 @@ void binaryComparisonOperators() throws Exception { testBinaryComparisonOperator(Filter.BinaryComparisonOperator.PropertyIsEqualTo::new); testBinaryComparisonOperator(Filter.BinaryComparisonOperator.PropertyIsNotEqualTo::new); testBinaryComparisonOperator(Filter.BinaryComparisonOperator.PropertyIsLessThan::new); - testBinaryComparisonOperator( - Filter.BinaryComparisonOperator.PropertyIsLessThanOrEqualTo::new); + testBinaryComparisonOperator(Filter.BinaryComparisonOperator.PropertyIsLessThanOrEqualTo::new); testBinaryComparisonOperator(Filter.BinaryComparisonOperator.PropertyIsGreaterThan::new); - testBinaryComparisonOperator( - Filter.BinaryComparisonOperator.PropertyIsGreaterThanOrEqualTo::new); + testBinaryComparisonOperator(Filter.BinaryComparisonOperator.PropertyIsGreaterThanOrEqualTo::new); } - private void testBinaryComparisonOperator(Supplier factory) - throws Exception { + private void testBinaryComparisonOperator(Supplier factory) throws Exception { BinaryComparisonOperator filter = factory.get(); filter.setExpression1(propertyName("the_geom")); filter.setExpression2(geometry()); @@ -235,8 +224,7 @@ void distanceBufferOperators() throws Exception { testDistanceBufferOperator(Filter.BinarySpatialOperator.DWithin::new); } - private void testBinarySpatialOperator(Supplier factory) - throws Exception { + private void testBinarySpatialOperator(Supplier factory) throws Exception { BinarySpatialOperator filter = factory.get(); filter.setExpression1(propertyName("the_geom")); filter.setExpression2(geometry()); @@ -244,8 +232,7 @@ private void testBinarySpatialOperator(Supplier factory) roundtripTest(filter); } - private void testDistanceBufferOperator(Supplier factory) - throws Exception { + private void testDistanceBufferOperator(Supplier factory) throws Exception { DistanceBufferOperator filter = factory.get(); filter.setExpression1(propertyName("the_geom")); filter.setExpression2(geometry()); @@ -255,8 +242,7 @@ private void testDistanceBufferOperator(Supplier factory roundtripTest(filter); } - private void testBinaryTemporalOperator(Supplier factory) - throws Exception { + private void testBinaryTemporalOperator(Supplier factory) throws Exception { BinaryTemporalOperator filter = factory.get(); filter.setExpression1(propertyName("time")); filter.setExpression2(temporalLiteral()); diff --git a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleExpressionsTest.java b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleExpressionsTest.java index 155fa3704..2acae1383 100644 --- a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleExpressionsTest.java +++ b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleExpressionsTest.java @@ -9,7 +9,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.fasterxml.jackson.databind.ObjectMapper; - import org.geotools.api.filter.expression.Function; import org.geotools.api.filter.expression.Literal; import org.geotools.jackson.databind.filter.dto.Expression; @@ -43,9 +42,7 @@ public abstract class GeoToolsFilterModuleExpressionsTest extends ExpressionRoun String serialized = objectMapper.writeValueAsString(expected); print("serialized: {}", serialized); org.geotools.api.filter.expression.Expression deserialized; - deserialized = - objectMapper.readValue( - serialized, org.geotools.api.filter.expression.Expression.class); + deserialized = objectMapper.readValue(serialized, org.geotools.api.filter.expression.Expression.class); if (expected instanceof Function f1) { assertThat(deserialized).isInstanceOf(Function.class); @@ -56,8 +53,7 @@ public abstract class GeoToolsFilterModuleExpressionsTest extends ExpressionRoun assertThat(deserialized).isInstanceOf(Literal.class); Object v1 = literal.getValue(); Object v2 = ((Literal) deserialized).getValue(); - boolean valueEquals = - org.geotools.jackson.databind.filter.dto.Literal.valueEquals(v1, v2); + boolean valueEquals = org.geotools.jackson.databind.filter.dto.Literal.valueEquals(v1, v2); assertTrue(valueEquals); } else { assertEquals(expected, deserialized); @@ -70,8 +66,7 @@ public abstract class GeoToolsFilterModuleExpressionsTest extends ExpressionRoun String serialized = objectMapper.writeValueAsString(expected); print("serialized: {}", serialized); org.geotools.api.filter.capability.FunctionName deserialized = - objectMapper.readValue( - serialized, org.geotools.api.filter.capability.FunctionName.class); + objectMapper.readValue(serialized, org.geotools.api.filter.capability.FunctionName.class); assertEquals(dto.getName(), deserialized.getName()); assertEquals(dto.getArgumentCount(), deserialized.getArgumentCount()); assertEquals(dto.getArgumentNames(), deserialized.getArgumentNames()); diff --git a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleExpressions_JsonTest.java b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleExpressions_JsonTest.java index 1a4f080ca..6ab949219 100644 --- a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleExpressions_JsonTest.java +++ b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleExpressions_JsonTest.java @@ -5,7 +5,6 @@ package org.geotools.jackson.databind.filter; import com.fasterxml.jackson.databind.ObjectMapper; - import org.geotools.jackson.databind.util.ObjectMapperUtil; /** diff --git a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleExpressions_YamlTest.java b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleExpressions_YamlTest.java index c0bf298ef..2aec023a4 100644 --- a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleExpressions_YamlTest.java +++ b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleExpressions_YamlTest.java @@ -5,7 +5,6 @@ package org.geotools.jackson.databind.filter; import com.fasterxml.jackson.databind.ObjectMapper; - import org.geotools.jackson.databind.util.ObjectMapperUtil; /** diff --git a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleFiltersTest.java b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleFiltersTest.java index 37c1946b3..f9fe903f8 100644 --- a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleFiltersTest.java +++ b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleFiltersTest.java @@ -7,9 +7,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.fasterxml.jackson.databind.ObjectMapper; - import lombok.extern.slf4j.Slf4j; - import org.geotools.jackson.databind.filter.dto.Filter; import org.geotools.jackson.databind.filter.dto.SortBy; import org.geotools.jackson.databind.filter.mapper.FilterMapper; @@ -55,8 +53,7 @@ protected void print(String logmsg, Object... args) { String serialized = objectMapper.writeValueAsString(expected); print("serialized: {}", serialized); org.geotools.api.filter.sort.SortBy deserialized; - deserialized = - objectMapper.readValue(serialized, org.geotools.api.filter.sort.SortBy.class); + deserialized = objectMapper.readValue(serialized, org.geotools.api.filter.sort.SortBy.class); assertEquals(expected, deserialized); } diff --git a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleFilters_JsonTest.java b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleFilters_JsonTest.java index c417a3a73..b0fb64285 100644 --- a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleFilters_JsonTest.java +++ b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleFilters_JsonTest.java @@ -5,7 +5,6 @@ package org.geotools.jackson.databind.filter; import com.fasterxml.jackson.databind.ObjectMapper; - import org.geotools.jackson.databind.util.ObjectMapperUtil; /** diff --git a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleFilters_YamlTest.java b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleFilters_YamlTest.java index a065530f6..1f93b0fa9 100644 --- a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleFilters_YamlTest.java +++ b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/GeoToolsFilterModuleFilters_YamlTest.java @@ -5,7 +5,6 @@ package org.geotools.jackson.databind.filter; import com.fasterxml.jackson.databind.ObjectMapper; - import org.geotools.jackson.databind.util.ObjectMapperUtil; /** diff --git a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/dto/ExpressionSerializationTest.java b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/dto/ExpressionSerializationTest.java index b92265c11..e13f48a92 100644 --- a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/dto/ExpressionSerializationTest.java +++ b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/dto/ExpressionSerializationTest.java @@ -7,7 +7,6 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.fasterxml.jackson.databind.ObjectMapper; - import org.geotools.jackson.databind.filter.ExpressionRoundtripTest; import org.geotools.jackson.databind.filter.dto.Expression.FunctionName; import org.geotools.jackson.databind.util.ObjectMapperUtil; @@ -33,8 +32,7 @@ class ExpressionSerializationTest extends ExpressionRoundtripTest { protected @Override FunctionName roundtripTest(FunctionName dto) throws Exception { String serialized = objectMapper.writeValueAsString(dto); print("serialized: {}", serialized); - FunctionName deserialized = - objectMapper.readValue(serialized, Expression.FunctionName.class); + FunctionName deserialized = objectMapper.readValue(serialized, Expression.FunctionName.class); assertEquals(dto, deserialized); return deserialized; } diff --git a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/dto/FilterSerializationTest.java b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/dto/FilterSerializationTest.java index d57fafed2..33c0682c4 100644 --- a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/dto/FilterSerializationTest.java +++ b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/filter/dto/FilterSerializationTest.java @@ -7,9 +7,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import com.fasterxml.jackson.databind.ObjectMapper; - import lombok.extern.slf4j.Slf4j; - import org.geotools.jackson.databind.filter.FilterRoundtripTest; import org.geotools.jackson.databind.util.ObjectMapperUtil; import org.junit.jupiter.api.BeforeAll; diff --git a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/geojson/GeoToolsGeoJsonModuleTest.java b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/geojson/GeoToolsGeoJsonModuleTest.java index cfccc77a4..b61ba1843 100644 --- a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/geojson/GeoToolsGeoJsonModuleTest.java +++ b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/geojson/GeoToolsGeoJsonModuleTest.java @@ -9,9 +9,8 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; - +import java.util.EnumSet; import lombok.extern.slf4j.Slf4j; - import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.locationtech.jts.geom.Coordinate; @@ -29,8 +28,6 @@ import org.locationtech.jts.io.WKTReader; import org.locationtech.jts.io.WKTWriter; -import java.util.EnumSet; - /** * Test suite for {@link GeoToolsGeoJsonModule}, assuming it's registered to an {@link ObjectMapper} */ @@ -98,17 +95,14 @@ void testPolygon() throws JsonProcessingException { roundtripTest("POLYGON ((0 0, 10 10, 20 0, 0 0),(1 1, 9 9, 19 1, 1 1))"); roundtripTest("POLYGON Z((0 0 0, 10 10 1, 20 0 2, 0 0 0),(1 1 1, 9 9 2, 19 1 3, 1 1 1))"); roundtripTest("POLYGON M((0 0 0, 10 10 1, 20 0 2, 0 0 0),(1 1 1, 9 9 2, 19 1 3, 1 1 1))"); - roundtripTest( - "POLYGON ZM((0 0 0 0, 10 10 1 1, 20 0 2 2, 0 0 0 0),(1 1 1 1, 9 9 2 2, 19 1 3 3, 1 1 1 1))"); + roundtripTest("POLYGON ZM((0 0 0 0, 10 10 1 1, 20 0 2 2, 0 0 0 0),(1 1 1 1, 9 9 2 2, 19 1 3 3, 1 1 1 1))"); } @Test void testMultiPolygon() throws JsonProcessingException { roundtripTest("MULTIPOLYGON (((0 0, 10 10, 20 0, 0 0)), ((1 1, 9 9, 19 1, 1 1)))"); - roundtripTest( - "MULTIPOLYGON Z(((0 0 0, 10 10 1, 20 0 2, 0 0 0)), ((1 1 1, 9 9 2, 19 1 3, 1 1 1)))"); - roundtripTest( - "MULTIPOLYGON M(((0 0 0, 10 10 1, 20 0 2, 0 0 0)), ((1 1 1, 9 9 2, 19 1 3, 1 1 1)))"); + roundtripTest("MULTIPOLYGON Z(((0 0 0, 10 10 1, 20 0 2, 0 0 0)), ((1 1 1, 9 9 2, 19 1 3, 1 1 1)))"); + roundtripTest("MULTIPOLYGON M(((0 0 0, 10 10 1, 20 0 2, 0 0 0)), ((1 1 1, 9 9 2, 19 1 3, 1 1 1)))"); roundtripTest( "MULTIPOLYGON ZM(((0 0 0 0, 10 10 1 1, 20 0 2 2, 0 0 0 0)), ((1 1 1 1, 9 9 2 2, 19 1 3 3, 1 1 1 1)))"); } diff --git a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/geojson/GeoToolsGeoJsonModule_JsonTest.java b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/geojson/GeoToolsGeoJsonModule_JsonTest.java index a4cc04cad..fd0e17d6f 100644 --- a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/geojson/GeoToolsGeoJsonModule_JsonTest.java +++ b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/geojson/GeoToolsGeoJsonModule_JsonTest.java @@ -5,7 +5,6 @@ package org.geotools.jackson.databind.geojson; import com.fasterxml.jackson.databind.ObjectMapper; - import org.geotools.jackson.databind.util.ObjectMapperUtil; /** diff --git a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/geojson/GeoToolsGeoJsonModule_YamlTest.java b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/geojson/GeoToolsGeoJsonModule_YamlTest.java index fc2076189..6ad70dcb1 100644 --- a/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/geojson/GeoToolsGeoJsonModule_YamlTest.java +++ b/src/catalog/jackson-bindings/geotools/src/test/java/org/geotools/jackson/databind/geojson/GeoToolsGeoJsonModule_YamlTest.java @@ -5,7 +5,6 @@ package org.geotools.jackson.databind.geojson; import com.fasterxml.jackson.databind.ObjectMapper; - import org.geotools.jackson.databind.util.ObjectMapperUtil; /** diff --git a/src/catalog/jackson-bindings/starter/src/main/java/org/geoserver/cloud/autoconfigure/jackson/GeoServerJacksonBindingsAutoConfiguration.java b/src/catalog/jackson-bindings/starter/src/main/java/org/geoserver/cloud/autoconfigure/jackson/GeoServerJacksonBindingsAutoConfiguration.java index 3b9fea1ba..b17b0e9ac 100644 --- a/src/catalog/jackson-bindings/starter/src/main/java/org/geoserver/cloud/autoconfigure/jackson/GeoServerJacksonBindingsAutoConfiguration.java +++ b/src/catalog/jackson-bindings/starter/src/main/java/org/geoserver/cloud/autoconfigure/jackson/GeoServerJacksonBindingsAutoConfiguration.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.autoconfigure.jackson; import com.fasterxml.jackson.databind.Module; - import org.geoserver.jackson.databind.catalog.GeoServerCatalogModule; import org.geoserver.jackson.databind.config.GeoServerConfigModule; import org.springframework.boot.autoconfigure.AutoConfiguration; diff --git a/src/catalog/jackson-bindings/starter/src/main/java/org/geoserver/cloud/autoconfigure/jackson/GeoToolsJacksonBindingsAutoConfiguration.java b/src/catalog/jackson-bindings/starter/src/main/java/org/geoserver/cloud/autoconfigure/jackson/GeoToolsJacksonBindingsAutoConfiguration.java index 5df12dbdc..b927784a9 100644 --- a/src/catalog/jackson-bindings/starter/src/main/java/org/geoserver/cloud/autoconfigure/jackson/GeoToolsJacksonBindingsAutoConfiguration.java +++ b/src/catalog/jackson-bindings/starter/src/main/java/org/geoserver/cloud/autoconfigure/jackson/GeoToolsJacksonBindingsAutoConfiguration.java @@ -6,7 +6,6 @@ import com.fasterxml.jackson.databind.Module; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; - import org.geotools.jackson.databind.filter.GeoToolsFilterModule; import org.geotools.jackson.databind.geojson.GeoToolsGeoJsonModule; import org.springframework.boot.autoconfigure.AutoConfiguration; diff --git a/src/catalog/jackson-bindings/starter/src/test/java/org/geoserver/cloud/autoconfigure/jackson/GeoServerJacksonBindingsAutoConfigurationTest.java b/src/catalog/jackson-bindings/starter/src/test/java/org/geoserver/cloud/autoconfigure/jackson/GeoServerJacksonBindingsAutoConfigurationTest.java index d0afb16ba..173e4c937 100644 --- a/src/catalog/jackson-bindings/starter/src/test/java/org/geoserver/cloud/autoconfigure/jackson/GeoServerJacksonBindingsAutoConfigurationTest.java +++ b/src/catalog/jackson-bindings/starter/src/test/java/org/geoserver/cloud/autoconfigure/jackson/GeoServerJacksonBindingsAutoConfigurationTest.java @@ -8,7 +8,7 @@ import static org.assertj.core.api.HamcrestCondition.matching; import com.fasterxml.jackson.databind.ObjectMapper; - +import java.util.Set; import org.assertj.core.api.Condition; import org.geoserver.jackson.databind.catalog.GeoServerCatalogModule; import org.geoserver.jackson.databind.config.GeoServerConfigModule; @@ -18,30 +18,20 @@ import org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration; import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import java.util.Set; - class GeoServerJacksonBindingsAutoConfigurationTest { - private final ApplicationContextRunner contextRunner = - new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of( - GeoServerJacksonBindingsAutoConfiguration.class, - JacksonAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + GeoServerJacksonBindingsAutoConfiguration.class, JacksonAutoConfiguration.class)); @Test void testObjectMapper() { this.contextRunner.run(context -> assertThat(context).hasSingleBean(ObjectMapper.class)); - Condition> condition = - matching( - Matchers.hasItems( - new GeoServerCatalogModule().getTypeId(), - new GeoServerConfigModule().getTypeId())); - this.contextRunner.run( - context -> - assertThat(context) - .getBean(ObjectMapper.class) - .extracting(ObjectMapper::getRegisteredModuleIds) - .has(condition)); + Condition> condition = matching( + Matchers.hasItems(new GeoServerCatalogModule().getTypeId(), new GeoServerConfigModule().getTypeId())); + this.contextRunner.run(context -> assertThat(context) + .getBean(ObjectMapper.class) + .extracting(ObjectMapper::getRegisteredModuleIds) + .has(condition)); } } diff --git a/src/catalog/jackson-bindings/starter/src/test/java/org/geoserver/cloud/autoconfigure/jackson/GeoToolsJacksonBindingsAutoConfigurationTest.java b/src/catalog/jackson-bindings/starter/src/test/java/org/geoserver/cloud/autoconfigure/jackson/GeoToolsJacksonBindingsAutoConfigurationTest.java index cc8ec1ed2..7255ee6ae 100644 --- a/src/catalog/jackson-bindings/starter/src/test/java/org/geoserver/cloud/autoconfigure/jackson/GeoToolsJacksonBindingsAutoConfigurationTest.java +++ b/src/catalog/jackson-bindings/starter/src/test/java/org/geoserver/cloud/autoconfigure/jackson/GeoToolsJacksonBindingsAutoConfigurationTest.java @@ -9,7 +9,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; - +import java.util.Set; import org.assertj.core.api.Condition; import org.geotools.jackson.databind.filter.GeoToolsFilterModule; import org.geotools.jackson.databind.geojson.GeoToolsGeoJsonModule; @@ -20,44 +20,33 @@ import org.springframework.boot.test.context.FilteredClassLoader; import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import java.util.Set; - class GeoToolsJacksonBindingsAutoConfigurationTest { - private final ApplicationContextRunner contextRunner = - new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of( - GeoToolsJacksonBindingsAutoConfiguration.class, - JacksonAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + GeoToolsJacksonBindingsAutoConfiguration.class, JacksonAutoConfiguration.class)); @Test void testObjectMapper() { this.contextRunner.run(context -> assertThat(context).hasSingleBean(ObjectMapper.class)); - Condition> condition = - matching( - Matchers.hasItems( - new GeoToolsFilterModule().getTypeId(), - new GeoToolsGeoJsonModule().getTypeId(), - new JavaTimeModule().getTypeId())); - this.contextRunner.run( - context -> - assertThat(context) - .getBean(ObjectMapper.class) - .extracting(ObjectMapper::getRegisteredModuleIds) - .has(condition)); + Condition> condition = matching(Matchers.hasItems( + new GeoToolsFilterModule().getTypeId(), + new GeoToolsGeoJsonModule().getTypeId(), + new JavaTimeModule().getTypeId())); + this.contextRunner.run(context -> assertThat(context) + .getBean(ObjectMapper.class) + .extracting(ObjectMapper::getRegisteredModuleIds) + .has(condition)); } @Test void testFilterModuleAutoConfiguration() { - this.contextRunner.run( - context -> assertThat(context).hasSingleBean(GeoToolsFilterModule.class)); + this.contextRunner.run(context -> assertThat(context).hasSingleBean(GeoToolsFilterModule.class)); } @Test void testGeoJsonModuleAutoConfiguration() { - this.contextRunner.run( - context -> assertThat(context).hasSingleBean(GeoToolsGeoJsonModule.class)); + this.contextRunner.run(context -> assertThat(context).hasSingleBean(GeoToolsGeoJsonModule.class)); } @Test diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogFacadeExtensionAdapter.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogFacadeExtensionAdapter.java index daa596efc..9014a7aa7 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogFacadeExtensionAdapter.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogFacadeExtensionAdapter.java @@ -9,6 +9,13 @@ import static java.util.Spliterator.NONNULL; import static java.util.Spliterator.ORDERED; +import java.util.List; +import java.util.Spliterator; +import java.util.Spliterators; +import java.util.function.Consumer; +import java.util.logging.Logger; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogFacade; import org.geoserver.catalog.CatalogInfo; @@ -31,14 +38,6 @@ import org.geotools.api.filter.sort.SortBy; import org.geotools.util.logging.Logging; -import java.util.List; -import java.util.Spliterator; -import java.util.Spliterators; -import java.util.function.Consumer; -import java.util.logging.Logger; -import java.util.stream.Stream; -import java.util.stream.StreamSupport; - /** * Adapts a regular {@link CatalogFacade} to a {@link ExtendedCatalogFacade} * @@ -46,11 +45,9 @@ * adapting a legacy {@link CatalogFacade} implementation, that mixes up responsibilities with the * catalog itself. */ -public class CatalogFacadeExtensionAdapter extends ForwardingCatalogFacade - implements ExtendedCatalogFacade { +public class CatalogFacadeExtensionAdapter extends ForwardingCatalogFacade implements ExtendedCatalogFacade { - private CatalogInfoTypeRegistry> updateToSaveBridge = - new CatalogInfoTypeRegistry<>(); + private CatalogInfoTypeRegistry> updateToSaveBridge = new CatalogInfoTypeRegistry<>(); public CatalogFacadeExtensionAdapter(CatalogFacade facade) { super(facade); @@ -77,11 +74,10 @@ public CatalogFacadeExtensionAdapter(CatalogFacade facade) { public void setCatalog(Catalog catalog) { if (catalog != null) { if (!(catalog instanceof CatalogPlugin)) { - throw new IllegalArgumentException( - "Expected %s, got %s" - .formatted( - CatalogPlugin.class.getName(), - catalog.getClass().getName())); + throw new IllegalArgumentException("Expected %s, got %s" + .formatted( + CatalogPlugin.class.getName(), + catalog.getClass().getName())); } if (!(catalog instanceof SilentCatalog)) { catalog = new SilentCatalog((CatalogPlugin) catalog, this); @@ -181,14 +177,12 @@ public void fireAdded(CatalogInfo object) { } @Override - public void fireModified( - CatalogInfo object, List propertyNames, List oldValues, List newValues) { + public void fireModified(CatalogInfo object, List propertyNames, List oldValues, List newValues) { LOGGER.fine("Suppressing catalog pre-modify event from legacy CatalogFacade"); } @Override - public void firePostModified( - CatalogInfo object, List propertyNames, List oldValues, List newValues) { + public void firePostModified(CatalogInfo object, List propertyNames, List oldValues, List newValues) { LOGGER.fine("Suppressing catalog post-modify event from legacy CatalogFacade"); } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogInfoLookup.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogInfoLookup.java index 6aab27151..88ca63589 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogInfoLookup.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogInfoLookup.java @@ -8,28 +8,6 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Ordering; - -import org.geoserver.catalog.CatalogInfo; -import org.geoserver.catalog.DataStoreInfo; -import org.geoserver.catalog.LayerGroupInfo; -import org.geoserver.catalog.LayerInfo; -import org.geoserver.catalog.MapInfo; -import org.geoserver.catalog.NamespaceInfo; -import org.geoserver.catalog.ResourceInfo; -import org.geoserver.catalog.StoreInfo; -import org.geoserver.catalog.StyleInfo; -import org.geoserver.catalog.WorkspaceInfo; -import org.geoserver.catalog.impl.ClassMappings; -import org.geoserver.catalog.impl.LayerInfoImpl; -import org.geoserver.ows.util.OwsUtils; -import org.geotools.api.feature.type.Name; -import org.geotools.api.filter.Filter; -import org.geotools.api.filter.sort.SortBy; -import org.geotools.api.filter.sort.SortOrder; -import org.geotools.feature.NameImpl; -import org.geotools.util.logging.Logging; -import org.springframework.lang.Nullable; - import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; @@ -50,6 +28,26 @@ import java.util.function.Predicate; import java.util.logging.Logger; import java.util.stream.Stream; +import org.geoserver.catalog.CatalogInfo; +import org.geoserver.catalog.DataStoreInfo; +import org.geoserver.catalog.LayerGroupInfo; +import org.geoserver.catalog.LayerInfo; +import org.geoserver.catalog.MapInfo; +import org.geoserver.catalog.NamespaceInfo; +import org.geoserver.catalog.ResourceInfo; +import org.geoserver.catalog.StoreInfo; +import org.geoserver.catalog.StyleInfo; +import org.geoserver.catalog.WorkspaceInfo; +import org.geoserver.catalog.impl.ClassMappings; +import org.geoserver.catalog.impl.LayerInfoImpl; +import org.geoserver.ows.util.OwsUtils; +import org.geotools.api.feature.type.Name; +import org.geotools.api.filter.Filter; +import org.geotools.api.filter.sort.SortBy; +import org.geotools.api.filter.sort.SortOrder; +import org.geotools.feature.NameImpl; +import org.geotools.util.logging.Logging; +import org.springframework.lang.Nullable; /** * A support index for {@link DefaultMemoryCatalogFacade}, can perform fast lookups of {@link @@ -88,37 +86,28 @@ abstract class CatalogInfoLookup implements CatalogInfoRe r -> new NameImpl(r.getNamespace().getId(), r.getName()); /** Like LayerInfo, actually delegates to the resource logic */ - static final Function LAYER_NAME_MAPPER = - l -> RESOURCE_NAME_MAPPER.apply(l.getResource()); + static final Function LAYER_NAME_MAPPER = l -> RESOURCE_NAME_MAPPER.apply(l.getResource()); /** * The name uses the workspace id as it does not need to be updated when the workspace is * renamed */ static final Function LAYERGROUP_NAME_MAPPER = - lg -> - new NameImpl( - lg.getWorkspace() != null ? lg.getWorkspace().getId() : null, - lg.getName()); + lg -> new NameImpl(lg.getWorkspace() != null ? lg.getWorkspace().getId() : null, lg.getName()); - static final Function NAMESPACE_NAME_MAPPER = - n -> new NameImpl(n.getPrefix()); + static final Function NAMESPACE_NAME_MAPPER = n -> new NameImpl(n.getPrefix()); - static final Function WORKSPACE_NAME_MAPPER = - w -> new NameImpl(w.getName()); + static final Function WORKSPACE_NAME_MAPPER = w -> new NameImpl(w.getName()); static final Function STYLE_NAME_MAPPER = - s -> - new NameImpl( - s.getWorkspace() != null ? s.getWorkspace().getId() : null, - s.getName()); + s -> new NameImpl(s.getWorkspace() != null ? s.getWorkspace().getId() : null, s.getName()); protected ConcurrentMap, ConcurrentNavigableMap> idMultiMap = new ConcurrentHashMap<>(); protected ConcurrentMap, ConcurrentNavigableMap> nameMultiMap = new ConcurrentHashMap<>(); - protected ConcurrentMap, ConcurrentNavigableMap> - idToMameMultiMap = new ConcurrentHashMap<>(); + protected ConcurrentMap, ConcurrentNavigableMap> idToMameMultiMap = + new ConcurrentHashMap<>(); protected final Function nameMapper; @@ -147,15 +136,13 @@ ConcurrentMap getMapForValue( } protected ConcurrentMap getMapForType( - ConcurrentMap, ConcurrentNavigableMap> maps, - Class vc) { + ConcurrentMap, ConcurrentNavigableMap> maps, Class vc) { return maps.computeIfAbsent(vc, k -> new ConcurrentSkipListMap()); } private static void checkNotAProxy(CatalogInfo value) { if (Proxy.isProxyClass(value.getClass())) { - throw new IllegalArgumentException( - "Proxy values shall not be passed to CatalogInfoLookup"); + throw new IllegalArgumentException("Proxy values shall not be passed to CatalogInfoLookup"); } } @@ -168,12 +155,11 @@ public void add(T value) { Map idToName = getMapForValue(idToMameMultiMap, value); synchronized (idMap) { if (null != idMap.putIfAbsent(value.getId(), value)) { - String msg = - "%s:%s(%s) already exists" - .formatted( - ClassMappings.fromImpl(value.getClass()), - value.getId(), - nameMapper.apply(value).getLocalPart()); + String msg = "%s:%s(%s) already exists" + .formatted( + ClassMappings.fromImpl(value.getClass()), + value.getId(), + nameMapper.apply(value).getLocalPart()); LOGGER.warning(msg); } Name name = nameMapper.apply(value); @@ -208,8 +194,7 @@ public I update(final I value, Patch patch) { T storedValue = idMap.get(value.getId()); if (storedValue == null) { throw new NoSuchElementException( - "%s with id %s does not exist" - .formatted(value.getClass().getSimpleName(), value.getId())); + "%s with id %s does not exist".formatted(value.getClass().getSimpleName(), value.getId())); } synchronized (idMap) { patch.applyTo(storedValue); @@ -301,9 +286,7 @@ public static Comparator toComparator(Query query) Comparator comparator = providedOrder(); for (SortBy sortBy : query.getSortBy()) { comparator = - (comparator == PROVIDED_ORDER) - ? comparator(sortBy) - : comparator.thenComparing(comparator(sortBy)); + (comparator == PROVIDED_ORDER) ? comparator(sortBy) : comparator.thenComparing(comparator(sortBy)); } return comparator; } @@ -318,21 +301,20 @@ protected Predicate toPredicate(Filter filter) { } private static Comparator comparator(final SortBy sortOrder) { - Comparator comparator = - (o1, o2) -> { - Object v1 = OwsUtils.get(o1, sortOrder.getPropertyName().getPropertyName()); - Object v2 = OwsUtils.get(o2, sortOrder.getPropertyName().getPropertyName()); - if (v1 == null) { - return v2 == null ? 0 : -1; - } else if (v2 == null) { - return 1; - } - @SuppressWarnings({"rawtypes", "unchecked"}) - Comparable c1 = (Comparable) v1; - @SuppressWarnings({"rawtypes", "unchecked"}) - Comparable c2 = (Comparable) v2; - return c1.compareTo(c2); - }; + Comparator comparator = (o1, o2) -> { + Object v1 = OwsUtils.get(o1, sortOrder.getPropertyName().getPropertyName()); + Object v2 = OwsUtils.get(o2, sortOrder.getPropertyName().getPropertyName()); + if (v1 == null) { + return v2 == null ? 0 : -1; + } else if (v2 == null) { + return 1; + } + @SuppressWarnings({"rawtypes", "unchecked"}) + Comparable c1 = (Comparable) v1; + @SuppressWarnings({"rawtypes", "unchecked"}) + Comparable c2 = (Comparable) v2; + return c1.compareTo(c2); + }; if (SortOrder.DESCENDING.equals(sortOrder.getSortOrder())) { comparator = comparator.reversed(); } @@ -351,8 +333,7 @@ Stream list(Class clazz, Predicate predicate) { * with 20k layers go down from 50s to 44s (which is a lot, considering there is a lot of other * things going on) */ - Stream list( - Class clazz, Predicate predicate, Comparator comparator) { + Stream list(Class clazz, Predicate predicate, Comparator comparator) { requireNonNull(clazz); requireNonNull(predicate); requireNonNull(comparator); @@ -458,8 +439,7 @@ public void syncTo(CatalogInfoRepository target) { } } - static class NamespaceInfoLookup extends CatalogInfoLookup - implements NamespaceRepository { + static class NamespaceInfoLookup extends CatalogInfoLookup implements NamespaceRepository { private ConcurrentHashMap> index = new ConcurrentHashMap<>(); private static final Comparator VALUE_ORDER = @@ -485,8 +465,7 @@ public Optional findFirstByName(String name, Class< public void setDefaultNamespace(NamespaceInfo namespace) { requireNonNull(namespace); this.defaultNamespace = - findById(namespace.getId(), NamespaceInfo.class) - .orElseThrow(NoSuchElementException::new); + findById(namespace.getId(), NamespaceInfo.class).orElseThrow(NoSuchElementException::new); } @Override @@ -601,8 +580,7 @@ List valueList(String uri, boolean create) { } } - static class WorkspaceInfoLookup extends CatalogInfoLookup - implements WorkspaceRepository { + static class WorkspaceInfoLookup extends CatalogInfoLookup implements WorkspaceRepository { private WorkspaceInfo defaultWorkspace; @@ -611,8 +589,7 @@ public WorkspaceInfoLookup() { } @Override - public Optional findFirstByName( - String name, @Nullable Class clazz) { + public Optional findFirstByName(String name, @Nullable Class clazz) { requireNonNull(name); requireNonNull(clazz); return findByName(new NameImpl(name), clazz); @@ -621,8 +598,7 @@ public Optional findFirstByName( @Override public void setDefaultWorkspace(WorkspaceInfo workspace) { this.defaultWorkspace = - findById(workspace.getId(), WorkspaceInfo.class) - .orElseThrow(NoSuchElementException::new); + findById(workspace.getId(), WorkspaceInfo.class).orElseThrow(NoSuchElementException::new); } @Override @@ -650,8 +626,7 @@ public void setDefaultDataStore(WorkspaceInfo workspace, DataStoreInfo store) { requireNonNull(store); String wsId = workspace.getId(); final DataStoreInfo localStore = - super.findById(store.getId(), DataStoreInfo.class) - .orElseThrow(NoSuchElementException::new); + super.findById(store.getId(), DataStoreInfo.class).orElseThrow(NoSuchElementException::new); defaultStores.compute(wsId, (ws, oldDefaultStore) -> localStore); } @@ -678,8 +653,7 @@ public void dispose() { } @Override - public Stream findAllByWorkspace( - WorkspaceInfo workspace, Class clazz) { + public Stream findAllByWorkspace(WorkspaceInfo workspace, Class clazz) { requireNonNull(workspace); requireNonNull(clazz); return list(clazz, s -> workspace.getId().equals(s.getWorkspace().getId())); @@ -701,8 +675,7 @@ public Optional findByNameAndWorkspace( } } - static class LayerGroupInfoLookup extends CatalogInfoLookup - implements LayerGroupRepository { + static class LayerGroupInfoLookup extends CatalogInfoLookup implements LayerGroupRepository { public LayerGroupInfoLookup() { super(LayerGroupInfo.class, LAYERGROUP_NAME_MAPPER); } @@ -717,9 +690,7 @@ public Stream findAllByWorkspace(WorkspaceInfo workspace) { requireNonNull(workspace); return list( LayerGroupInfo.class, - lg -> - lg.getWorkspace() != null - && lg.getWorkspace().getId().equals(workspace.getId())); + lg -> lg.getWorkspace() != null && lg.getWorkspace().getId().equals(workspace.getId())); } @Override @@ -729,8 +700,7 @@ public Optional findByNameAndWorkspaceIsNull(String name) { } @Override - public Optional findByNameAndWorkspace( - String name, WorkspaceInfo workspace) { + public Optional findByNameAndWorkspace(String name, WorkspaceInfo workspace) { requireNonNull(name); requireNonNull(workspace); return findByName(new NameImpl(workspace.getId(), name), LayerGroupInfo.class); @@ -748,8 +718,7 @@ public MapInfoLookup() { * update the name lookup for the linked {@code LayerInfo} given that {@code LayerInfo.getName() * == LayerInfo.getResource().getName()} */ - static final class ResourceInfoLookup extends CatalogInfoLookup - implements ResourceRepository { + static final class ResourceInfoLookup extends CatalogInfoLookup implements ResourceRepository { private final LayerInfoLookup layers; public ResourceInfoLookup(LayerInfoLookup layers) { @@ -777,22 +746,21 @@ public Stream findAllByType(Class clazz) { } @Override - public Stream findAllByNamespace( - NamespaceInfo ns, Class clazz) { + public Stream findAllByNamespace(NamespaceInfo ns, Class clazz) { requireNonNull(ns); requireNonNull(clazz); return list(clazz, r -> ns.equals(r.getNamespace())); } @Override - public Optional findByStoreAndName( - StoreInfo store, String name, Class clazz) { + public Optional findByStoreAndName(StoreInfo store, String name, Class clazz) { requireNonNull(store); requireNonNull(name); requireNonNull(clazz); return findFirst( clazz, - r -> name.equals(r.getName()) && store.getId().equals(r.getStore().getId())); + r -> name.equals(r.getName()) + && store.getId().equals(r.getStore().getId())); } @Override @@ -812,8 +780,7 @@ public Optional findByNameAndNamespace( } } - static final class LayerInfoLookup extends CatalogInfoLookup - implements LayerRepository { + static final class LayerInfoLookup extends CatalogInfoLookup implements LayerRepository { public LayerInfoLookup() { super(LayerInfo.class, LAYER_NAME_MAPPER); @@ -822,8 +789,7 @@ public LayerInfoLookup() { void updateName(Name oldName, Name newName) { requireNonNull(oldName); requireNonNull(newName); - ConcurrentMap nameLookup = - getMapForType(nameMultiMap, LayerInfoImpl.class); + ConcurrentMap nameLookup = getMapForType(nameMultiMap, LayerInfoImpl.class); LayerInfo layer = nameLookup.remove(oldName); if (layer != null) { nameLookup.put(newName, layer); diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogInfoRepository.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogInfoRepository.java index a5335ed0c..a7c84fa44 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogInfoRepository.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogInfoRepository.java @@ -4,8 +4,9 @@ */ package org.geoserver.catalog.plugin; +import java.util.Optional; +import java.util.stream.Stream; import lombok.NonNull; - import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.DataStoreInfo; import org.geoserver.catalog.LayerGroupInfo; @@ -19,9 +20,6 @@ import org.geotools.api.filter.Filter; import org.springframework.lang.Nullable; -import java.util.Optional; -import java.util.stream.Stream; - /** * Raw data access API for {@link CatalogInfo} back-end implementations. * @@ -139,8 +137,7 @@ public interface WorkspaceRepository extends CatalogInfoRepository { - void setDefaultDataStore( - @NonNull WorkspaceInfo workspace, @NonNull DataStoreInfo dataStore); + void setDefaultDataStore(@NonNull WorkspaceInfo workspace, @NonNull DataStoreInfo dataStore); void unsetDefaultDataStore(@NonNull WorkspaceInfo workspace); @@ -148,8 +145,7 @@ void setDefaultDataStore( Stream getDefaultDataStores(); - Stream findAllByWorkspace( - @NonNull WorkspaceInfo workspace, @NonNull Class clazz); + Stream findAllByWorkspace(@NonNull WorkspaceInfo workspace, @NonNull Class clazz); Stream findAllByType(@NonNull Class clazz); @@ -164,8 +160,7 @@ Optional findByNameAndNamespace( Stream findAllByType(@NonNull Class clazz); - Stream findAllByNamespace( - @NonNull NamespaceInfo ns, @NonNull Class clazz); + Stream findAllByNamespace(@NonNull NamespaceInfo ns, @NonNull Class clazz); Optional findByStoreAndName( @NonNull StoreInfo store, @NonNull String name, @NonNull Class clazz); @@ -186,8 +181,7 @@ public interface LayerGroupRepository extends CatalogInfoRepository findByNameAndWorkspaceIsNull(@NonNull String name); - Optional findByNameAndWorkspace( - @NonNull String name, @NonNull WorkspaceInfo workspace); + Optional findByNameAndWorkspace(@NonNull String name, @NonNull WorkspaceInfo workspace); Stream findAllByWorkspaceIsNull(); @@ -202,8 +196,7 @@ public interface StyleRepository extends CatalogInfoRepository { Optional findByNameAndWordkspaceNull(@NonNull String name); - Optional findByNameAndWorkspace( - @NonNull String name, @NonNull WorkspaceInfo workspace); + Optional findByNameAndWorkspace(@NonNull String name, @NonNull WorkspaceInfo workspace); } public interface MapRepository extends CatalogInfoRepository {} diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogInfoRepositoryHolderImpl.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogInfoRepositoryHolderImpl.java index bb33279f0..bc5de88d5 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogInfoRepositoryHolderImpl.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogInfoRepositoryHolderImpl.java @@ -4,6 +4,7 @@ */ package org.geoserver.catalog.plugin; +import java.util.List; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.LayerGroupInfo; import org.geoserver.catalog.LayerInfo; @@ -22,8 +23,6 @@ import org.geoserver.catalog.plugin.CatalogInfoRepository.StyleRepository; import org.geoserver.catalog.plugin.CatalogInfoRepository.WorkspaceRepository; -import java.util.List; - public class CatalogInfoRepositoryHolderImpl implements CatalogInfoRepositoryHolder { protected NamespaceRepository namespaces; @@ -35,8 +34,7 @@ public class CatalogInfoRepositoryHolderImpl implements CatalogInfoRepositoryHol protected StyleRepository styles; protected MapRepository maps; - protected CatalogInfoTypeRegistry> repos = - new CatalogInfoTypeRegistry<>(); + protected CatalogInfoTypeRegistry> repos = new CatalogInfoTypeRegistry<>(); @SuppressWarnings("unchecked") @Override diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogInfoTypeRegistry.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogInfoTypeRegistry.java index 9bc841de5..6abb4fbee 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogInfoTypeRegistry.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogInfoTypeRegistry.java @@ -6,6 +6,10 @@ import static java.util.Objects.requireNonNull; +import java.util.Arrays; +import java.util.EnumMap; +import java.util.List; +import java.util.function.Consumer; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.CoverageInfo; import org.geoserver.catalog.CoverageStoreInfo; @@ -27,11 +31,6 @@ import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.impl.ClassMappings; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.List; -import java.util.function.Consumer; - /** * Utility class to register providers of any kind based on {@link CatalogInfo} subtypes. * @@ -63,8 +62,7 @@ public List getAll() { } @SuppressWarnings("unchecked") - public CatalogInfoTypeRegistry> consume( - Class type, Consumer with) { + public CatalogInfoTypeRegistry> consume(Class type, Consumer with) { return ((CatalogInfoTypeRegistry>) this).registerRecursively(type, with); } @@ -75,8 +73,7 @@ public CatalogInfoTypeRegistry> consume( * WMSStoreInfo}, and {@link WMTSStoreInfo}) */ @SuppressWarnings("unchecked") - public CatalogInfoTypeRegistry registerRecursively( - Class type, R resource) { + public CatalogInfoTypeRegistry registerRecursively(Class type, R resource) { ClassMappings key = determineKey(type); Class mainType = (Class) key.getInterface(); @@ -124,10 +121,7 @@ public static Class resolveType(T object) { } public static ClassMappings determineKey(Class type) { - ClassMappings cm = - type.isInterface() - ? ClassMappings.fromInterface(type) - : ClassMappings.fromImpl(type); + ClassMappings cm = type.isInterface() ? ClassMappings.fromInterface(type) : ClassMappings.fromImpl(type); if (cm != null) { return cm; } @@ -135,23 +129,22 @@ public static ClassMappings determineKey(Class type) { "Unable to determine CatalogInfo subtype from class %s".formatted(type.getName())); } - private static final List> instanceOfLookup = - Arrays.asList( - WorkspaceInfo.class, - NamespaceInfo.class, - DataStoreInfo.class, - CoverageStoreInfo.class, - WMSStoreInfo.class, - WMTSStoreInfo.class, - StoreInfo.class, - FeatureTypeInfo.class, - CoverageInfo.class, - WMSLayerInfo.class, - WMTSLayerInfo.class, - ResourceInfo.class, - LayerInfo.class, - LayerGroupInfo.class, - PublishedInfo.class, - StyleInfo.class, - MapInfo.class); + private static final List> instanceOfLookup = Arrays.asList( + WorkspaceInfo.class, + NamespaceInfo.class, + DataStoreInfo.class, + CoverageStoreInfo.class, + WMSStoreInfo.class, + WMTSStoreInfo.class, + StoreInfo.class, + FeatureTypeInfo.class, + CoverageInfo.class, + WMSLayerInfo.class, + WMTSLayerInfo.class, + ResourceInfo.class, + LayerInfo.class, + LayerGroupInfo.class, + PublishedInfo.class, + StyleInfo.class, + MapInfo.class); } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogPlugin.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogPlugin.java index 3a5319d6a..4f63bea6e 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogPlugin.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogPlugin.java @@ -8,9 +8,17 @@ import com.github.f4b6a3.ulid.Ulid; import com.github.f4b6a3.ulid.UlidCreator; - +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.function.UnaryOperator; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.stream.Stream; +import javax.annotation.Nullable; import lombok.NonNull; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogFacade; import org.geoserver.catalog.CatalogInfo; @@ -52,18 +60,6 @@ import org.geotools.util.Converters; import org.geotools.util.logging.Logging; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.function.UnaryOperator; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.stream.Stream; - -import javax.annotation.Nullable; - /** * Alternative to {@link org.geoserver.catalog.impl.CatalogImpl} to improve separation of concerns * between levels of abstractions and favor plug-ability of the underlying object store. @@ -221,8 +217,8 @@ public void add(@NonNull CatalogInfo info) { case LayerGroupInfo lg -> add(lg); case StyleInfo s -> add(s); case MapInfo m -> add(m); - default -> throw new IllegalArgumentException( - "Unexpected value: %s".formatted(ModificationProxy.unwrap(info).getClass())); + default -> throw new IllegalArgumentException("Unexpected value: %s" + .formatted(ModificationProxy.unwrap(info).getClass())); } } @@ -240,8 +236,8 @@ public void remove(@NonNull CatalogInfo info) { case LayerGroupInfo lg -> remove(lg); case StyleInfo s -> remove(s); case MapInfo m -> remove(m); - default -> throw new IllegalArgumentException( - "Unexpected value: %s".formatted(ModificationProxy.unwrap(info).getClass())); + default -> throw new IllegalArgumentException("Unexpected value: %s" + .formatted(ModificationProxy.unwrap(info).getClass())); } } @@ -304,8 +300,7 @@ public void save(StoreInfo store) { // they've been rolled back try { namespaceChange.ifPresent( - newNamespace -> - updateResourcesNamespace(store, oldWorkspace.getName(), newNamespace)); + newNamespace -> updateResourcesNamespace(store, oldWorkspace.getName(), newNamespace)); } catch (RuntimeException e) { rollback(store, rollbackCopy); throw e; @@ -324,9 +319,7 @@ public void save(StoreInfo store) { } protected @Override void rollbackNamespaces( - List storeResources, - String oldNamespacePrefix, - NamespaceInfo newNamespace) { + List storeResources, String oldNamespacePrefix, NamespaceInfo newNamespace) { // rolback the namespace on all the resources that got it changed final NamespaceInfo rolbackNamespace = getNamespaceByPrefix(oldNamespacePrefix); Objects.requireNonNull(rolbackNamespace); @@ -355,8 +348,7 @@ public void updateNamespace(ResourceInfo resource, NamespaceInfo newNamespace) { } @Override - public List getStoresByWorkspace( - WorkspaceInfo workspace, Class clazz) { + public List getStoresByWorkspace(WorkspaceInfo workspace, Class clazz) { return unmodifiableList(facade.getStoresByWorkspace(workspace, clazz)); } @@ -381,7 +373,9 @@ public void setDefaultDataStore(WorkspaceInfo workspace, DataStoreInfo store) { if (!store.getWorkspace().equals(workspace)) { throw new IllegalArgumentException( "Trying to mark as default for workspace %s a store that is contained in %s" - .formatted(workspace.getName(), store.getWorkspace().getName())); + .formatted( + workspace.getName(), + store.getWorkspace().getName())); } } @@ -428,8 +422,7 @@ public List getResources(Class clazz) { } @Override - public List getResourcesByNamespace( - NamespaceInfo namespace, Class clazz) { + public List getResourcesByNamespace(NamespaceInfo namespace, Class clazz) { return unmodifiableList(facade.getResourcesByNamespace(namespace, clazz)); } @@ -560,8 +553,7 @@ public void setDefaultNamespace(NamespaceInfo defaultNamespace) { if (defaultNamespace != null) { NamespaceInfo ns = getNamespaceByPrefix(defaultNamespace.getPrefix()); if (ns == null) { - throw new IllegalArgumentException( - "No such namespace: '%s'".formatted(defaultNamespace.getPrefix())); + throw new IllegalArgumentException("No such namespace: '%s'".formatted(defaultNamespace.getPrefix())); } else { defaultNamespace = ns; } @@ -607,8 +599,7 @@ public void setDefaultWorkspace(WorkspaceInfo defaultWorkspace) { if (defaultWorkspace != null) { WorkspaceInfo ws = facade.getWorkspaceByName(defaultWorkspace.getName()); if (ws == null) { - throw new IllegalArgumentException( - "No such workspace: '%s'".formatted(defaultWorkspace.getName())); + throw new IllegalArgumentException("No such workspace: '%s'".formatted(defaultWorkspace.getName())); } else { defaultWorkspace = ws; } @@ -679,14 +670,9 @@ public void sync(CatalogImpl other) { /** Overrides to call {@link ExtendedCatalogFacade#query(Query)} */ @Override public CloseableIterator list( - final Class of, - final Filter filter, - Integer offset, - Integer count, - SortBy sortOrder) { + final Class of, final Filter filter, Integer offset, Integer count, SortBy sortOrder) { ExtendedCatalogFacade facade = getFacade(); - if (sortOrder != null - && !facade.canSort(of, sortOrder.getPropertyName().getPropertyName())) { + if (sortOrder != null && !facade.canSort(of, sortOrder.getPropertyName().getPropertyName())) { // TODO: use GeoTools' merge-sort code to provide sorting anyways throw new UnsupportedOperationException( "Catalog backend can't sort on property %s in-process sorting is pending implementation" @@ -703,8 +689,7 @@ public Optional findById(@NonNull String id) { } @Override - public T get(Class type, Filter filter) - throws IllegalArgumentException { + public T get(Class type, Filter filter) throws IllegalArgumentException { // try optimizing by querying by id first, defer to regular filter query if // filter is not and Id filter return getIdIfIdFilter(filter) // @@ -739,8 +724,7 @@ private Optional getIdIfIdFilter(Filter filter) { } } else if (filter instanceof PropertyIsEqualTo eq) { boolean idProperty = - (eq.getExpression1() instanceof PropertyName prop) - && "id".equals(prop.getPropertyName()); + (eq.getExpression1() instanceof PropertyName prop) && "id".equals(prop.getPropertyName()); if (idProperty && eq.getExpression2() instanceof Literal) { id = Converters.convert(eq.getExpression2().evaluate(null), String.class); } @@ -865,10 +849,9 @@ private void doRemove(T found) { protected void setId(@NonNull CatalogInfo o) { if (null == o.getId()) { - String type = - ClassMappings.fromImpl(ModificationProxy.unwrap(o).getClass()) - .getInterface() - .getSimpleName(); + String type = ClassMappings.fromImpl(ModificationProxy.unwrap(o).getClass()) + .getInterface() + .getSimpleName(); Ulid ulid = UlidCreator.getMonotonicUlid(); String id = "%s-%s".formatted(type, ulid); OwsUtils.set(o, "id", id); diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogPluginStyleResourcePersister.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogPluginStyleResourcePersister.java index 9821a1fd2..5340030f5 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogPluginStyleResourcePersister.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/CatalogPluginStyleResourcePersister.java @@ -5,7 +5,6 @@ package org.geoserver.catalog.plugin; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.Info; diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/DefaultMemoryCatalogFacade.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/DefaultMemoryCatalogFacade.java index 4fc595094..b908f24b8 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/DefaultMemoryCatalogFacade.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/DefaultMemoryCatalogFacade.java @@ -4,9 +4,12 @@ */ package org.geoserver.catalog.plugin; +import java.rmi.server.UID; +import java.util.LinkedHashSet; +import java.util.List; +import javax.annotation.Nullable; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogFacade; import org.geoserver.catalog.CatalogInfo; @@ -38,19 +41,12 @@ import org.geoserver.catalog.plugin.CatalogInfoLookup.WorkspaceInfoLookup; import org.geoserver.ows.util.OwsUtils; -import java.rmi.server.UID; -import java.util.LinkedHashSet; -import java.util.List; - -import javax.annotation.Nullable; - /** * Default catalog facade implementation using in-memory {@link CatalogRepository repositories} to * store the {@link CatalogInfo} */ @Slf4j -public class DefaultMemoryCatalogFacade extends RepositoryCatalogFacadeImpl - implements CatalogFacade { +public class DefaultMemoryCatalogFacade extends RepositoryCatalogFacadeImpl implements CatalogFacade { public DefaultMemoryCatalogFacade() { this(null); @@ -118,8 +114,7 @@ protected void resolve(LayerGroupInfo layerGroup) { } } - private void resolveLayerGroupStyles( - List assignedLayers, List styles) { + private void resolveLayerGroupStyles(List assignedLayers, List styles) { for (int i = 0; i < styles.size(); i++) { StyleInfo s = styles.get(i); if (s != null) { @@ -158,8 +153,7 @@ private void resolveLayerGroupLayers(List layers) { private PublishedInfo resolveLayerGroupLayers(@NonNull PublishedInfo published) { PublishedInfo resolved = unwrap(ResolvingProxy.resolve(getCatalog(), published)); // special case to handle catalog loading, when nested publishables might not be loaded. - if (resolved == null - && (published instanceof LayerInfo || published instanceof LayerGroupInfo)) { + if (resolved == null && (published instanceof LayerInfo || published instanceof LayerGroupInfo)) { resolved = published; } return resolved; diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/ExtendedCatalogFacade.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/ExtendedCatalogFacade.java index c5512bbc3..686be4dbe 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/ExtendedCatalogFacade.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/ExtendedCatalogFacade.java @@ -4,8 +4,14 @@ */ package org.geoserver.catalog.plugin; +import java.io.Closeable; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Consumer; +import java.util.stream.Stream; +import javax.annotation.Nullable; import lombok.NonNull; - import org.geoserver.catalog.CatalogFacade; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.LayerGroupInfo; @@ -23,15 +29,6 @@ import org.geotools.api.filter.Filter; import org.geotools.api.filter.sort.SortBy; -import java.io.Closeable; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.function.Consumer; -import java.util.stream.Stream; - -import javax.annotation.Nullable; - /** * {@link CatalogFacade} with additional methods * @@ -41,15 +38,14 @@ public interface ExtendedCatalogFacade extends CatalogFacade { default void forEach(Consumer consumer) { - List> types = - List.of( - WorkspaceInfo.class, - NamespaceInfo.class, - StoreInfo.class, - ResourceInfo.class, - StyleInfo.class, - LayerInfo.class, - LayerGroupInfo.class); + List> types = List.of( + WorkspaceInfo.class, + NamespaceInfo.class, + StoreInfo.class, + ResourceInfo.class, + StyleInfo.class, + LayerInfo.class, + LayerGroupInfo.class); for (var type : types) { try (var stream = query(Query.valueOf(type, Filter.INCLUDE))) { @@ -83,11 +79,9 @@ default Optional get(@NonNull String id, @NonNull Cla case WORKSPACE -> getWorkspace(id); case NAMESPACE -> getNamespace(id); - case DATASTORE, COVERAGESTORE, WMSSTORE, WMTSSTORE, STORE -> getStore( - id, StoreInfo.class); + case DATASTORE, COVERAGESTORE, WMSSTORE, WMTSSTORE, STORE -> getStore(id, StoreInfo.class); - case FEATURETYPE, COVERAGE, WMSLAYER, WMTSLAYER, RESOURCE -> getResource( - id, ResourceInfo.class); + case FEATURETYPE, COVERAGE, WMSLAYER, WMTSLAYER, RESOURCE -> getResource(id, ResourceInfo.class); case LAYER -> getLayer(id); case LAYERGROUP -> getLayerGroup(id); @@ -95,8 +89,7 @@ default Optional get(@NonNull String id, @NonNull Cla case STYLE -> getStyle(id); case MAP -> getMap(id); - default -> throw new IllegalArgumentException( - "Unknown CatalogInfo type " + type); + default -> throw new IllegalArgumentException("Unknown CatalogInfo type " + type); }; return Optional.ofNullable(found).filter(type::isInstance).map(type::cast); diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/IsolatedCatalogFacade.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/IsolatedCatalogFacade.java index 66a77c02f..9e4049a57 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/IsolatedCatalogFacade.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/IsolatedCatalogFacade.java @@ -5,7 +5,13 @@ package org.geoserver.catalog.plugin; import com.google.common.collect.Iterators; - +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import java.util.function.Predicate; +import java.util.stream.Stream; +import javax.annotation.Nullable; import org.geoserver.catalog.CatalogCapabilities; import org.geoserver.catalog.CatalogFacade; import org.geoserver.catalog.CatalogInfo; @@ -26,15 +32,6 @@ import org.geotools.api.filter.Filter; import org.geotools.api.filter.sort.SortBy; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; -import java.util.Objects; -import java.util.function.Predicate; -import java.util.stream.Stream; - -import javax.annotation.Nullable; - /** Copy of package private {@code org.geoserver.catalog.impl.IsolatedCatalogFacade} */ public final class IsolatedCatalogFacade extends ForwardingExtendedCatalogFacade { @@ -48,17 +45,13 @@ public T getStore(String id, Class clazz) { } @Override - public T getStoreByName( - WorkspaceInfo workspace, String name, Class clazz) { + public T getStoreByName(WorkspaceInfo workspace, String name, Class clazz) { return canSeeWorkspace(workspace) ? facade.getStoreByName(workspace, name, clazz) : null; } @Override - public List getStoresByWorkspace( - WorkspaceInfo workspace, Class clazz) { - return canSeeWorkspace(workspace) - ? facade.getStoresByWorkspace(workspace, clazz) - : Collections.emptyList(); + public List getStoresByWorkspace(WorkspaceInfo workspace, Class clazz) { + return canSeeWorkspace(workspace) ? facade.getStoresByWorkspace(workspace, clazz) : Collections.emptyList(); } @Override @@ -77,8 +70,7 @@ public T getResource(String id, Class clazz) { } @Override - public T getResourceByName( - NamespaceInfo namespace, String name, Class clazz) { + public T getResourceByName(NamespaceInfo namespace, String name, Class clazz) { NamespaceInfo localNamespace = tryMatchLocalNamespace(namespace); if (localNamespace != null) { // the URIs of the provided namespace and of the local workspace namespace matched @@ -93,20 +85,17 @@ public List getResources(Class clazz) { } @Override - public List getResourcesByNamespace( - NamespaceInfo namespace, Class clazz) { + public List getResourcesByNamespace(NamespaceInfo namespace, Class clazz) { NamespaceInfo localNamespace = tryMatchLocalNamespace(namespace); if (localNamespace != null) { // the URIs of the provided namespace and of the local workspace namespace matched return facade.getResourcesByNamespace(localNamespace, clazz); } - return filterIsolated( - facade.getResourcesByNamespace(namespace, clazz), clazz, this::filter); + return filterIsolated(facade.getResourcesByNamespace(namespace, clazz), clazz, this::filter); } @Override - public T getResourceByStore( - StoreInfo store, String name, Class clazz) { + public T getResourceByStore(StoreInfo store, String name, Class clazz) { return enforceResourceIsolation(facade.getResourceByStore(store, name, clazz)); } @@ -162,8 +151,7 @@ public List getLayerGroups() { @Override public List getLayerGroupsByWorkspace(WorkspaceInfo workspace) { - return filterIsolated( - facade.getLayerGroupsByWorkspace(workspace), LayerGroupInfo.class, this::filter); + return filterIsolated(facade.getLayerGroupsByWorkspace(workspace), LayerGroupInfo.class, this::filter); } @Override @@ -206,8 +194,7 @@ public List getStyles() { @Override public List getStylesByWorkspace(WorkspaceInfo workspace) { - return filterIsolated( - facade.getStylesByWorkspace(workspace), StyleInfo.class, this::filter); + return filterIsolated(facade.getStylesByWorkspace(workspace), StyleInfo.class, this::filter); } @Override @@ -411,8 +398,7 @@ private boolean canSeeWorkspace(WorkspaceInfo workspace) { WorkspaceInfo localWorkspace = getLocalWorkspace(); // the workspace content will be visible only if we are in the context of one // of its virtual services - return localWorkspace != null - && Objects.equals(localWorkspace.getName(), workspace.getName()); + return localWorkspace != null && Objects.equals(localWorkspace.getName(), workspace.getName()); } /** @@ -424,8 +410,7 @@ private boolean canSeeWorkspace(WorkspaceInfo workspace) { * @param filter filter that checks if an element should be visible * @return a list wrapped with a modification proxy that contains the visible catalog objects */ - private List filterIsolated( - List objects, Class type, Predicate filter) { + private List filterIsolated(List objects, Class type, Predicate filter) { // unwrap the catalog objects list List unwrapped = ModificationProxy.unwrap(objects); // filter the non visible catalog objects and wrap the resulting list with a modification @@ -446,8 +431,7 @@ private NamespaceInfo tryMatchLocalNamespace(NamespaceInfo namespace) { if (localWorkspace != null) { // get the namespace for the current local workspace NamespaceInfo localNamespace = facade.getNamespaceByPrefix(localWorkspace.getName()); - if (localNamespace != null - && Objects.equals(localNamespace.getURI(), namespace.getURI())) { + if (localNamespace != null && Objects.equals(localNamespace.getURI(), namespace.getURI())) { // the URIs match, let's return the local workspace namespace return localNamespace; } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/Patch.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/Patch.java index 42509aa23..bd3a6e5d6 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/Patch.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/Patch.java @@ -4,13 +4,6 @@ */ package org.geoserver.catalog.plugin; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.NonNull; - -import org.geoserver.catalog.impl.ModificationProxy; -import org.geoserver.ows.util.OwsUtils; - import java.io.Serializable; import java.lang.reflect.Method; import java.lang.reflect.Proxy; @@ -22,6 +15,11 @@ import java.util.Objects; import java.util.Optional; import java.util.stream.Collectors; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.NonNull; +import org.geoserver.catalog.impl.ModificationProxy; +import org.geoserver.ows.util.OwsUtils; @NoArgsConstructor public @Data class Patch implements Serializable { @@ -51,7 +49,10 @@ public static boolean valueEquals(final Object v1, final Object v2) { return true; } - if (v1 != null && v1.getClass().isArray() && v2 != null && v2.getClass().isArray()) { + if (v1 != null + && v1.getClass().isArray() + && v2 != null + && v2.getClass().isArray()) { if (!v1.getClass().equals(v2.getClass())) return false; final Class componentType = v1.getClass().getComponentType(); @@ -65,8 +66,7 @@ public static boolean valueEquals(final Object v1, final Object v2) { case "long" -> Arrays.equals((long[]) v1, (long[]) v2); case "float" -> Arrays.equals((float[]) v1, (float[]) v2); case "double" -> Arrays.equals((double[]) v1, (double[]) v2); - default -> throw new IllegalArgumentException( - "Unexpected value: %s".formatted(componentType)); + default -> throw new IllegalArgumentException("Unexpected value: %s".formatted(componentType)); }; } else { Object[] a1 = (Object[]) v1; @@ -160,8 +160,7 @@ private static void applyCollectionValueChange(Object target, final Property cha try { currentValue.clear(); } catch (UnsupportedOperationException e) { - throw new IllegalArgumentException( - "Collection property %s is immutable".formatted(propertyName), e); + throw new IllegalArgumentException("Collection property %s is immutable".formatted(propertyName), e); } if (newValue != null) { currentValue.addAll(newValue); @@ -185,8 +184,7 @@ private static void applyMapValueChange(Object target, final Property change) { private static Method findGetterOrThrow(Class objectType, Property change) { Method getter = OwsUtils.getter(objectType, change.getName(), null); if (getter == null) { - throw new IllegalArgumentException( - "No such property in target object: %s".formatted(change.getName())); + throw new IllegalArgumentException("No such property in target object: %s".formatted(change.getName())); } return getter; } @@ -201,10 +199,9 @@ private static boolean isCollection(Method getter) { @Override public String toString() { - String props = - this.getPatches().stream() - .map(p -> "(%s: %s)".formatted(p.getName(), p.getValue())) - .collect(Collectors.joining(",")); + String props = this.getPatches().stream() + .map(p -> "(%s: %s)".formatted(p.getName(), p.getValue())) + .collect(Collectors.joining(",")); return "%s[%s]".formatted(getClass().getSimpleName(), props); } } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/PropertyDiff.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/PropertyDiff.java index 1c010ad1e..b95dbb3d7 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/PropertyDiff.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/PropertyDiff.java @@ -4,26 +4,6 @@ */ package org.geoserver.catalog.plugin; -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.NonNull; -import lombok.extern.slf4j.Slf4j; - -import org.geoserver.catalog.Catalog; -import org.geoserver.catalog.Info; -import org.geoserver.catalog.MetadataMap; -import org.geoserver.catalog.PublishedInfo; -import org.geoserver.catalog.impl.ClassMappings; -import org.geoserver.catalog.impl.ModificationProxy; -import org.geoserver.catalog.impl.ProxyUtils; -import org.geoserver.config.ServiceInfo; -import org.geoserver.ows.util.ClassProperties; -import org.geoserver.ows.util.OwsUtils; -import org.geotools.api.referencing.crs.CoordinateReferenceSystem; -import org.geotools.api.util.InternationalString; -import org.geotools.referencing.CRS; - import java.io.Serializable; import java.lang.reflect.Proxy; import java.util.ArrayList; @@ -46,6 +26,24 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.NonNull; +import lombok.extern.slf4j.Slf4j; +import org.geoserver.catalog.Catalog; +import org.geoserver.catalog.Info; +import org.geoserver.catalog.MetadataMap; +import org.geoserver.catalog.PublishedInfo; +import org.geoserver.catalog.impl.ClassMappings; +import org.geoserver.catalog.impl.ModificationProxy; +import org.geoserver.catalog.impl.ProxyUtils; +import org.geoserver.config.ServiceInfo; +import org.geoserver.ows.util.ClassProperties; +import org.geoserver.ows.util.OwsUtils; +import org.geotools.api.referencing.crs.CoordinateReferenceSystem; +import org.geotools.api.util.InternationalString; +import org.geotools.referencing.CRS; @Slf4j public @Data class PropertyDiff implements Serializable { @@ -91,7 +89,9 @@ public Change get(int index) { } public Optional get(@NonNull String propertyName) { - return changes.stream().filter(c -> propertyName.equals(c.getPropertyName())).findFirst(); + return changes.stream() + .filter(c -> propertyName.equals(c.getPropertyName())) + .findFirst(); } public List getPropertyNames() { @@ -145,10 +145,8 @@ protected boolean isSameCrs() { if (neitherIsNull()) { try { final boolean fullScan = false; // don't bother - String id1 = - CRS.lookupIdentifier((CoordinateReferenceSystem) oldValue, fullScan); - String id2 = - CRS.lookupIdentifier((CoordinateReferenceSystem) newValue, fullScan); + String id1 = CRS.lookupIdentifier((CoordinateReferenceSystem) oldValue, fullScan); + String id2 = CRS.lookupIdentifier((CoordinateReferenceSystem) newValue, fullScan); boolean sameId = Objects.equals(id1, id2); return sameId && CRS.equalsIgnoreMetadata(oldValue, newValue); } catch (Exception e) { @@ -159,8 +157,7 @@ protected boolean isSameCrs() { } protected boolean isNullInternationalStringOp() { - return isNullOrEmpty(toStringOrNull(oldValue)) - && isNullOrEmpty(toStringOrNull(newValue)); + return isNullOrEmpty(toStringOrNull(oldValue)) && isNullOrEmpty(toStringOrNull(newValue)); } private String toStringOrNull(Object o) { @@ -223,14 +220,12 @@ public static PropertyDiff valueOf( final @NonNull List newValues) { PropertyDiffBuilder builder = PropertyDiff.builder(); - IntStream.range(0, propertyNames.size()) - .forEach( - i -> { - String prop = propertyNames.get(i); - Object oldV = hanldeProxy(oldValues.get(i)); - Object newV = hanldeProxy(newValues.get(i)); - builder.with(prop, oldV, newV); - }); + IntStream.range(0, propertyNames.size()).forEach(i -> { + String prop = propertyNames.get(i); + Object oldV = hanldeProxy(oldValues.get(i)); + Object newV = hanldeProxy(newValues.get(i)); + builder.with(prop, oldV, newV); + }); return builder.build(); } @@ -250,15 +245,11 @@ private static Object hanldeProxy(Object value) { @SuppressWarnings("unchecked") private static Class findInfoIterface(Class of) { - return (Class) - Arrays.stream(of.getInterfaces()) - .filter(c -> !IGNORE.contains(c)) - .findFirst() - .orElseThrow( - () -> - new IllegalArgumentException( - "Unable to find most concrete Info sub-interface of %s" - .formatted(of.getCanonicalName()))); + return (Class) Arrays.stream(of.getInterfaces()) + .filter(c -> !IGNORE.contains(c)) + .findFirst() + .orElseThrow(() -> new IllegalArgumentException( + "Unable to find most concrete Info sub-interface of %s".formatted(of.getCanonicalName()))); } public static PropertyDiff empty() { @@ -289,16 +280,14 @@ public static class PropertyDiffBuilder { } public PropertyDiff build() { - List changes = - IntStream.range(0, propertyNames.size()) - .mapToObj( - i -> { - String name = propertyNames.get(i); - Object oldV = oldValues.get(i); - Object newV = newValues.get(i); - return Change.valueOf(name, oldV, newV); - }) - .toList(); + List changes = IntStream.range(0, propertyNames.size()) + .mapToObj(i -> { + String name = propertyNames.get(i); + Object oldV = oldValues.get(i); + Object newV = newValues.get(i); + return Change.valueOf(name, oldV, newV); + }) + .toList(); return new PropertyDiff(changes); } @@ -306,9 +295,7 @@ public PropertyDiffBuilder with(String property, Object newValue) { property = fixCase(property); Class type = info.getClass(); ClassProperties classProperties = OwsUtils.getClassProperties(type); - if (null - == classProperties.getter( - property, newValue == null ? null : newValue.getClass())) { + if (null == classProperties.getter(property, newValue == null ? null : newValue.getClass())) { throw new IllegalArgumentException("No such property: %s".formatted(property)); } @@ -338,8 +325,7 @@ public static Collection copyOf(Collection val) { return copyOf(val, Function.identity()); } - public static Collection copyOf( - Collection val, Function mapper) { + public static Collection copyOf(Collection val, Function mapper) { Stream stream = val.stream().map(PropertyDiffBuilder::copySafe).map(mapper); @@ -369,13 +355,12 @@ public static Map copyOf(final Map val, Function val } else { target = new HashMap<>(); } - val.forEach( - (k, v) -> { - Object key = copySafe(k); - V value = copySafe(v); - R result = valueMapper.apply(value); - target.put(key, result); - }); + val.forEach((k, v) -> { + Object key = copySafe(k); + V value = copySafe(v); + R result = valueMapper.apply(value); + target.put(key, result); + }); return target; } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/Query.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/Query.java index 7cb911f34..e694837fb 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/Query.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/Query.java @@ -4,24 +4,22 @@ */ package org.geoserver.catalog.plugin; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.OptionalInt; +import java.util.stream.Stream; import lombok.Data; import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.experimental.Accessors; - import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.Info; import org.geotools.api.filter.Filter; import org.geotools.api.filter.sort.SortBy; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Objects; -import java.util.OptionalInt; -import java.util.stream.Stream; - /** */ @NoArgsConstructor @RequiredArgsConstructor @@ -74,16 +72,11 @@ public static Query valueOf(Class type, Filter fil @SuppressWarnings("unchecked") public static Query valueOf( - Class type, - Filter filter, - Integer offset, - Integer count, - SortBy... sortOrder) { + Class type, Filter filter, Integer offset, Integer count, SortBy... sortOrder) { - List sortBy = - sortOrder == null - ? Collections.emptyList() - : Stream.of(sortOrder).filter(Objects::nonNull).toList(); + List sortBy = sortOrder == null + ? Collections.emptyList() + : Stream.of(sortOrder).filter(Objects::nonNull).toList(); filter = filter == null ? Filter.INCLUDE : filter; return new Query<>((Class) type) diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/RepositoryCatalogFacade.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/RepositoryCatalogFacade.java index 8417e38b4..c04f7ec3a 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/RepositoryCatalogFacade.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/RepositoryCatalogFacade.java @@ -7,5 +7,4 @@ import org.geoserver.catalog.CatalogFacade; /** {@link CatalogFacade} extension backed by {@link CatalogInfoRepository} repositories */ -public interface RepositoryCatalogFacade - extends ExtendedCatalogFacade, CatalogInfoRepositoryHolder {} +public interface RepositoryCatalogFacade extends ExtendedCatalogFacade, CatalogInfoRepositoryHolder {} diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/RepositoryCatalogFacadeImpl.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/RepositoryCatalogFacadeImpl.java index 50e826e86..83bb8285c 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/RepositoryCatalogFacadeImpl.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/RepositoryCatalogFacadeImpl.java @@ -6,7 +6,17 @@ import com.google.common.collect.Iterators; import com.google.common.collect.Streams; - +import java.lang.reflect.Proxy; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Consumer; +import java.util.function.Supplier; +import java.util.stream.Stream; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogCapabilities; import org.geoserver.catalog.CatalogException; @@ -43,20 +53,7 @@ import org.geotools.filter.visitor.SimplifyingFilterVisitor; import org.springframework.util.Assert; -import java.lang.reflect.Proxy; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.function.Consumer; -import java.util.function.Supplier; -import java.util.stream.Stream; - -public class RepositoryCatalogFacadeImpl - implements RepositoryCatalogFacade, CatalogInfoRepositoryHolder { +public class RepositoryCatalogFacadeImpl implements RepositoryCatalogFacade, CatalogInfoRepositoryHolder { protected final CatalogInfoRepositoryHolderImpl repositories; @@ -93,8 +90,7 @@ public void resolve() { // no-op, override as appropriate } - protected I add( - I info, Class type, CatalogInfoRepository repository) { + protected I add(I info, Class type, CatalogInfoRepository repository) { checkNotAProxy(info); Objects.requireNonNull(info.getId(), "Object id not provided"); repository.add(info); @@ -120,8 +116,7 @@ public T getStore(String id, Class clazz) { } @Override - public T getStoreByName( - WorkspaceInfo workspace, String name, Class clazz) { + public T getStoreByName(WorkspaceInfo workspace, String name, Class clazz) { Optional result; if (workspace == ANY_WORKSPACE || workspace == null) { @@ -133,8 +128,7 @@ public T getStoreByName( } @Override - public List getStoresByWorkspace( - WorkspaceInfo workspace, Class clazz) { + public List getStoresByWorkspace(WorkspaceInfo workspace, Class clazz) { // Question: do we need to support ANY_WORKSPACE? see "todo" comment in DefaultCatalogFacade final WorkspaceInfo ws; if (workspace == null) { @@ -160,9 +154,7 @@ public DataStoreInfo getDefaultDataStore(WorkspaceInfo workspace) { public void setDefaultDataStore(WorkspaceInfo workspace, DataStoreInfo store) { if (store != null) { Objects.requireNonNull(store.getWorkspace()); - Assert.isTrue( - workspace.getId().equals(store.getWorkspace().getId()), - "Store workspace mismatch"); + Assert.isTrue(workspace.getId().equals(store.getWorkspace().getId()), "Store workspace mismatch"); } if (store == null) getStoreRepository().unsetDefaultDataStore(workspace); @@ -188,8 +180,7 @@ public T getResource(String id, Class clazz) { } @Override - public T getResourceByName( - NamespaceInfo namespace, String name, Class clazz) { + public T getResourceByName(NamespaceInfo namespace, String name, Class clazz) { if (namespace == null) return null; Optional result; if (namespace == ANY_NAMESPACE) { @@ -207,16 +198,14 @@ public List getResources(Class clazz) { } @Override - public List getResourcesByNamespace( - NamespaceInfo namespace, Class clazz) { + public List getResourcesByNamespace(NamespaceInfo namespace, Class clazz) { // Question: do we need to support ANY_WORKSPACE? see "todo" comment in DefaultCatalogFacade NamespaceInfo ns = namespace == null ? getDefaultNamespace() : namespace; return toList(() -> getResourceRepository().findAllByNamespace(ns, clazz)); } @Override - public T getResourceByStore( - StoreInfo store, String name, Class clazz) { + public T getResourceByStore(StoreInfo store, String name, Class clazz) { Optional resource; NamespaceInfo ns = null; if (store.getWorkspace() != null @@ -403,7 +392,9 @@ public NamespaceInfo getNamespace(String id) { @Override public NamespaceInfo getNamespaceByPrefix(String prefix) { - return getNamespaceRepository().findFirstByName(prefix, NamespaceInfo.class).orElse(null); + return getNamespaceRepository() + .findFirstByName(prefix, NamespaceInfo.class) + .orElse(null); } @Override @@ -463,7 +454,9 @@ public WorkspaceInfo getWorkspace(String id) { @Override public WorkspaceInfo getWorkspaceByName(String name) { - return getWorkspaceRepository().findFirstByName(name, WorkspaceInfo.class).orElse(null); + return getWorkspaceRepository() + .findFirstByName(name, WorkspaceInfo.class) + .orElse(null); } // @@ -573,8 +566,7 @@ public void syncTo(CatalogFacade to) { dao.setDefaultWorkspace(getDefaultWorkspace()); dao.setDefaultNamespace(getDefaultNamespace()); - try (Stream defaultDataStores = - getStoreRepository().getDefaultDataStores()) { + try (Stream defaultDataStores = getStoreRepository().getDefaultDataStores()) { defaultDataStores.forEach(d -> dao.setDefaultDataStore(d.getWorkspace(), d)); } } @@ -601,9 +593,7 @@ public int count(final Class of, Filter filter) { count = repository(of).count(of, filter); } catch (RuntimeException e) { throw new CatalogException( - "Error obtaining count of %s with filter %s" - .formatted(of.getSimpleName(), filter), - e); + "Error obtaining count of %s with filter %s".formatted(of.getSimpleName(), filter), e); } } return count > Integer.MAX_VALUE ? Integer.MAX_VALUE : (int) count; @@ -655,8 +645,7 @@ private IsInstanceOf extractInstanceOf(BinaryComparisonOperator f) { @Override public boolean canSort(final Class type, final String propertyName) { if (PublishedInfo.class.equals(type)) { - return canSort(LayerInfo.class, propertyName) - || canSort(LayerGroupInfo.class, propertyName); + return canSort(LayerInfo.class, propertyName) || canSort(LayerGroupInfo.class, propertyName); } return repository(type).canSortBy(propertyName); } @@ -668,8 +657,7 @@ private void checkCanSort(final Query query) { private void checkCanSort(final Class type, SortBy order) { if (!canSort(type, order.getPropertyName().getPropertyName())) { throw new IllegalArgumentException( - "Can't sort objects of type %s by %s" - .formatted(type.getName(), order.getPropertyName())); + "Can't sort objects of type %s by %s".formatted(type.getName(), order.getPropertyName())); } } @@ -727,7 +715,8 @@ protected Stream queryPublishedInfo(Query query) { // merge-sort the two streams without additional memory allocation, they're guaranteed // to be sorted - Iterator layersit = layers.map(PublishedInfo.class::cast).iterator(); + Iterator layersit = + layers.map(PublishedInfo.class::cast).iterator(); Iterator lgit = groups.map(PublishedInfo.class::cast).iterator(); Comparator comparator = CatalogInfoLookup.toComparator(query); @@ -746,10 +735,7 @@ protected Stream queryPublishedInfo(Query query) { } protected boolean shallApplyOffsetLimit( - final Integer offset, - final Integer limit, - Query layerQuery, - Query lgQuery) { + final Integer offset, final Integer limit, Query layerQuery, Query lgQuery) { if (null == offset && null == limit) { return false; } @@ -774,10 +760,9 @@ protected boolean shallApplyOffsetLimit( } private Stream closing(Stream stream, Stream... closeables) { - return stream.onClose( - () -> { - for (var s : closeables) s.close(); - }); + return stream.onClose(() -> { + for (var s : closeables) s.close(); + }); } @Override @@ -789,8 +774,7 @@ public I update(I info, Patch patch) { private static void checkNotAProxy(CatalogInfo value) { if (Proxy.isProxyClass(value.getClass())) { - throw new IllegalArgumentException( - "Proxy values shall not be passed to CatalogInfoLookup"); + throw new IllegalArgumentException("Proxy values shall not be passed to CatalogInfoLookup"); } } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingCatalog.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingCatalog.java index b1732b254..8cf4dec04 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingCatalog.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingCatalog.java @@ -4,6 +4,11 @@ */ package org.geoserver.catalog.plugin.forwarding; +import java.io.Serializable; +import java.util.Collection; +import java.util.Date; +import java.util.List; +import java.util.Objects; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogCapabilities; import org.geoserver.catalog.CatalogFacade; @@ -33,12 +38,6 @@ import org.geotools.api.filter.Filter; import org.geotools.api.filter.sort.SortBy; -import java.io.Serializable; -import java.util.Collection; -import java.util.Date; -import java.util.List; -import java.util.Objects; - /** * {@link Catalog} which forwards all its method calls to another {@code Catalog} aiding in * implementing a decorator. @@ -139,14 +138,12 @@ public T getStoreByName(String name, Class clazz) { } @Override - public T getStoreByName( - String workspaceName, String name, Class clazz) { + public T getStoreByName(String workspaceName, String name, Class clazz) { return catalog.getStoreByName(workspaceName, name, clazz); } @Override - public T getStoreByName( - WorkspaceInfo workspace, String name, Class clazz) { + public T getStoreByName(WorkspaceInfo workspace, String name, Class clazz) { return catalog.getStoreByName(workspace, name, clazz); } @@ -176,14 +173,12 @@ public WMTSStoreInfo getWMTSStoreByName(String name) { } @Override - public List getStoresByWorkspace( - WorkspaceInfo workspace, Class clazz) { + public List getStoresByWorkspace(WorkspaceInfo workspace, Class clazz) { return catalog.getStoresByWorkspace(workspace, clazz); } @Override - public List getStoresByWorkspace( - String workspaceName, Class clazz) { + public List getStoresByWorkspace(String workspaceName, Class clazz) { return catalog.getStoresByWorkspace(workspaceName, clazz); } @@ -278,8 +273,7 @@ public T getResourceByName(String ns, String name, Clas } @Override - public T getResourceByName( - NamespaceInfo ns, String name, Class clazz) { + public T getResourceByName(NamespaceInfo ns, String name, Class clazz) { return catalog.getResourceByName(ns, name, clazz); } @@ -329,20 +323,17 @@ public List getResources(Class clazz) { } @Override - public List getResourcesByNamespace( - NamespaceInfo namespace, Class clazz) { + public List getResourcesByNamespace(NamespaceInfo namespace, Class clazz) { return catalog.getResourcesByNamespace(namespace, clazz); } @Override - public List getResourcesByNamespace( - String namespace, Class clazz) { + public List getResourcesByNamespace(String namespace, Class clazz) { return catalog.getResourcesByNamespace(namespace, clazz); } @Override - public T getResourceByStore( - StoreInfo store, String name, Class clazz) { + public T getResourceByStore(StoreInfo store, String name, Class clazz) { return catalog.getResourceByStore(store, name, clazz); } @@ -783,19 +774,13 @@ public void fireAdded(CatalogInfo object) { @Override public void fireModified( - CatalogInfo object, - List propertyNames, - List oldValues, - List newValues) { + CatalogInfo object, List propertyNames, List oldValues, List newValues) { catalog.fireModified(object, propertyNames, oldValues, newValues); } @Override public void firePostModified( - CatalogInfo object, - List propertyNames, - List oldValues, - List newValues) { + CatalogInfo object, List propertyNames, List oldValues, List newValues) { catalog.firePostModified(object, propertyNames, oldValues, newValues); } @@ -835,8 +820,7 @@ public int count(Class of, Filter filter) { } @Override - public T get(Class type, Filter filter) - throws IllegalArgumentException { + public T get(Class type, Filter filter) throws IllegalArgumentException { return catalog.get(type, filter); } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingCatalogFacade.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingCatalogFacade.java index 7a30ae64f..8ddd0f0bb 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingCatalogFacade.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingCatalogFacade.java @@ -4,6 +4,8 @@ */ package org.geoserver.catalog.plugin.forwarding; +import java.util.List; +import javax.annotation.Nullable; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogCapabilities; import org.geoserver.catalog.CatalogFacade; @@ -21,10 +23,6 @@ import org.geotools.api.filter.Filter; import org.geotools.api.filter.sort.SortBy; -import java.util.List; - -import javax.annotation.Nullable; - /** * {@link CatalogFacade} which forwards all its method calls to another {@code CatalogFacade} aiding * in implementing a decorator. @@ -86,14 +84,12 @@ public T getStore(String id, Class clazz) { } @Override - public T getStoreByName( - WorkspaceInfo workspace, String name, Class clazz) { + public T getStoreByName(WorkspaceInfo workspace, String name, Class clazz) { return facade.getStoreByName(workspace, name, clazz); } @Override - public List getStoresByWorkspace( - WorkspaceInfo workspace, Class clazz) { + public List getStoresByWorkspace(WorkspaceInfo workspace, Class clazz) { return facade.getStoresByWorkspace(workspace, clazz); } @@ -138,8 +134,7 @@ public T getResource(String id, Class clazz) { } @Override - public T getResourceByName( - NamespaceInfo namespace, String name, Class clazz) { + public T getResourceByName(NamespaceInfo namespace, String name, Class clazz) { return facade.getResourceByName(namespace, name, clazz); } @@ -149,14 +144,12 @@ public List getResources(Class clazz) { } @Override - public List getResourcesByNamespace( - NamespaceInfo namespace, Class clazz) { + public List getResourcesByNamespace(NamespaceInfo namespace, Class clazz) { return facade.getResourcesByNamespace(namespace, clazz); } @Override - public T getResourceByStore( - StoreInfo store, String name, Class clazz) { + public T getResourceByStore(StoreInfo store, String name, Class clazz) { return facade.getResourceByStore(store, name, clazz); } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingCatalogRepository.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingCatalogRepository.java index 18daedd1c..e3ac7f1d1 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingCatalogRepository.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingCatalogRepository.java @@ -4,19 +4,16 @@ */ package org.geoserver.catalog.plugin.forwarding; +import java.util.Optional; +import java.util.stream.Stream; import lombok.NonNull; - import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.plugin.CatalogInfoRepository; import org.geoserver.catalog.plugin.Patch; import org.geoserver.catalog.plugin.Query; import org.geotools.api.filter.Filter; -import java.util.Optional; -import java.util.stream.Stream; - -public abstract class ForwardingCatalogRepository< - I extends CatalogInfo, S extends CatalogInfoRepository> +public abstract class ForwardingCatalogRepository> implements CatalogInfoRepository { protected S subject; diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingExtendedCatalogFacade.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingExtendedCatalogFacade.java index fdb3cb7b5..c2148d56f 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingExtendedCatalogFacade.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingExtendedCatalogFacade.java @@ -4,8 +4,8 @@ */ package org.geoserver.catalog.plugin.forwarding; +import java.util.stream.Stream; import lombok.NonNull; - import org.geoserver.catalog.CatalogFacade; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.LayerGroupInfo; @@ -20,11 +20,8 @@ import org.geoserver.catalog.plugin.Patch; import org.geoserver.catalog.plugin.Query; -import java.util.stream.Stream; - /** Adapts a regular {@link CatalogFacade} to a {@link ExtendedCatalogFacade} */ -public class ForwardingExtendedCatalogFacade extends ForwardingCatalogFacade - implements ExtendedCatalogFacade { +public class ForwardingExtendedCatalogFacade extends ForwardingCatalogFacade implements ExtendedCatalogFacade { public ForwardingExtendedCatalogFacade(ExtendedCatalogFacade facade) { super(facade); diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingLayerGroupRepository.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingLayerGroupRepository.java index 89b87f35d..ad42022f0 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingLayerGroupRepository.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingLayerGroupRepository.java @@ -4,17 +4,14 @@ */ package org.geoserver.catalog.plugin.forwarding; +import java.util.Optional; +import java.util.stream.Stream; import lombok.NonNull; - import org.geoserver.catalog.LayerGroupInfo; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.plugin.CatalogInfoRepository.LayerGroupRepository; -import java.util.Optional; -import java.util.stream.Stream; - -public class ForwardingLayerGroupRepository - extends ForwardingCatalogRepository +public class ForwardingLayerGroupRepository extends ForwardingCatalogRepository implements LayerGroupRepository { public ForwardingLayerGroupRepository(LayerGroupRepository subject) { diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingLayerRepository.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingLayerRepository.java index b243cd52e..c8300d761 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingLayerRepository.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingLayerRepository.java @@ -4,16 +4,15 @@ */ package org.geoserver.catalog.plugin.forwarding; +import java.util.Optional; +import java.util.stream.Stream; import org.geoserver.catalog.LayerInfo; import org.geoserver.catalog.ResourceInfo; import org.geoserver.catalog.StyleInfo; import org.geoserver.catalog.plugin.CatalogInfoRepository.LayerRepository; -import java.util.Optional; -import java.util.stream.Stream; - -public class ForwardingLayerRepository - extends ForwardingCatalogRepository implements LayerRepository { +public class ForwardingLayerRepository extends ForwardingCatalogRepository + implements LayerRepository { public ForwardingLayerRepository(LayerRepository subject) { super(subject); diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingNamespaceRepository.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingNamespaceRepository.java index b6f4a5287..dff0da254 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingNamespaceRepository.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingNamespaceRepository.java @@ -4,14 +4,12 @@ */ package org.geoserver.catalog.plugin.forwarding; -import org.geoserver.catalog.NamespaceInfo; -import org.geoserver.catalog.plugin.CatalogInfoRepository.NamespaceRepository; - import java.util.Optional; import java.util.stream.Stream; +import org.geoserver.catalog.NamespaceInfo; +import org.geoserver.catalog.plugin.CatalogInfoRepository.NamespaceRepository; -public class ForwardingNamespaceRepository - extends ForwardingCatalogRepository +public class ForwardingNamespaceRepository extends ForwardingCatalogRepository implements NamespaceRepository { public ForwardingNamespaceRepository(NamespaceRepository subject) { diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingResourceRepository.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingResourceRepository.java index 3f3970f52..42dd61544 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingResourceRepository.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingResourceRepository.java @@ -4,18 +4,15 @@ */ package org.geoserver.catalog.plugin.forwarding; +import java.util.Optional; +import java.util.stream.Stream; import lombok.NonNull; - import org.geoserver.catalog.NamespaceInfo; import org.geoserver.catalog.ResourceInfo; import org.geoserver.catalog.StoreInfo; import org.geoserver.catalog.plugin.CatalogInfoRepository.ResourceRepository; -import java.util.Optional; -import java.util.stream.Stream; - -public class ForwardingResourceRepository - extends ForwardingCatalogRepository +public class ForwardingResourceRepository extends ForwardingCatalogRepository implements ResourceRepository { public ForwardingResourceRepository(ResourceRepository subject) { @@ -33,8 +30,7 @@ public Stream findAllByNamespace(NamespaceInfo ns, C } @Override - public Optional findByStoreAndName( - StoreInfo store, String name, Class clazz) { + public Optional findByStoreAndName(StoreInfo store, String name, Class clazz) { return subject.findByStoreAndName(store, name, clazz); } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingStoreRepository.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingStoreRepository.java index ca2a6e822..ceeea6f2b 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingStoreRepository.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingStoreRepository.java @@ -4,18 +4,16 @@ */ package org.geoserver.catalog.plugin.forwarding; +import java.util.Optional; +import java.util.stream.Stream; import lombok.NonNull; - import org.geoserver.catalog.DataStoreInfo; import org.geoserver.catalog.StoreInfo; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.plugin.CatalogInfoRepository.StoreRepository; -import java.util.Optional; -import java.util.stream.Stream; - -public class ForwardingStoreRepository - extends ForwardingCatalogRepository implements StoreRepository { +public class ForwardingStoreRepository extends ForwardingCatalogRepository + implements StoreRepository { public ForwardingStoreRepository(StoreRepository subject) { super(subject); @@ -37,8 +35,7 @@ public Stream getDefaultDataStores() { } @Override - public Stream findAllByWorkspace( - WorkspaceInfo workspace, Class clazz) { + public Stream findAllByWorkspace(WorkspaceInfo workspace, Class clazz) { return subject.findAllByWorkspace(workspace, clazz); } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingStyleRepository.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingStyleRepository.java index 508cb76fc..ec02adfc0 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingStyleRepository.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingStyleRepository.java @@ -4,15 +4,14 @@ */ package org.geoserver.catalog.plugin.forwarding; +import java.util.Optional; +import java.util.stream.Stream; import org.geoserver.catalog.StyleInfo; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.plugin.CatalogInfoRepository.StyleRepository; -import java.util.Optional; -import java.util.stream.Stream; - -public class ForwardingStyleRepository - extends ForwardingCatalogRepository implements StyleRepository { +public class ForwardingStyleRepository extends ForwardingCatalogRepository + implements StyleRepository { public ForwardingStyleRepository(StyleRepository subject) { super(subject); diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingWorkspaceRepository.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingWorkspaceRepository.java index ef55b76f8..51ddd5730 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingWorkspaceRepository.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ForwardingWorkspaceRepository.java @@ -4,13 +4,11 @@ */ package org.geoserver.catalog.plugin.forwarding; +import java.util.Optional; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.plugin.CatalogInfoRepository.WorkspaceRepository; -import java.util.Optional; - -public class ForwardingWorkspaceRepository - extends ForwardingCatalogRepository +public class ForwardingWorkspaceRepository extends ForwardingCatalogRepository implements WorkspaceRepository { public ForwardingWorkspaceRepository(WorkspaceRepository subject) { diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ResolvingCatalogFacadeDecorator.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ResolvingCatalogFacadeDecorator.java index 27fa39fad..3e09658e4 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ResolvingCatalogFacadeDecorator.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/forwarding/ResolvingCatalogFacadeDecorator.java @@ -5,9 +5,14 @@ package org.geoserver.catalog.plugin.forwarding; import com.google.common.collect.Lists; - +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.UnaryOperator; +import java.util.stream.Stream; import lombok.NonNull; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogFacade; import org.geoserver.catalog.CatalogInfo; @@ -33,14 +38,6 @@ import org.geotools.api.filter.Filter; import org.geotools.api.filter.sort.SortBy; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.UnaryOperator; -import java.util.stream.Stream; - /** * {@link ExtendedCatalogFacade} decorator that applies a possibly side-effect producing * {@link Function} to each {@link CatalogInfo} right before returning it. @@ -84,8 +81,7 @@ * {@link Catalog}, may some of the functions in the chain require one; {@link #setOutboundResolver} * is agnostic of such concerns. */ -public class ResolvingCatalogFacadeDecorator extends ForwardingExtendedCatalogFacade - implements ResolvingCatalogFacade { +public class ResolvingCatalogFacadeDecorator extends ForwardingExtendedCatalogFacade implements ResolvingCatalogFacade { private ResolvingFacadeSupport resolver; @@ -182,14 +178,12 @@ public T getStore(String id, Class clazz) { } @Override - public T getStoreByName( - WorkspaceInfo workspace, String name, Class clazz) { + public T getStoreByName(WorkspaceInfo workspace, String name, Class clazz) { return resolveOutbound(super.getStoreByName(workspace, name, clazz)); } @Override - public List getStoresByWorkspace( - WorkspaceInfo workspace, Class clazz) { + public List getStoresByWorkspace(WorkspaceInfo workspace, Class clazz) { return resolveOutbound(super.getStoresByWorkspace(workspace, clazz)); } @@ -214,8 +208,7 @@ public T getResource(String id, Class clazz) { } @Override - public T getResourceByName( - NamespaceInfo namespace, String name, Class clazz) { + public T getResourceByName(NamespaceInfo namespace, String name, Class clazz) { return resolveOutbound(super.getResourceByName(namespace, name, clazz)); } @@ -225,14 +218,12 @@ public List getResources(Class clazz) { } @Override - public List getResourcesByNamespace( - NamespaceInfo namespace, Class clazz) { + public List getResourcesByNamespace(NamespaceInfo namespace, Class clazz) { return resolveOutbound(super.getResourcesByNamespace(namespace, clazz)); } @Override - public T getResourceByStore( - StoreInfo store, String name, Class clazz) { + public T getResourceByStore(StoreInfo store, String name, Class clazz) { return resolveOutbound(super.getResourceByStore(store, name, clazz)); } @@ -549,8 +540,7 @@ public void remove(MapInfo info) { public CloseableIterator list( Class of, Filter filter, Integer offset, Integer count, SortBy... sortOrder) { - final CloseableIterator orig = - asExtendedFacade().list(of, filter, offset, count, sortOrder); + final CloseableIterator orig = asExtendedFacade().list(of, filter, offset, count, sortOrder); return CloseableIteratorAdapter.transform(orig, this::resolveOutbound); } } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/ConfigInfoType.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/ConfigInfoType.java index 2020ecc0f..17be9b03d 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/ConfigInfoType.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/ConfigInfoType.java @@ -8,7 +8,6 @@ import lombok.Getter; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CoverageInfo; import org.geoserver.catalog.CoverageStoreInfo; diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/LockProviderGeoServerConfigurationLock.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/LockProviderGeoServerConfigurationLock.java index 731cb76bb..b5543dc09 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/LockProviderGeoServerConfigurationLock.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/LockProviderGeoServerConfigurationLock.java @@ -7,7 +7,6 @@ import static org.geoserver.GeoServerConfigurationLock.LockType.WRITE; import lombok.NonNull; - import org.geoserver.GeoServerConfigurationLock; import org.geoserver.platform.resource.LockProvider; import org.geoserver.platform.resource.Resource.Lock; @@ -59,8 +58,7 @@ public void forceUnlock() { } } - private static final ThreadLocal GLOBAL = - ThreadLocal.withInitial(ReentrantGlobalLock::new); + private static final ThreadLocal GLOBAL = ThreadLocal.withInitial(ReentrantGlobalLock::new); public LockProviderGeoServerConfigurationLock(@NonNull LockProvider lockProvider) { super(); diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/LockingCatalog.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/LockingCatalog.java index ffe3b3497..775ed42bd 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/LockingCatalog.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/LockingCatalog.java @@ -7,8 +7,8 @@ import static org.geoserver.catalog.plugin.locking.LockingSupport.nameOf; import static org.geoserver.catalog.plugin.locking.LockingSupport.typeOf; +import java.util.function.UnaryOperator; import lombok.NonNull; - import org.geoserver.GeoServerConfigurationLock; import org.geoserver.catalog.CatalogFacade; import org.geoserver.catalog.CatalogInfo; @@ -19,8 +19,6 @@ import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.plugin.CatalogPlugin; -import java.util.function.UnaryOperator; - /** * A locking catalog, akin to {@link LockingCatalogFacade}, but at a higher level of granularity, * because a single catalog operation (e.g. save()), can imply multiple config changes (e.g. sets @@ -52,17 +50,14 @@ public LockingCatalog(@NonNull GeoServerConfigurationLock configurationLock, boo enableLocking(); } - public LockingCatalog( - @NonNull GeoServerConfigurationLock configurationLock, CatalogFacade facade) { + public LockingCatalog(@NonNull GeoServerConfigurationLock configurationLock, CatalogFacade facade) { super(facade); this.configurationLock = configurationLock; enableLocking(); } public LockingCatalog( - @NonNull GeoServerConfigurationLock configurationLock, - CatalogFacade facade, - boolean isolated) { + @NonNull GeoServerConfigurationLock configurationLock, CatalogFacade facade, boolean isolated) { super(facade, isolated); this.configurationLock = configurationLock; enableLocking(); @@ -80,44 +75,37 @@ public void disableLocking() { public void setDefaultDataStore(@NonNull WorkspaceInfo workspace, DataStoreInfo store) { locking.runInWriteLock( () -> super.setDefaultDataStore(workspace, store), - "setDefaultDataStore(%s, %s)" - .formatted(workspace.getName(), store == null ? "null" : store.getName())); + "setDefaultDataStore(%s, %s)".formatted(workspace.getName(), store == null ? "null" : store.getName())); } @Override public void setDefaultNamespace(NamespaceInfo defaultNamespace) { locking.runInWriteLock( () -> super.setDefaultNamespace(defaultNamespace), - "setDefaultNamespace(%s)" - .formatted(defaultNamespace == null ? "null" : defaultNamespace.getName())); + "setDefaultNamespace(%s)".formatted(defaultNamespace == null ? "null" : defaultNamespace.getName())); } @Override public void setDefaultWorkspace(WorkspaceInfo defaultWorkspace) { locking.runInWriteLock( () -> super.setDefaultWorkspace(defaultWorkspace), - "setDefaultWorkspace(%s)" - .formatted(defaultWorkspace == null ? "null" : defaultWorkspace.getName())); + "setDefaultWorkspace(%s)".formatted(defaultWorkspace == null ? "null" : defaultWorkspace.getName())); } /** {@inheritDoc} */ protected @Override void doAdd(T info, UnaryOperator inserter) { - locking.runInWriteLock( - () -> super.doAdd(info, inserter), - "add(%s[%s])".formatted(typeOf(info), nameOf(info))); + locking.runInWriteLock(() -> super.doAdd(info, inserter), "add(%s[%s])".formatted(typeOf(info), nameOf(info))); } /** {@inheritDoc} */ protected @Override void doSave(final I info) { - locking.runInWriteLock( - () -> super.doSave(info), "save(%s[%s])".formatted(typeOf(info), nameOf(info))); + locking.runInWriteLock(() -> super.doSave(info), "save(%s[%s])".formatted(typeOf(info), nameOf(info))); } /** {@inheritDoc} */ protected @Override void doRemove(T info, Class type) { locking.runInWriteLock( - () -> super.doRemove(info, type), - "remove(%s[%s])".formatted(typeOf(info), nameOf(info))); + () -> super.doRemove(info, type), "remove(%s[%s])".formatted(typeOf(info), nameOf(info))); } /** @@ -125,7 +113,6 @@ public void setDefaultWorkspace(WorkspaceInfo defaultWorkspace) { */ @Override public void save(StoreInfo store) { - locking.runInWriteLock( - () -> super.save(store), "save(%s[%s])".formatted(typeOf(store), nameOf(store))); + locking.runInWriteLock(() -> super.save(store), "save(%s[%s])".formatted(typeOf(store), nameOf(store))); } } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/LockingGeoServer.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/LockingGeoServer.java index b48c93e00..59ade47c1 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/LockingGeoServer.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/LockingGeoServer.java @@ -8,7 +8,6 @@ import static org.geoserver.catalog.plugin.locking.LockingSupport.typeOf; import lombok.NonNull; - import org.geoserver.GeoServerConfigurationLock; import org.geoserver.config.GeoServerFacade; import org.geoserver.config.GeoServerInfo; @@ -31,8 +30,7 @@ public LockingGeoServer(@NonNull GeoServerConfigurationLock locking) { enableLocking(); } - public LockingGeoServer( - @NonNull GeoServerConfigurationLock locking, @NonNull GeoServerFacade facade) { + public LockingGeoServer(@NonNull GeoServerConfigurationLock locking, @NonNull GeoServerFacade facade) { super(facade); this.configurationLock = locking; enableLocking(); @@ -52,35 +50,30 @@ public void disableLocking() { @Override public void setGlobal(GeoServerInfo global) { - lockingSupport.runInWriteLock( - () -> super.setGlobal(global), "setGlobal(%s)".formatted(nameOf(global))); + lockingSupport.runInWriteLock(() -> super.setGlobal(global), "setGlobal(%s)".formatted(nameOf(global))); } @Override public void save(GeoServerInfo geoServer) { - lockingSupport.runInWriteLock( - () -> super.save(geoServer), "save(%s)".formatted(nameOf(geoServer))); + lockingSupport.runInWriteLock(() -> super.save(geoServer), "save(%s)".formatted(nameOf(geoServer))); } @Override public void add(SettingsInfo settings) { lockingSupport.runInWriteLock( - () -> super.add(settings), - "add(%s[%s])".formatted(typeOf(settings), nameOf(settings))); + () -> super.add(settings), "add(%s[%s])".formatted(typeOf(settings), nameOf(settings))); } @Override public void save(SettingsInfo settings) { lockingSupport.runInWriteLock( - () -> super.save(settings), - "save(%s[%s])".formatted(typeOf(settings), nameOf(settings))); + () -> super.save(settings), "save(%s[%s])".formatted(typeOf(settings), nameOf(settings))); } @Override public void remove(SettingsInfo settings) { lockingSupport.runInWriteLock( - () -> super.remove(settings), - "remove(%s[%s])".formatted(typeOf(settings), nameOf(settings))); + () -> super.remove(settings), "remove(%s[%s])".formatted(typeOf(settings), nameOf(settings))); } @Override @@ -96,21 +89,18 @@ public void save(LoggingInfo logging) { @Override public void add(ServiceInfo service) { lockingSupport.runInWriteLock( - () -> super.add(service), - "add(%s[%s])".formatted(typeOf(service), nameOf(service))); + () -> super.add(service), "add(%s[%s])".formatted(typeOf(service), nameOf(service))); } @Override public void remove(ServiceInfo service) { lockingSupport.runInWriteLock( - () -> super.remove(service), - "remove(%s[%s])".formatted(typeOf(service), nameOf(service))); + () -> super.remove(service), "remove(%s[%s])".formatted(typeOf(service), nameOf(service))); } @Override public void save(ServiceInfo service) { lockingSupport.runInWriteLock( - () -> super.save(service), - "save(%s[%s])".formatted(typeOf(service), nameOf(service))); + () -> super.save(service), "save(%s[%s])".formatted(typeOf(service), nameOf(service))); } } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/LockingSupport.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/LockingSupport.java index 6293f3498..682029b0a 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/LockingSupport.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/locking/LockingSupport.java @@ -4,10 +4,12 @@ */ package org.geoserver.catalog.plugin.locking; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.concurrent.Callable; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; - import org.geoserver.GeoServerConfigurationLock; import org.geoserver.GeoServerConfigurationLock.LockType; import org.geoserver.catalog.Info; @@ -17,10 +19,6 @@ import org.geoserver.config.SettingsInfo; import org.geoserver.ows.util.OwsUtils; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.util.concurrent.Callable; - /** */ @Slf4j(topic = "org.geoserver.cloud.catalog.locking") public abstract class LockingSupport { @@ -85,8 +83,8 @@ public void runInWriteLock(Runnable action, String reason) { } } - public V callInWriteLock( - Class exceptionType, Callable action, String reason) throws E { + public V callInWriteLock(Class exceptionType, Callable action, String reason) + throws E { lock(reason); try { return action.call(); @@ -107,8 +105,8 @@ public void runInWriteLock(Runnable action, String reason) { } @Override - public V callInWriteLock( - Class exceptionType, Callable action, String reason) throws E { + public V callInWriteLock(Class exceptionType, Callable action, String reason) + throws E { try { return action.call(); diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/CatalogPropertyResolver.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/CatalogPropertyResolver.java index cc45faca6..dbfe3d14a 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/CatalogPropertyResolver.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/CatalogPropertyResolver.java @@ -4,8 +4,11 @@ */ package org.geoserver.catalog.plugin.resolving; +import java.util.Collection; +import java.util.Objects; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; import lombok.NonNull; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.Info; @@ -22,11 +25,6 @@ import org.geoserver.catalog.impl.StyleInfoImpl; import org.geoserver.catalog.plugin.forwarding.ResolvingCatalogFacadeDecorator; -import java.util.Collection; -import java.util.Objects; -import java.util.function.Supplier; -import java.util.function.UnaryOperator; - /** * {@link ResolvingCatalogFacadeDecorator#setObjectResolver resolving function} to set the {@link * Catalog} property on {@link CatalogInfo} objects that require it before returning them from the diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/CollectionPropertiesInitializer.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/CollectionPropertiesInitializer.java index e9403694b..466120ac3 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/CollectionPropertiesInitializer.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/CollectionPropertiesInitializer.java @@ -4,12 +4,11 @@ */ package org.geoserver.catalog.plugin.resolving; +import java.util.function.UnaryOperator; import org.geoserver.catalog.impl.ModificationProxy; import org.geoserver.catalog.plugin.forwarding.ResolvingCatalogFacadeDecorator; import org.geoserver.ows.util.OwsUtils; -import java.util.function.UnaryOperator; - /** * {@link ResolvingCatalogFacadeDecorator#setObjectResolver resolving function} that returns the * incoming object decorated with a {@link ModificationProxy} @@ -18,8 +17,7 @@ */ public class CollectionPropertiesInitializer implements UnaryOperator { - private static final CollectionPropertiesInitializer INSTANCE = - new CollectionPropertiesInitializer<>(); + private static final CollectionPropertiesInitializer INSTANCE = new CollectionPropertiesInitializer<>(); @Override public T apply(T value) { diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ModificationProxyDecorator.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ModificationProxyDecorator.java index 27691d163..3d799b01e 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ModificationProxyDecorator.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ModificationProxyDecorator.java @@ -4,16 +4,14 @@ */ package org.geoserver.catalog.plugin.resolving; +import java.util.function.UnaryOperator; import lombok.experimental.UtilityClass; - import org.geoserver.catalog.Info; import org.geoserver.catalog.impl.ClassMappings; import org.geoserver.catalog.impl.ModificationProxy; import org.geoserver.catalog.impl.ProxyUtils; import org.geoserver.catalog.plugin.forwarding.ResolvingCatalogFacadeDecorator; -import java.util.function.UnaryOperator; - /** * {@link ResolvingCatalogFacadeDecorator#setObjectResolver resolving function} that returns the * incoming object decorated with a {@link ModificationProxy} diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ProxyUtils.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ProxyUtils.java index f598e5f94..d36f18cf7 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ProxyUtils.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ProxyUtils.java @@ -4,10 +4,18 @@ */ package org.geoserver.catalog.plugin.resolving; +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.function.Supplier; +import java.util.stream.Collectors; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.AttributeTypeInfo; import org.geoserver.catalog.AttributionInfo; import org.geoserver.catalog.Catalog; @@ -37,16 +45,6 @@ import org.geoserver.config.ServiceInfo; import org.geoserver.config.SettingsInfo; -import java.lang.reflect.Proxy; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.function.Supplier; -import java.util.stream.Collectors; - /** */ @Slf4j(topic = "org.geoserver.catalog.plugin.resolving") @RequiredArgsConstructor @@ -61,17 +59,16 @@ public class ProxyUtils { * @see #encodeByReference * @see #referenceTypeOf */ - private static final Set> VALUE_BY_REFERENCE_TYPES = - Set.of( - WorkspaceInfo.class, // - NamespaceInfo.class, // - StoreInfo.class, // - ResourceInfo.class, // - PublishedInfo.class, // - MapInfo.class, // - StyleInfo.class, // - GeoServerInfo.class, // - ServiceInfo.class); + private static final Set> VALUE_BY_REFERENCE_TYPES = Set.of( + WorkspaceInfo.class, // + NamespaceInfo.class, // + StoreInfo.class, // + ResourceInfo.class, // + PublishedInfo.class, // + MapInfo.class, // + StyleInfo.class, // + GeoServerInfo.class, // + ServiceInfo.class); private final @NonNull Supplier catalog; private final @NonNull Optional config; @@ -157,8 +154,7 @@ public T resolve(final T unresolved) { } if (info == null) { - if (failOnNotFound) - throw new IllegalArgumentException("Reference to %s".formatted(unresolved.getId())); + if (failOnNotFound) throw new IllegalArgumentException("Reference to %s".formatted(unresolved.getId())); return null; } @@ -205,13 +201,9 @@ private T resolveCatalogInfo(T info) { // to a concrete LayerInfo or LayerGroupInfo) it does nothing. if (info instanceof PublishedInfo) { PublishedInfo l = - ResolvingProxy.resolve( - actualCatalog, ResolvingProxy.create(info.getId(), LayerInfo.class)); + ResolvingProxy.resolve(actualCatalog, ResolvingProxy.create(info.getId(), LayerInfo.class)); if (null == l) { - l = - ResolvingProxy.resolve( - actualCatalog, - ResolvingProxy.create(info.getId(), LayerGroupInfo.class)); + l = ResolvingProxy.resolve(actualCatalog, ResolvingProxy.create(info.getId(), LayerGroupInfo.class)); } return (T) l; } @@ -330,13 +322,9 @@ protected ResourceInfo resolveInternal(ResourceInfo resource) { } public static Optional> referenceTypeOf(Object val) { - return Optional.ofNullable(val) - .filter(Info.class::isInstance) - .flatMap( - i -> - VALUE_BY_REFERENCE_TYPES.stream() - .filter(type -> type.isInstance(i)) - .findFirst()); + return Optional.ofNullable(val).filter(Info.class::isInstance).flatMap(i -> VALUE_BY_REFERENCE_TYPES.stream() + .filter(type -> type.isInstance(i)) + .findFirst()); } public static boolean encodeByReference(Object o) { diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingCatalogFacade.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingCatalogFacade.java index 98848a374..3e16e42c6 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingCatalogFacade.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingCatalogFacade.java @@ -4,6 +4,7 @@ */ package org.geoserver.catalog.plugin.resolving; +import java.util.function.Function; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogFacade; import org.geoserver.catalog.CatalogInfo; @@ -13,8 +14,6 @@ import org.geoserver.catalog.impl.ResolvingProxy; import org.geoserver.catalog.plugin.ExtendedCatalogFacade; -import java.util.function.Function; - /** * {@link ExtendedCatalogFacade} extension that applies a possibly side-effect producing * {@link Function} to each {@link CatalogInfo} right before returning it. @@ -58,5 +57,4 @@ * {@link Catalog}, may some of the functions in the chain require one; {@link #setOutboundResolver} * is agnostic of such concerns. */ -public interface ResolvingCatalogFacade - extends ExtendedCatalogFacade, ResolvingFacade {} +public interface ResolvingCatalogFacade extends ExtendedCatalogFacade, ResolvingFacade {} diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingCatalogInfoRepository.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingCatalogInfoRepository.java index 9a756e182..e0e68c0cf 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingCatalogInfoRepository.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingCatalogInfoRepository.java @@ -4,11 +4,10 @@ */ package org.geoserver.catalog.plugin.resolving; +import java.util.function.UnaryOperator; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.plugin.CatalogInfoRepository; -import java.util.function.UnaryOperator; - /** * @since 1.4 */ diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingFacade.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingFacade.java index 2ab80764e..f1ccfda17 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingFacade.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingFacade.java @@ -4,6 +4,8 @@ */ package org.geoserver.catalog.plugin.resolving; +import java.util.function.Function; +import java.util.function.UnaryOperator; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.ResourceInfo; @@ -11,9 +13,6 @@ import org.geoserver.catalog.impl.ModificationProxy; import org.geoserver.catalog.impl.ResolvingProxy; -import java.util.function.Function; -import java.util.function.UnaryOperator; - /** * Facade trait that applies a possibly side-effect producing {@link Function} to each outgoing * object right before returning it, and an in-bound resolving function to each object reaching to diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingFacadeSupport.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingFacadeSupport.java index e9ae7caa5..ccdac8d5a 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingFacadeSupport.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingFacadeSupport.java @@ -5,7 +5,6 @@ package org.geoserver.catalog.plugin.resolving; import com.google.common.collect.Lists; - import java.util.List; import java.util.Objects; import java.util.function.UnaryOperator; diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingProxyResolver.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingProxyResolver.java index 105b22c38..76905776c 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingProxyResolver.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/resolving/ResolvingProxyResolver.java @@ -4,9 +4,19 @@ */ package org.geoserver.catalog.plugin.resolving; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Proxy; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.function.BiConsumer; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import java.util.stream.Collectors; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.Info; @@ -24,18 +34,6 @@ import org.geoserver.config.ServiceInfo; import org.geoserver.config.SettingsInfo; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Proxy; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.NoSuchElementException; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.function.BiConsumer; -import java.util.function.Supplier; -import java.util.function.UnaryOperator; -import java.util.stream.Collectors; - /** * {@link ResolvingCatalogFacadeDecorator#setObjectResolver resolving function} that resolves {@link * CatalogInfo} properties that are proxied through {@link ResolvingProxy} before returning the @@ -60,15 +58,12 @@ public class ResolvingProxyResolver implements UnaryOperator { private ResolvingProxyResolver(@NonNull Supplier catalog) { this( catalog, - (info, proxy) -> - log.warn( - "ResolvingProxy object not found in catalog, keeping proxy around: %s" - .formatted(info.getId()))); + (info, proxy) -> log.warn("ResolvingProxy object not found in catalog, keeping proxy around: %s" + .formatted(info.getId()))); } private ResolvingProxyResolver( - @NonNull Supplier catalog, - @NonNull BiConsumer onNotFound) { + @NonNull Supplier catalog, @NonNull BiConsumer onNotFound) { this.catalog = catalog; this.onNotFound = onNotFound; this.proxyUtils = new ProxyUtils(catalog, Optional.empty()); @@ -84,15 +79,11 @@ public static ResolvingProxyResolver of( return new ResolvingProxyResolver<>(catalog, onNotFound); } - public static ResolvingProxyResolver of( - Catalog catalog, boolean errorOnNotFound) { + public static ResolvingProxyResolver of(Catalog catalog, boolean errorOnNotFound) { if (errorOnNotFound) - return ResolvingProxyResolver.of( - catalog, - (proxiedInfo, proxy) -> { - throw new NoSuchElementException( - "Object not found: %s".formatted(proxiedInfo.getId())); - }); + return ResolvingProxyResolver.of(catalog, (proxiedInfo, proxy) -> { + throw new NoSuchElementException("Object not found: %s".formatted(proxiedInfo.getId())); + }); return ResolvingProxyResolver.of(catalog); } @@ -109,8 +100,7 @@ public ResolvingProxyResolver memoizing() { return (ResolvingProxyResolver) new MemoizingProxyResolver(catalog, onNotFound); } - public ResolvingProxyResolver onNotFound( - BiConsumer onNotFound) { + public ResolvingProxyResolver onNotFound(BiConsumer onNotFound) { this.onNotFound = onNotFound; return this; } @@ -133,9 +123,7 @@ public I resolve(final I orig) { // may the object itself be a resolving proxy Info resolved = doResolveProxy(info); if (resolved == null && info instanceof CatalogInfo cinfo) { - log.debug( - "Proxy object {} not found, calling on-not-found consumer", - info.getId()); + log.debug("Proxy object {} not found, calling on-not-found consumer", info.getId()); onNotFound.accept(cinfo, resolvingProxy); // if onNotFound didn't throw an exception, return the proxied value if the // consumer didn't throw an exception @@ -199,18 +187,14 @@ protected

    P resolveInternal(P published) { protected LayerInfo resolveInternal(LayerInfo layer) { if (isResolvingProxy(layer.getResource())) layer.setResource(resolve(layer.getResource())); - if (isResolvingProxy(layer.getDefaultStyle())) - layer.setDefaultStyle(resolve(layer.getDefaultStyle())); + if (isResolvingProxy(layer.getDefaultStyle())) layer.setDefaultStyle(resolve(layer.getDefaultStyle())); - final boolean hasProxiedStyles = - layer.getStyles().stream().anyMatch(this::isResolvingProxy); + final boolean hasProxiedStyles = layer.getStyles().stream().anyMatch(this::isResolvingProxy); if (hasProxiedStyles) { LinkedHashSet resolvedStyles; resolvedStyles = - layer.getStyles().stream() - .map(this::resolve) - .collect(Collectors.toCollection(LinkedHashSet::new)); + layer.getStyles().stream().map(this::resolve).collect(Collectors.toCollection(LinkedHashSet::new)); layer.getStyles().clear(); layer.getStyles().addAll(resolvedStyles); @@ -286,8 +270,7 @@ private static class MemoizingProxyResolver extends ResolvingProxyResolver private Map resolvedById = new ConcurrentHashMap<>(); public MemoizingProxyResolver( - @NonNull Supplier catalog, - BiConsumer onNotFound) { + @NonNull Supplier catalog, BiConsumer onNotFound) { super(catalog, onNotFound); } @@ -306,8 +289,7 @@ public MemoizingProxyResolver( @SuppressWarnings("unchecked") private I computeIfAbsent(final I orig) { - return (I) - resolvedById.computeIfAbsent(orig.getId(), key -> super.doResolveProxy(orig)); + return (I) resolvedById.computeIfAbsent(orig.getId(), key -> super.doResolveProxy(orig)); } } } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/CatalogBusinessRules.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/CatalogBusinessRules.java index c46b92f9c..292117ff2 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/CatalogBusinessRules.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/CatalogBusinessRules.java @@ -4,20 +4,18 @@ */ package org.geoserver.catalog.plugin.rules; +import java.util.EnumMap; +import java.util.Objects; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.Info; import org.geoserver.catalog.MapInfo; import org.geoserver.catalog.impl.ClassMappings; import org.geoserver.catalog.impl.ModificationProxy; -import java.util.EnumMap; -import java.util.Objects; - /** */ public class CatalogBusinessRules { - private EnumMap> rulesByType = - new EnumMap<>(ClassMappings.class); + private EnumMap> rulesByType = new EnumMap<>(ClassMappings.class); public CatalogBusinessRules() { register(ClassMappings.WORKSPACE, new DefaultWorkspaceInfoRules()); @@ -47,18 +45,13 @@ public CatalogInfoBusinessRules rulesFor(T info) { } public CatalogInfoBusinessRules rulesOf(Class type) { - ClassMappings cm = - type.isInterface() - ? ClassMappings.fromInterface(type) - : ClassMappings.fromImpl(type); + ClassMappings cm = type.isInterface() ? ClassMappings.fromInterface(type) : ClassMappings.fromImpl(type); - Objects.requireNonNull( - cm, () -> "Unable to determine type enum for class " + type.getCanonicalName()); + Objects.requireNonNull(cm, () -> "Unable to determine type enum for class " + type.getCanonicalName()); @SuppressWarnings("unchecked") CatalogInfoBusinessRules rules = (CatalogInfoBusinessRules) rulesByType.get(cm); - Objects.requireNonNull( - rules, () -> "Rules for type %s not found".formatted(type.getCanonicalName())); + Objects.requireNonNull(rules, () -> "Rules for type %s not found".formatted(type.getCanonicalName())); return rules; } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/CatalogOpContext.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/CatalogOpContext.java index 9ab7f858d..e9dd24681 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/CatalogOpContext.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/CatalogOpContext.java @@ -6,15 +6,14 @@ import static java.util.Objects.requireNonNull; +import java.util.HashMap; +import java.util.Map; +import java.util.function.BooleanSupplier; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.plugin.CatalogInfoTypeRegistry; import org.geoserver.catalog.plugin.PropertyDiff; -import java.util.HashMap; -import java.util.Map; -import java.util.function.BooleanSupplier; - /** * Encapsulates the context on which a catalog add/save/remove operation is being executed, * providing the necessary information for {@link CatalogInfoBusinessRules} implementations to act @@ -132,11 +131,10 @@ public boolean is(String key) { @SuppressWarnings("unchecked") public CatalogOpContext as(Class subtype) { if (subtype.isInstance(object)) return (CatalogOpContext) this; - throw new IllegalArgumentException( - "%s<%s> can't be type narrowed to <%s>" - .formatted( - getClass().getSimpleName(), - CatalogInfoTypeRegistry.determineKey(object.getClass()), - subtype.getSimpleName())); + throw new IllegalArgumentException("%s<%s> can't be type narrowed to <%s>" + .formatted( + getClass().getSimpleName(), + CatalogInfoTypeRegistry.determineKey(object.getClass()), + subtype.getSimpleName())); } } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/DefaultNamespaceInfoRules.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/DefaultNamespaceInfoRules.java index f1fb7c4c9..b6773b888 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/DefaultNamespaceInfoRules.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/DefaultNamespaceInfoRules.java @@ -4,12 +4,11 @@ */ package org.geoserver.catalog.plugin.rules; +import java.util.List; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.NamespaceInfo; import org.geoserver.catalog.WorkspaceInfo; -import java.util.List; - /** Encapsulates default {@link Catalog} business rules for {@link NamespaceInfo} objects */ public class DefaultNamespaceInfoRules implements CatalogInfoBusinessRules { @@ -38,8 +37,7 @@ public void afterAdd(CatalogOpContext context) { setAsDefaultIfThereWasNoDefaultNamespace(context); } - protected void setAsDefaultIfThereWasNoDefaultNamespace( - CatalogOpContext context) { + protected void setAsDefaultIfThereWasNoDefaultNamespace(CatalogOpContext context) { if (context.isSuccess()) { Boolean needsSetDefault = context.getContextOption(SET_DEFAULT); if (needsSetDefault.booleanValue()) { @@ -66,8 +64,7 @@ protected void selectNewDefaultNamespaceIfRemoved(Catalog catalog, NamespaceInfo defaultNamespace = namespaces.isEmpty() ? null : namespaces.get(0); catalog.setDefaultNamespace(defaultNamespace); if (defaultNamespace != null) { - WorkspaceInfo defaultWorkspace = - catalog.getWorkspaceByName(defaultNamespace.getPrefix()); + WorkspaceInfo defaultWorkspace = catalog.getWorkspaceByName(defaultNamespace.getPrefix()); if (defaultWorkspace != null) { catalog.setDefaultWorkspace(defaultWorkspace); } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/DefaultStoreInfoRules.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/DefaultStoreInfoRules.java index 41061723d..dada7bc11 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/DefaultStoreInfoRules.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/DefaultStoreInfoRules.java @@ -4,13 +4,12 @@ */ package org.geoserver.catalog.plugin.rules; +import java.util.List; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.DataStoreInfo; import org.geoserver.catalog.StoreInfo; import org.geoserver.catalog.WorkspaceInfo; -import java.util.List; - /** Encapsulates default {@link Catalog} business rules for {@link StoreInfo} objects */ public class DefaultStoreInfoRules implements CatalogInfoBusinessRules { @@ -50,8 +49,7 @@ public void beforeRemove(CatalogOpContext context) { StoreInfo toRemove = context.getObject(); WorkspaceInfo workspace = toRemove.getWorkspace(); DataStoreInfo defaultDs = context.getCatalog().getDefaultDataStore(workspace); - boolean needsToSelectNew = - defaultDs == null || toRemove.getId().equals(defaultDs.getId()); + boolean needsToSelectNew = defaultDs == null || toRemove.getId().equals(defaultDs.getId()); if (needsToSelectNew) { context.setContextOption(SELECT_NEW_DEFAULT_FOR_WORKSPACE, workspace); } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/DefaultStyleInfoRules.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/DefaultStyleInfoRules.java index 04c07ca44..8e62980e2 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/DefaultStyleInfoRules.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/DefaultStyleInfoRules.java @@ -4,6 +4,10 @@ */ package org.geoserver.catalog.plugin.rules; +import java.io.IOException; +import java.util.Optional; +import java.util.logging.Level; +import java.util.logging.Logger; import org.apache.commons.io.FilenameUtils; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.SLDHandler; @@ -19,11 +23,6 @@ import org.geoserver.platform.resource.Resources; import org.geotools.util.logging.Logging; -import java.io.IOException; -import java.util.Optional; -import java.util.logging.Level; -import java.util.logging.Logger; - /** Encapsulates default {@link Catalog} business rules for {@link StyleInfo} objects */ public class DefaultStyleInfoRules implements CatalogInfoBusinessRules { private static final Logger LOGGER = Logging.getLogger(DefaultStyleInfoRules.class); @@ -37,17 +36,14 @@ public class DefaultStyleInfoRules implements CatalogInfoBusinessRules context) { PropertyDiff diff = context.getDiff(); Optional nameChange = diff.get("name"); - nameChange.ifPresent( - change -> { - try { - renameStyle( - context.getCatalog(), - context.getObject(), - (String) nameChange.get().getNewValue()); - } catch (IOException e) { - LOGGER.log(Level.SEVERE, "Failed to rename style file along with name.", e); - } - }); + nameChange.ifPresent(change -> { + try { + renameStyle(context.getCatalog(), context.getObject(), (String) + nameChange.get().getNewValue()); + } catch (IOException e) { + LOGGER.log(Level.SEVERE, "Failed to rename style file along with name.", e); + } + }); } /** Reverts the style file rename performed in {@link #beforeAdd} if the operation has failed */ @@ -58,17 +54,13 @@ public void afterSave(CatalogOpContext context) { } PropertyDiff diff = context.getDiff(); Optional nameChange = diff.get("name"); - nameChange.ifPresent( - change -> { - try { - revertRenameStyle( - context.getCatalog(), - context.getObject(), - (String) change.getOldValue()); - } catch (IOException e) { - LOGGER.log(Level.SEVERE, "Failed to revert style rename.", e); - } - }); + nameChange.ifPresent(change -> { + try { + revertRenameStyle(context.getCatalog(), context.getObject(), (String) change.getOldValue()); + } catch (IOException e) { + LOGGER.log(Level.SEVERE, "Failed to revert style rename.", e); + } + }); } private void renameStyle(Catalog catalog, StyleInfo s, String newName) throws IOException { @@ -86,8 +78,7 @@ private void renameStyle(Catalog catalog, StyleInfo s, String newName) throws IO String sldFileName = "%s.sld".formatted(FilenameUtils.getBaseName(style.name())); Resource sld = style.parent().get(sldFileName); if (sld.getType() == Type.RESOURCE) { - LOGGER.fine( - () -> "Renaming style resource %s to %s".formatted(s.getName(), newName)); + LOGGER.fine(() -> "Renaming style resource %s to %s".formatted(s.getName(), newName)); Resource generated = Resources.uniqueResource(sld, newName, "sld"); sld.renameTo(generated); @@ -95,8 +86,7 @@ private void renameStyle(Catalog catalog, StyleInfo s, String newName) throws IO } } - private void revertRenameStyle(Catalog catalog, StyleInfo style, String oldName) - throws IOException { + private void revertRenameStyle(Catalog catalog, StyleInfo style, String oldName) throws IOException { if (oldName != null) { renameStyle(catalog, style, oldName); } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/DefaultWorkspaceInfoRules.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/DefaultWorkspaceInfoRules.java index 3517d263f..5376c725d 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/DefaultWorkspaceInfoRules.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/rules/DefaultWorkspaceInfoRules.java @@ -4,12 +4,11 @@ */ package org.geoserver.catalog.plugin.rules; +import java.util.List; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.NamespaceInfo; import org.geoserver.catalog.WorkspaceInfo; -import java.util.List; - /** Encapsulates default {@link Catalog} business rules for {@link WorkspaceInfo} objects */ public class DefaultWorkspaceInfoRules implements CatalogInfoBusinessRules { @@ -66,8 +65,7 @@ protected void selectNewDefaultWorkspaceIfRemoved(Catalog catalog, WorkspaceInfo defaultWorkspace = workspaces.isEmpty() ? null : workspaces.get(0); catalog.setDefaultWorkspace(defaultWorkspace); if (defaultWorkspace != null) { - NamespaceInfo defaultNamespace = - catalog.getNamespaceByPrefix(defaultWorkspace.getName()); + NamespaceInfo defaultNamespace = catalog.getNamespaceByPrefix(defaultWorkspace.getName()); if (defaultNamespace != null) { catalog.setDefaultNamespace(defaultNamespace); } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/BeforeRemoveValidator.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/BeforeRemoveValidator.java index 006d40dbd..aa50a13a8 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/BeforeRemoveValidator.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/BeforeRemoveValidator.java @@ -5,19 +5,20 @@ package org.geoserver.catalog.plugin.validation; import static com.google.common.base.Preconditions.checkArgument; - import static org.geoserver.catalog.Predicates.acceptAll; import static org.geoserver.catalog.Predicates.equal; import static org.geoserver.catalog.Predicates.isNull; import static org.geoserver.catalog.Predicates.or; import com.google.common.collect.Streams; - +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; +import java.util.stream.Stream; import lombok.AccessLevel; import lombok.Cleanup; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.LayerGroupInfo; @@ -32,11 +33,6 @@ import org.geoserver.catalog.util.CloseableIterator; import org.geotools.api.filter.Filter; -import java.util.List; -import java.util.Objects; -import java.util.stream.Collectors; -import java.util.stream.Stream; - /** * Implements validation rules to apply before {@code Catalog.remove(...)} * @@ -50,10 +46,7 @@ final class BeforeRemoveValidator extends AbstractCatalogVisitor { private final @NonNull Catalog catalog; private void checkEmpty( - Class type, - String queryProperty, - String queryValue, - String errorMessage) { + Class type, String queryProperty, String queryValue, String errorMessage) { Filter filter = equal(queryProperty, queryValue); int count = catalog.count(type, filter); @@ -70,35 +63,22 @@ public void visit(WorkspaceInfo workspace) { throw new IllegalArgumentException("Cannot delete workspace with linked namespace"); } - checkEmpty( - StoreInfo.class, - "workspace.id", - workspace.getId(), - "Cannot delete non-empty workspace."); + checkEmpty(StoreInfo.class, "workspace.id", workspace.getId(), "Cannot delete non-empty workspace."); } @Override public void visit(NamespaceInfo namespace) { - checkEmpty( - ResourceInfo.class, - "namespace.id", - namespace.getId(), - "Unable to delete non-empty namespace."); + checkEmpty(ResourceInfo.class, "namespace.id", namespace.getId(), "Unable to delete non-empty namespace."); } @Override protected void visit(StoreInfo store) { - checkEmpty( - ResourceInfo.class, "store.id", store.getId(), "Unable to delete non-empty store."); + checkEmpty(ResourceInfo.class, "store.id", store.getId(), "Unable to delete non-empty store."); } @Override protected void visit(ResourceInfo resource) { - checkEmpty( - LayerInfo.class, - "resource.id", - resource.getId(), - "Unable to delete resource referenced by layer"); + checkEmpty(LayerInfo.class, "resource.id", resource.getId(), "Unable to delete resource referenced by layer"); } @Override @@ -140,11 +120,9 @@ private void checkNoLayerReferencesStyle(StyleInfo style) { List layers = catalog.getLayers(style); if (!layers.isEmpty()) { String styleName = style.prefixedName(); - String layerNames = - layers.stream().map(LayerInfo::prefixedName).collect(Collectors.joining(",")); + String layerNames = layers.stream().map(LayerInfo::prefixedName).collect(Collectors.joining(",")); throw new IllegalArgumentException( - "Unable to delete style %s referenced by layers %s" - .formatted(styleName, layerNames)); + "Unable to delete style %s referenced by layers %s".formatted(styleName, layerNames)); } } @@ -164,9 +142,8 @@ private void checkLayerGroupDoesNotContain(LayerGroupInfo lg, PublishedInfo toDe String publishedType = toDelete instanceof LayerInfo ? "layer" : "layer group"; String publishedName = toDelete.prefixedName(); String lgName = lg.prefixedName(); - throw new IllegalArgumentException( - "Unable to delete %s %s referenced by layer group '%s'" - .formatted(publishedType, publishedName, lgName)); + throw new IllegalArgumentException("Unable to delete %s %s referenced by layer group '%s'" + .formatted(publishedType, publishedName, lgName)); } } @@ -199,16 +176,14 @@ private void checkLayerGroupDoesNotContain(LayerGroupInfo lg, StyleInfo toDelete StyleInfo rootLayerStyle = lg.getRootLayerStyle(); boolean rootStyleMatches = null != rootLayerStyle && styleId.equals(rootLayerStyle.getId()); - boolean referenced = - rootStyleMatches - || lg.getStyles().stream() - .filter(Objects::nonNull) - .map(StyleInfo::getId) - .anyMatch(styleId::equals); + boolean referenced = rootStyleMatches + || lg.getStyles().stream() + .filter(Objects::nonNull) + .map(StyleInfo::getId) + .anyMatch(styleId::equals); if (referenced) - throw new IllegalArgumentException( - "Unable to delete style %s referenced by layer group '%s'" - .formatted(toDelete.prefixedName(), lg.prefixedName())); + throw new IllegalArgumentException("Unable to delete style %s referenced by layer group '%s'" + .formatted(toDelete.prefixedName(), lg.prefixedName())); } } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/CatalogValidationRules.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/CatalogValidationRules.java index fa6977dbd..7efc0b250 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/CatalogValidationRules.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/CatalogValidationRules.java @@ -4,6 +4,8 @@ */ package org.geoserver.catalog.plugin.validation; +import java.util.List; +import java.util.Objects; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.CatalogValidator; @@ -11,9 +13,6 @@ import org.geoserver.catalog.impl.ModificationProxy; import org.geoserver.platform.GeoServerExtensions; -import java.util.List; -import java.util.Objects; - /** * Support class implementing the {@link Catalog} state validation rules for {@link CatalogInfo} * objects before being created, updated, or removed; @@ -74,11 +73,10 @@ private ValidationResult postValidate(CatalogInfo info, boolean isNew) { return new ValidationResult(null); } - List errors = - getValidators().stream() - .map(validator -> validate(info, validator, isNew)) - .filter(Objects::nonNull) - .toList(); + List errors = getValidators().stream() + .map(validator -> validate(info, validator, isNew)) + .filter(Objects::nonNull) + .toList(); return new ValidationResult(errors); } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/CatalogValidatorVisitor.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/CatalogValidatorVisitor.java index 3fb9b8e6c..787a45aea 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/CatalogValidatorVisitor.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/CatalogValidatorVisitor.java @@ -7,7 +7,6 @@ import lombok.AccessLevel; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.catalog.CatalogValidator; import org.geoserver.catalog.CatalogVisitor; import org.geoserver.catalog.CatalogVisitorAdapter; diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/DefaultCatalogValidator.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/DefaultCatalogValidator.java index 3501c0d55..a8f64cf76 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/DefaultCatalogValidator.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/DefaultCatalogValidator.java @@ -4,6 +4,17 @@ */ package org.geoserver.catalog.plugin.validation; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Iterator; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.Stack; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Matcher; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogBuilder; import org.geoserver.catalog.CatalogInfo; @@ -25,18 +36,6 @@ import org.geotools.api.style.StyledLayerDescriptor; import org.geotools.util.logging.Logging; -import java.io.IOException; -import java.net.URI; -import java.net.URISyntaxException; -import java.util.Iterator; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.Stack; -import java.util.logging.Level; -import java.util.logging.Logger; -import java.util.regex.Matcher; - /** Default validation rules for {@link CatalogInfo} pre-add and pre-modify states */ public class DefaultCatalogValidator implements CatalogValidator { private static final Logger LOGGER = Logging.getLogger(DefaultCatalogValidator.class); @@ -62,8 +61,7 @@ public void validate(WorkspaceInfo workspace, boolean isNew) { newObjectPropertiesResolver.resolve(workspace); } checkArgument( - !workspace.isIsolated() - || catalog.getCatalogCapabilities().supportsIsolatedWorkspaces(), + !workspace.isIsolated() || catalog.getCatalogCapabilities().supportsIsolatedWorkspaces(), "Workspace '%s' is isolated but isolated workspaces are not supported by this catalog.", workspace.getName()); @@ -81,8 +79,7 @@ public void validate(NamespaceInfo namespace, boolean isNew) { if (isNew) { newObjectPropertiesResolver.resolve(namespace); } - if (namespace.isIsolated() - && !catalog.getCatalogCapabilities().supportsIsolatedWorkspaces()) { + if (namespace.isIsolated() && !catalog.getCatalogCapabilities().supportsIsolatedWorkspaces()) { // isolated namespaces \ workspaces are not supported by this catalog throw new IllegalArgumentException( "Namespace '%s:%s' is isolated but isolated workspaces are not supported by this catalog." @@ -131,9 +128,7 @@ public void validate(StoreInfo store, boolean isNew) { WorkspaceInfo workspace = store.getWorkspace(); StoreInfo existing = catalog.getStoreByName(workspace, store.getName(), StoreInfo.class); if (existing != null && (isNew || !existing.getId().equals(store.getId()))) { - String msg = - "Store '%s' already exists in workspace '%s'" - .formatted(store.getName(), workspace.getName()); + String msg = "Store '%s' already exists in workspace '%s'".formatted(store.getName(), workspace.getName()); throw new IllegalArgumentException(msg); } } @@ -145,16 +140,14 @@ public void validate(ResourceInfo resource, boolean isNew) { newObjectPropertiesResolver.resolve(resource); } if (isNullOrEmpty(resource.getNativeName()) - && !(resource instanceof CoverageInfo coverage - && coverage.getNativeCoverageName() != null)) { + && !(resource instanceof CoverageInfo coverage && coverage.getNativeCoverageName() != null)) { throw new NullPointerException("Resource native name must not be null"); } checkArgument(null != resource.getStore(), "Resource must be part of a store"); checkArgument(null != resource.getNamespace(), "Resource must be part of a namespace"); StoreInfo store = resource.getStore(); - ResourceInfo existing = - catalog.getResourceByStore(store, resource.getName(), ResourceInfo.class); + ResourceInfo existing = catalog.getResourceByStore(store, resource.getName(), ResourceInfo.class); checkArgument( existing == null || existing.getId().equals(resource.getId()), "Resource named '%s' already exists in store: '%s'", @@ -199,19 +192,16 @@ public void validate(LayerInfo layer, boolean isNew) { // if the style is missing associate a default one, to avoid breaking WMS if (layer.getDefaultStyle() == null) { try { - LOGGER.info( - () -> - "Layer %s is missing the default style, assigning one automatically" - .formatted(layer.prefixedName())); + LOGGER.info(() -> "Layer %s is missing the default style, assigning one automatically" + .formatted(layer.prefixedName())); StyleInfo style = new CatalogBuilder(catalog).getDefaultStyle(resource); layer.setDefaultStyle(style); } catch (IOException e) { LOGGER.log( Level.WARNING, e, - () -> - "Layer %s is missing the default style, failed to associate one automatically" - .formatted(layer.prefixedName())); + () -> "Layer %s is missing the default style, failed to associate one automatically" + .formatted(layer.prefixedName())); } } @@ -254,9 +244,7 @@ private void validateModeMatchesStructure(LayerGroupInfo layerGroup) { checkArgument(mode != null, "Layer group mode must not be null"); if (LayerGroupInfo.Mode.EO.equals(mode)) { checkArgument( - layerGroup.getRootLayer() != null, - "Layer group in mode %s must have a root layer", - mode.getName()); + layerGroup.getRootLayer() != null, "Layer group in mode %s must have a root layer", mode.getName()); checkArgument( layerGroup.getRootLayerStyle() != null, "Layer group in mode %s must have a root layer style", @@ -278,8 +266,7 @@ private void verifyNoLoopsInStructure(LayerGroupInfo layerGroup) { Stack loopPath = helper.checkLoops(); if (loopPath != null) { String loopAsString = helper.getLoopAsString(loopPath); - throw new IllegalArgumentException( - "Layer group is in a loop: %s".formatted(loopAsString)); + throw new IllegalArgumentException("Layer group is in a loop: %s".formatted(loopAsString)); } } @@ -287,8 +274,7 @@ private void checkLayerGroupStyles(LayerGroupInfo layerGroup) { if (layerGroup.getStyles() != null && !layerGroup.getStyles().isEmpty() && (layerGroup.getStyles().size() != layerGroup.getLayers().size())) { - throw new IllegalArgumentException( - "Layer group has different number of styles than layers"); + throw new IllegalArgumentException("Layer group has different number of styles than layers"); } } @@ -319,13 +305,11 @@ private void validateStyleGroup(StyleInfo style) { StyledLayerDescriptor sld = style.getSLD(); errors = SLDNamedLayerValidator.validate(catalog, sld); } catch (IOException e) { - throw new IllegalArgumentException( - "Error validating style group: %s".formatted(e.getMessage()), e); + throw new IllegalArgumentException("Error validating style group: %s".formatted(e.getMessage()), e); } if (!errors.isEmpty()) { Exception first = errors.get(0); - throw new IllegalArgumentException( - "Invalid style group: %s".formatted(first.getMessage()), first); + throw new IllegalArgumentException("Invalid style group: %s".formatted(first.getMessage()), first); } } @@ -333,9 +317,7 @@ private List checkSameSize(List layers, List keywords) { if (kw.getVocabulary() != null) { m = KeywordInfo.RE.matcher(kw.getVocabulary()); if (!m.matches()) { - throw new IllegalArgumentException( - "Keyword vocbulary must not contain the '\\' character"); + throw new IllegalArgumentException("Keyword vocbulary must not contain the '\\' character"); } } } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/DefaultPropertyValuesResolver.java b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/DefaultPropertyValuesResolver.java index 3a46a8677..6bd14e293 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/DefaultPropertyValuesResolver.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/catalog/plugin/validation/DefaultPropertyValuesResolver.java @@ -4,6 +4,8 @@ */ package org.geoserver.catalog.plugin.validation; +import java.util.ArrayList; +import java.util.List; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.CoverageDimensionInfo; @@ -30,9 +32,6 @@ import org.geoserver.catalog.impl.WMTSLayerInfoImpl; import org.geoserver.ows.util.OwsUtils; -import java.util.ArrayList; -import java.util.List; - /** */ public class DefaultPropertyValuesResolver { diff --git a/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/ConfigRepository.java b/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/ConfigRepository.java index 3c16a770e..8e9c1b963 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/ConfigRepository.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/ConfigRepository.java @@ -4,6 +4,8 @@ */ package org.geoserver.config.plugin; +import java.util.Optional; +import java.util.stream.Stream; import org.geoserver.catalog.Info; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.plugin.Patch; @@ -12,9 +14,6 @@ import org.geoserver.config.ServiceInfo; import org.geoserver.config.SettingsInfo; -import java.util.Optional; -import java.util.stream.Stream; - /** * Raw data access API for GeoServer global configuration and per-workspace settings and services * configuration. @@ -91,8 +90,7 @@ public interface ConfigRepository { * @param workspace The workspace the service is specific to. * @param clazz The class of the service to return. */ - Optional getServiceByWorkspace( - WorkspaceInfo workspace, Class clazz); + Optional getServiceByWorkspace(WorkspaceInfo workspace, Class clazz); /** * Looks up a service by id. diff --git a/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/GeoServerImpl.java b/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/GeoServerImpl.java index 3a7cf4dc6..ab54f95f5 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/GeoServerImpl.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/GeoServerImpl.java @@ -6,6 +6,12 @@ import static org.geoserver.ows.util.OwsUtils.resolveCollections; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Objects; +import java.util.logging.Level; +import java.util.logging.Logger; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.Info; import org.geoserver.catalog.WorkspaceInfo; @@ -35,13 +41,6 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Objects; -import java.util.logging.Level; -import java.util.logging.Logger; - /** * Default implementation of GeoServer global and service configuration manager. * @@ -194,11 +193,8 @@ void validate(SettingsInfo settings) { } // make sure the workspace exists and is not dettached from the catalog final WorkspaceInfo realws = getCatalog().getWorkspace(workspace.getId()); - Objects.requireNonNull( - realws, - () -> - "Workspace %s(%s) attached to SettingsInfo does not exist" - .formatted(workspace.getName(), workspace.getId())); + Objects.requireNonNull(realws, () -> "Workspace %s(%s) attached to SettingsInfo does not exist" + .formatted(workspace.getName(), workspace.getId())); settings.setWorkspace(realws); } @@ -218,10 +214,7 @@ void fireSettingsAdded(SettingsInfo settings) { @Override public void fireSettingsModified( - SettingsInfo settings, - List changed, - List oldValues, - List newValues) { + SettingsInfo settings, List changed, List oldValues, List newValues) { for (ConfigurationListener l : listeners) { try { l.handleSettingsModified(settings, changed, oldValues, newValues); @@ -264,21 +257,16 @@ public void setLogging(LoggingInfo logging) { @Override public void add(ServiceInfo service) { - if (service.getId() != null - && facade.getService(service.getId(), ServiceInfo.class) != null) { - throw new IllegalArgumentException( - "service with id '%s' already exists".formatted(service.getId())); + if (service.getId() != null && facade.getService(service.getId(), ServiceInfo.class) != null) { + throw new IllegalArgumentException("service with id '%s' already exists".formatted(service.getId())); } validate(service); resolve(service); WorkspaceInfo workspace = service.getWorkspace(); - if (workspace != null - && facade.getServiceByName(service.getName(), workspace, ServiceInfo.class) - != null) { - throw new IllegalArgumentException( - "service with name '%s' already exists in workspace '%s'" - .formatted(service.getName(), workspace.getName())); + if (workspace != null && facade.getServiceByName(service.getName(), workspace, ServiceInfo.class) != null) { + throw new IllegalArgumentException("service with name '%s' already exists in workspace '%s'" + .formatted(service.getName(), workspace.getName())); } facade.add(service); @@ -300,10 +288,7 @@ public T getService(Class clazz) { T service = ws != null ? facade.getService(ws, clazz) : null; service = service != null ? service : facade.getService(clazz); if (service == null) { - LOGGER.severe( - () -> - "Could not locate service of type %s, local workspace is %s" - .formatted(clazz, ws)); + LOGGER.severe(() -> "Could not locate service of type %s, local workspace is %s".formatted(clazz, ws)); } return service; @@ -321,16 +306,12 @@ public T getService(String id, Class clazz) { @Override public T getServiceByName(String name, Class clazz) { - T service = - LocalWorkspace.get() != null - ? facade.getServiceByName(name, LocalWorkspace.get(), clazz) - : null; + T service = LocalWorkspace.get() != null ? facade.getServiceByName(name, LocalWorkspace.get(), clazz) : null; return service != null ? service : facade.getServiceByName(name, clazz); } @Override - public T getServiceByName( - WorkspaceInfo workspace, String name, Class clazz) { + public T getServiceByName(WorkspaceInfo workspace, String name, Class clazz) { return facade.getServiceByName(name, workspace, clazz); } @@ -389,10 +370,7 @@ private void notifyPost(ConfigurationListener l, GeoServerInfo global) { @Override public void fireGlobalModified( - GeoServerInfo global, - List changed, - List oldValues, - List newValues) { + GeoServerInfo global, List changed, List oldValues, List newValues) { for (ConfigurationListener l : getListeners()) { try { @@ -405,10 +383,7 @@ public void fireGlobalModified( @Override public void fireLoggingModified( - LoggingInfo logging, - List changed, - List oldValues, - List newValues) { + LoggingInfo logging, List changed, List oldValues, List newValues) { for (ConfigurationListener l : getListeners()) { try { @@ -449,10 +424,7 @@ void validate(ServiceInfo service) { @Override public void fireServiceModified( - ServiceInfo service, - List changed, - List oldValues, - List newValues) { + ServiceInfo service, List changed, List oldValues, List newValues) { for (ConfigurationListener l : getListeners()) { try { @@ -501,15 +473,11 @@ public Collection getListeners() { @Override public void dispose() { // look for pluggable handlers - for (GeoServerLifecycleHandler handler : - GeoServerExtensions.extensions(GeoServerLifecycleHandler.class)) { + for (GeoServerLifecycleHandler handler : GeoServerExtensions.extensions(GeoServerLifecycleHandler.class)) { try { handler.onDispose(); } catch (RuntimeException t) { - LOGGER.log( - Level.SEVERE, - "A GeoServer lifecycle handler threw an exception during dispose", - t); + LOGGER.log(Level.SEVERE, "A GeoServer lifecycle handler threw an exception during dispose", t); } } @@ -527,16 +495,12 @@ public void reload() throws Exception { @Override public void reload(Catalog newCatalog) throws Exception { // notify start of reload - List handlers = - GeoServerExtensions.extensions(GeoServerLifecycleHandler.class); + List handlers = GeoServerExtensions.extensions(GeoServerLifecycleHandler.class); for (GeoServerLifecycleHandler handler : handlers) { try { handler.beforeReload(); } catch (RuntimeException t) { - LOGGER.log( - Level.SEVERE, - "A GeoServer lifecycle handler threw an exception during reload", - t); + LOGGER.log(Level.SEVERE, "A GeoServer lifecycle handler threw an exception during reload", t); } } @@ -570,10 +534,7 @@ public void reload(Catalog newCatalog) throws Exception { try { handler.onReload(); } catch (Exception t) { - LOGGER.log( - Level.SEVERE, - "A GeoServer lifecycle handler threw an exception during reload", - t); + LOGGER.log(Level.SEVERE, "A GeoServer lifecycle handler threw an exception during reload", t); } } } @@ -598,15 +559,11 @@ public void reset() { CRS.reset("all"); // look for pluggable handlers - for (GeoServerLifecycleHandler handler : - GeoServerExtensions.extensions(GeoServerLifecycleHandler.class)) { + for (GeoServerLifecycleHandler handler : GeoServerExtensions.extensions(GeoServerLifecycleHandler.class)) { try { handler.onReset(); } catch (RuntimeException t) { - LOGGER.log( - Level.SEVERE, - "A GeoServer lifecycle handler threw an exception during reset", - t); + LOGGER.log(Level.SEVERE, "A GeoServer lifecycle handler threw an exception during reset", t); } } } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/MemoryConfigRepository.java b/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/MemoryConfigRepository.java index f94d0ddc1..989385982 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/MemoryConfigRepository.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/MemoryConfigRepository.java @@ -6,6 +6,11 @@ import static java.util.Objects.requireNonNull; +import java.lang.reflect.Proxy; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.stream.Stream; import org.geoserver.catalog.Info; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.catalog.plugin.Patch; @@ -14,12 +19,6 @@ import org.geoserver.config.ServiceInfo; import org.geoserver.config.SettingsInfo; -import java.lang.reflect.Proxy; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.stream.Stream; - /** * Purely in-memory {@link ConfigRepository} implementation holding live-objects (no serialization * nor {@link Proxy proxying} involved) @@ -38,8 +37,7 @@ public Optional getGlobal() { private static void checkNotAProxy(Info value) { if (Proxy.isProxyClass(value.getClass())) { - throw new IllegalArgumentException( - "Proxy values shall not be passed to DefaultConfigRepository"); + throw new IllegalArgumentException("Proxy values shall not be passed to DefaultConfigRepository"); } } @@ -147,10 +145,8 @@ public Stream getServicesByWorkspace(WorkspaceInfo workspace) { requireNonNull(workspace); requireNonNull(workspace.getId()); return this.services.values().stream() - .filter( - s -> - s.getWorkspace() != null - && workspace.getId().equals(s.getWorkspace().getId())); + .filter(s -> s.getWorkspace() != null + && workspace.getId().equals(s.getWorkspace().getId())); } @Override @@ -164,17 +160,14 @@ public Optional getGlobalService(Class clazz) { } @Override - public Optional getServiceByWorkspace( - WorkspaceInfo workspace, Class clazz) { + public Optional getServiceByWorkspace(WorkspaceInfo workspace, Class clazz) { requireNonNull(workspace); requireNonNull(workspace.getId()); requireNonNull(clazz); return this.services.values().stream() .filter(clazz::isInstance) - .filter( - s -> - s.getWorkspace() != null - && s.getWorkspace().getId().equals(workspace.getId())) + .filter(s -> + s.getWorkspace() != null && s.getWorkspace().getId().equals(workspace.getId())) .map(clazz::cast) .findFirst(); } @@ -207,11 +200,9 @@ public Optional getServiceByNameAndWorkspace( requireNonNull(clazz); return this.services.values().stream() .filter(clazz::isInstance) - .filter( - s -> - s.getWorkspace() != null - && s.getWorkspace().getId().equals(workspace.getId()) - && name.equals(s.getName())) + .filter(s -> s.getWorkspace() != null + && s.getWorkspace().getId().equals(workspace.getId()) + && name.equals(s.getName())) .map(clazz::cast) .findFirst(); } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/RepositoryGeoServerFacadeImpl.java b/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/RepositoryGeoServerFacadeImpl.java index 9e7e9cff8..c41154122 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/RepositoryGeoServerFacadeImpl.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/RepositoryGeoServerFacadeImpl.java @@ -6,6 +6,16 @@ import static java.util.Objects.requireNonNull; +import java.lang.reflect.Proxy; +import java.rmi.server.UID; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; +import java.util.Optional; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.annotation.Nullable; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.MetadataMap; import org.geoserver.catalog.WorkspaceInfo; @@ -24,18 +34,6 @@ import org.geoserver.ows.util.OwsUtils; import org.geotools.util.logging.Logging; -import java.lang.reflect.Proxy; -import java.rmi.server.UID; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Objects; -import java.util.Optional; -import java.util.logging.Level; -import java.util.logging.Logger; - -import javax.annotation.Nullable; - /** * Default implementation of {@link GeoServerFacade} backed by a pluggable {@link ConfigRepository} * @@ -106,9 +104,7 @@ public void save(GeoServerInfo global) { @Override public SettingsInfo getSettings(WorkspaceInfo workspace) { requireNonNull(workspace); - return wrap( - resolve(repository.getSettingsByWorkspace(workspace).orElse(null)), - SettingsInfo.class); + return wrap(resolve(repository.getSettingsByWorkspace(workspace).orElse(null)), SettingsInfo.class); } @Override @@ -226,14 +222,14 @@ public T getServiceByName(String name, Class clazz) { } @Override - public T getServiceByName( - String name, WorkspaceInfo workspace, Class clazz) { + public T getServiceByName(String name, WorkspaceInfo workspace, Class clazz) { return findByName(name, workspace, clazz); } @Override public Collection getServices() { - List all = repository.getGlobalServices().map(this::resolve).toList(); + List all = + repository.getGlobalServices().map(this::resolve).toList(); return ModificationProxy.createList(all, ServiceInfo.class); } @@ -282,16 +278,13 @@ protected T find(Class type, @Nullable WorkspaceInfo service = repository.getServiceByWorkspace(workspace, type); } if (service.isEmpty() && LOGGER.isLoggable(Level.FINE)) { - LOGGER.fine( - "Could not locate service of type %s in workspace %s" - .formatted(type, workspace)); + LOGGER.fine("Could not locate service of type %s in workspace %s".formatted(type, workspace)); } return wrap(resolve(service.orElse(null)), type); } - protected T findByName( - String name, WorkspaceInfo workspace, Class type) { + protected T findByName(String name, WorkspaceInfo workspace, Class type) { Optional service; if (workspace == null) { service = repository.getServiceByName(name, type); @@ -300,9 +293,8 @@ protected T findByName( service = repository.getServiceByNameAndWorkspace(name, workspace, type); } if (service.isEmpty() && LOGGER.isLoggable(Level.FINE)) { - LOGGER.fine( - "Could not locate service of type %s in workspace %s and name '%s'" - .formatted(type, workspace, name)); + LOGGER.fine("Could not locate service of type %s in workspace %s and name '%s'" + .formatted(type, workspace, name)); } return wrap(resolve(service.orElse(null)), type); } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/forwarding/ForwardingGeoServerFacade.java b/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/forwarding/ForwardingGeoServerFacade.java index 3d4768457..02232f4ba 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/forwarding/ForwardingGeoServerFacade.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/config/plugin/forwarding/ForwardingGeoServerFacade.java @@ -4,6 +4,7 @@ */ package org.geoserver.config.plugin.forwarding; +import java.util.Collection; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.config.GeoServer; import org.geoserver.config.GeoServerFacade; @@ -14,8 +15,6 @@ import org.geoserver.config.plugin.ConfigRepository; import org.geoserver.config.plugin.RepositoryGeoServerFacade; -import java.util.Collection; - /** */ public class ForwardingGeoServerFacade implements RepositoryGeoServerFacade { @@ -36,11 +35,9 @@ public GeoServerFacade getSubject() { @Override public void setRepository(ConfigRepository repository) { - if (facade instanceof RepositoryGeoServerFacade repoFacade) - repoFacade.setRepository(repository); + if (facade instanceof RepositoryGeoServerFacade repoFacade) repoFacade.setRepository(repository); - throw new IllegalStateException( - "subject GeoServerFacade is not a RepositoryGeoServerFacade"); + throw new IllegalStateException("subject GeoServerFacade is not a RepositoryGeoServerFacade"); } @Override @@ -149,8 +146,7 @@ public T getServiceByName(String name, Class clazz) { } @Override - public T getServiceByName( - String name, WorkspaceInfo workspace, Class clazz) { + public T getServiceByName(String name, WorkspaceInfo workspace, Class clazz) { return facade.getServiceByName(name, workspace, clazz); } diff --git a/src/catalog/plugin/src/main/java/org/geoserver/platform/config/DefaultUpdateSequence.java b/src/catalog/plugin/src/main/java/org/geoserver/platform/config/DefaultUpdateSequence.java index 3a60dc662..9583ca3c4 100644 --- a/src/catalog/plugin/src/main/java/org/geoserver/platform/config/DefaultUpdateSequence.java +++ b/src/catalog/plugin/src/main/java/org/geoserver/platform/config/DefaultUpdateSequence.java @@ -4,16 +4,14 @@ */ package org.geoserver.platform.config; -import lombok.NonNull; - -import org.geoserver.catalog.impl.ModificationProxy; -import org.geoserver.config.GeoServer; -import org.geoserver.config.GeoServerInfo; - import java.util.Optional; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; +import lombok.NonNull; +import org.geoserver.catalog.impl.ModificationProxy; +import org.geoserver.config.GeoServer; +import org.geoserver.config.GeoServerInfo; /** * @since 1.0 @@ -30,10 +28,9 @@ public class DefaultUpdateSequence implements UpdateSequence { public DefaultUpdateSequence(@NonNull GeoServer gs) { this.geoServer = gs; - sequence.set( - Optional.ofNullable(gs.getGlobal()) - .map(GeoServerInfo::getUpdateSequence) - .orElse(0L)); + sequence.set(Optional.ofNullable(gs.getGlobal()) + .map(GeoServerInfo::getUpdateSequence) + .orElse(0L)); } @Override @@ -59,11 +56,9 @@ public long nextValue() { } private Optional info() { - return Optional.ofNullable(geoServer.getGlobal()) - .map( - global -> { - sequence.compareAndSet(UNSET, global.getUpdateSequence()); - return global; - }); + return Optional.ofNullable(geoServer.getGlobal()).map(global -> { + sequence.compareAndSet(UNSET, global.getUpdateSequence()); + return global; + }); } } diff --git a/src/catalog/plugin/src/test/java/org/geoserver/catalog/CatalogTestData.java b/src/catalog/plugin/src/test/java/org/geoserver/catalog/CatalogTestData.java index 958a35ba3..6562fe8e9 100644 --- a/src/catalog/plugin/src/test/java/org/geoserver/catalog/CatalogTestData.java +++ b/src/catalog/plugin/src/test/java/org/geoserver/catalog/CatalogTestData.java @@ -6,10 +6,16 @@ import static org.junit.jupiter.api.Assertions.assertEquals; +import java.io.Serializable; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; import lombok.Getter; import lombok.NonNull; import lombok.experimental.Accessors; - import org.geoserver.catalog.faker.CatalogFaker; import org.geoserver.catalog.impl.LayerGroupInfoImpl; import org.geoserver.catalog.plugin.CatalogPlugin; @@ -39,14 +45,6 @@ import org.geotools.util.Converters; import org.springframework.lang.Nullable; -import java.io.Serializable; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Supplier; - /** * Provides or populates a catalog; use {@link CatalogTestData#empty * CatalogTestData.empty(Supplier)} to start up with an empty catalog but having the test @@ -66,10 +64,7 @@ public class CatalogTestData { private final @Getter CatalogFaker faker; private CatalogTestData( - Supplier catalog, - Supplier config, - boolean initCatalog, - boolean initConfig) { + Supplier catalog, Supplier config, boolean initCatalog, boolean initConfig) { this.catalog = catalog; this.configCatalog = config; this.initializeCatalog = initCatalog; @@ -96,8 +91,7 @@ public static CatalogTestData empty(Supplier catalog, Supplier catalog, Supplier config) { + public static CatalogTestData initialized(Supplier catalog, Supplier config) { return new CatalogTestData(catalog, config, true, true); } @@ -155,14 +149,11 @@ public void deleteAll() { public void deleteAll(GeoServer gs) { if (gs != null) { gs.getServices().forEach(gs::remove); - catalog.get() - .getWorkspaces() - .forEach( - ws -> { - SettingsInfo settings = gs.getSettings(ws); - if (settings != null) gs.remove(settings); - gs.getServices(ws).forEach(gs::remove); - }); + catalog.get().getWorkspaces().forEach(ws -> { + SettingsInfo settings = gs.getSettings(ws); + if (settings != null) gs.remove(settings); + gs.getServices(ws).forEach(gs::remove); + }); } } @@ -259,27 +250,16 @@ public CatalogTestData createCatalogObjects() { dataStoreB = faker().dataStoreInfo("ds2", workspaceB, "dsNameA", "dsDescription", true); dataStoreC = faker().dataStoreInfo("ds3", workspaceC, "dsNameB", "dsDescription", true); - featureTypeA = - createFeatureType( - "ft1", - dataStoreA, - namespaceA, - "ftName", - "ftAbstract", - "ftDescription", - true); - - coverageStoreA = - createCoverageStore("cs1", workspaceA, "csName", "fakeCoverageType", "file://fake"); + featureTypeA = createFeatureType("ft1", dataStoreA, namespaceA, "ftName", "ftAbstract", "ftDescription", true); + + coverageStoreA = createCoverageStore("cs1", workspaceA, "csName", "fakeCoverageType", "file://fake"); coverageA = createCoverage("cov1", coverageStoreA, "cvName"); wmsStoreA = createWebMapServer("wms1", workspaceA, "wmsName", "http://fake.url", true); wmsLayerA = createWMSLayer("wmsl-1", wmsStoreA, namespaceA, "wmsLayer1", true); - wmtsStoreA = - createWebMapTileServer( - "wmts1", workspaceA, "wmtsName", "http://fake.wmts.url", true); + wmtsStoreA = createWebMapTileServer("wmts1", workspaceA, "wmtsName", "http://fake.wmts.url", true); wmtsLayerA = createWMTSLayer("wmtsl1", wmtsStoreA, namespaceA, "wmtsLayer", true); @@ -357,8 +337,7 @@ public CatalogTestData createConfigObjects() { return this; } - public LayerGroupInfo createLayerGroup( - String name, @Nullable WorkspaceInfo ws, PublishedInfo layer) { + public LayerGroupInfo createLayerGroup(String name, @Nullable WorkspaceInfo ws, PublishedInfo layer) { StyleInfo style = layer instanceof LayerInfo l ? l.getDefaultStyle() : null; return createLayerGroup(null, ws, name, layer, style); } @@ -459,8 +438,7 @@ public WMSLayerInfo createWMSLayer( return wmsl; } - public WMSStoreInfo createWebMapServer( - String id, WorkspaceInfo wspace, String name, String url, boolean enabled) { + public WMSStoreInfo createWebMapServer(String id, WorkspaceInfo wspace, String name, String url, boolean enabled) { WMSStoreInfo wms = getFactory().createWebMapServer(); OwsUtils.set(wms, "id", id); wms.setName(name); @@ -530,14 +508,8 @@ public void assertEqualsLenientConnectionParameters(Info info1, Info info2) { DataStoreInfo ds2 = (DataStoreInfo) info2; Map p1 = new HashMap<>(ds1.getConnectionParameters()); Map p2 = new HashMap<>(ds2.getConnectionParameters()); - p1.forEach( - (k, v) -> - ds1.getConnectionParameters() - .put(k, Converters.convert(v, String.class))); - p2.forEach( - (k, v) -> - ds2.getConnectionParameters() - .put(k, Converters.convert(v, String.class))); + p1.forEach((k, v) -> ds1.getConnectionParameters().put(k, Converters.convert(v, String.class))); + p2.forEach((k, v) -> ds2.getConnectionParameters().put(k, Converters.convert(v, String.class))); assertEquals(ds1.getConnectionParameters(), ds2.getConnectionParameters()); } assertEquals(info1, info2); @@ -545,18 +517,15 @@ public void assertEqualsLenientConnectionParameters(Info info1, Info info2) { public void assertInternationalStringPropertiesEqual(Info info1, Info info2) { ClassProperties props = new ClassProperties(info1.getClass()); - List istringProps = - props.properties().stream() - .filter(p -> props.getter(p, InternationalString.class) != null) - .toList(); + List istringProps = props.properties().stream() + .filter(p -> props.getter(p, InternationalString.class) != null) + .toList(); for (String isp : istringProps) { InternationalString i1 = (InternationalString) OwsUtils.get(info1, isp); InternationalString i2 = (InternationalString) OwsUtils.get(info2, isp); Supplier msg = - () -> - "%s.%s:InternationalString" - .formatted(info1.getClass().getSimpleName(), isp); + () -> "%s.%s:InternationalString".formatted(info1.getClass().getSimpleName(), isp); assertEquals(i1, i2, msg); } } diff --git a/src/catalog/plugin/src/test/java/org/geoserver/catalog/faker/CatalogFaker.java b/src/catalog/plugin/src/test/java/org/geoserver/catalog/faker/CatalogFaker.java index 03363ab5b..3e829cd05 100644 --- a/src/catalog/plugin/src/test/java/org/geoserver/catalog/faker/CatalogFaker.java +++ b/src/catalog/plugin/src/test/java/org/geoserver/catalog/faker/CatalogFaker.java @@ -7,11 +7,18 @@ import com.github.javafaker.Address; import com.github.javafaker.Faker; import com.google.common.collect.Lists; - +import java.io.Serializable; +import java.math.BigDecimal; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.function.Supplier; +import java.util.stream.IntStream; import lombok.Getter; import lombok.NonNull; import lombok.experimental.Accessors; - import org.geoserver.catalog.AttributionInfo; import org.geoserver.catalog.AuthorityURLInfo; import org.geoserver.catalog.Catalog; @@ -84,16 +91,6 @@ import org.geotools.util.Version; import org.springframework.util.Assert; -import java.io.Serializable; -import java.math.BigDecimal; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Objects; -import java.util.function.Supplier; -import java.util.stream.IntStream; - @Accessors(fluent = true) public class CatalogFaker { @@ -105,8 +102,7 @@ public CatalogFaker(@NonNull Catalog catalog, @NonNull GeoServer geoserver) { this(() -> catalog, () -> geoserver); } - public CatalogFaker( - @NonNull Catalog catalog, @NonNull GeoServer geoserver, @NonNull Locale locale) { + public CatalogFaker(@NonNull Catalog catalog, @NonNull GeoServer geoserver, @NonNull Locale locale) { this(() -> catalog, () -> geoserver, locale); } @@ -115,9 +111,7 @@ public CatalogFaker(Supplier catalog, Supplier geoserver) { } public CatalogFaker( - @NonNull Supplier catalog, - @NonNull Supplier geoserver, - @NonNull Locale locale) { + @NonNull Supplier catalog, @NonNull Supplier geoserver, @NonNull Locale locale) { this.catalog = catalog; this.geoserver = geoserver; this.faker = new Faker(locale); @@ -163,12 +157,7 @@ public LayerGroupInfo layerGroupInfo( public LayerInfo layerInfo(ResourceInfo resource, StyleInfo defaultStyle) { - return layerInfo( - resource.getName() + "-layer-id", - resource, - resource.getName() + " title", - true, - defaultStyle); + return layerInfo(resource.getName() + "-layer-id", resource, resource.getName() + " title", true, defaultStyle); } public LayerInfo layerInfo( @@ -225,8 +214,7 @@ public WMTSLayerInfo wmtsLayerInfo( return wmtsl; } - public WMTSStoreInfo wmtsStoreInfo( - String id, WorkspaceInfo workspace, String name, String url, boolean enabled) { + public WMTSStoreInfo wmtsStoreInfo(String id, WorkspaceInfo workspace, String name, String url, boolean enabled) { WMTSStoreInfo wmtss = catalogFactory().createWebMapTileServer(); OwsUtils.set(wmtss, "id", id); wmtss.setWorkspace(workspace); @@ -250,8 +238,7 @@ public WMSLayerInfo wmsLayerInfo( return wmsl; } - public WMSStoreInfo wmsStoreInfo( - String id, WorkspaceInfo wspace, String name, String url, boolean enabled) { + public WMSStoreInfo wmsStoreInfo(String id, WorkspaceInfo wspace, String name, String url, boolean enabled) { WMSStoreInfo wms = catalogFactory().createWebMapServer(); OwsUtils.set(wms, "id", id); wms.setName(name); @@ -329,8 +316,7 @@ public DataStoreInfo dataStoreInfo(String name, WorkspaceInfo ws) { return dataStoreInfo("DataStoreInfo." + id(), ws, name, name + " description", true); } - public DataStoreInfo dataStoreInfo( - String id, WorkspaceInfo ws, String name, String description, boolean enabled) { + public DataStoreInfo dataStoreInfo(String id, WorkspaceInfo ws, String name, String description, boolean enabled) { DataStoreInfoImpl dstore = (DataStoreInfoImpl) catalogFactory().createDataStore(); OwsUtils.set(dstore, "id", id); dstore.setEnabled(enabled); @@ -480,8 +466,7 @@ public ContactInfo contactInfo() { Address it = italian().faker().address(); Address de = german().faker().address(); c.setInternationalAddress( - internationalString( - Locale.ITALIAN, it.fullAddress(), Locale.GERMAN, de.fullAddress())); + internationalString(Locale.ITALIAN, it.fullAddress(), Locale.GERMAN, de.fullAddress())); return c; } @@ -503,8 +488,7 @@ public SettingsInfo settingsInfo(WorkspaceInfo workspace) { s.setTitle(workspace == null ? "Global Settings" : workspace.getName() + " Settings"); s.setCharset("UTF-8"); s.setContact(contactInfo()); - s.getMetadata() - .putAll(metadataMap("k1", Integer.valueOf(1), "k2", "2", "k3", Boolean.FALSE)); + s.getMetadata().putAll(metadataMap("k1", Integer.valueOf(1), "k2", "2", "k3", Boolean.FALSE)); s.setNumDecimals(9); s.setOnlineResource("http://geoserver.org"); s.setProxyBaseUrl("http://test.geoserver.org"); @@ -520,18 +504,10 @@ public S serviceInfo(String name, Supplier factor s.setName(name); s.setTitle(name + " Title"); s.setAbstract(name + " Abstract"); - s.setInternationalTitle( - internationalString( - Locale.ENGLISH, - name + " english title", - Locale.CANADA_FRENCH, - name + "titre anglais")); - s.setInternationalAbstract( - internationalString( - Locale.ENGLISH, - name + " english abstract", - Locale.CANADA_FRENCH, - name + "résumé anglais")); + s.setInternationalTitle(internationalString( + Locale.ENGLISH, name + " english title", Locale.CANADA_FRENCH, name + "titre anglais")); + s.setInternationalAbstract(internationalString( + Locale.ENGLISH, name + " english abstract", Locale.CANADA_FRENCH, name + "résumé anglais")); s.setAccessConstraints("NONE"); s.setCiteCompliant(true); s.setEnabled(true); @@ -584,8 +560,7 @@ public GrowableInternationalString internationalString(Locale l, String val) { return s; } - public GrowableInternationalString internationalString( - Locale l1, String val1, Locale l2, String val2) { + public GrowableInternationalString internationalString(Locale l1, String val1, Locale l2, String val2) { GrowableInternationalString s = new GrowableInternationalString(); s.add(l1, val1); s.add(l2, val2); diff --git a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/AbstractCatalogVisitorTest.java b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/AbstractCatalogVisitorTest.java index 7b9d955bf..1b59543ea 100644 --- a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/AbstractCatalogVisitorTest.java +++ b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/AbstractCatalogVisitorTest.java @@ -32,18 +32,17 @@ class AbstractCatalogVisitorTest { @BeforeEach void setup() { - visitor = - new AbstractCatalogVisitor() { - @Override - protected void visit(StoreInfo store) { - visitedStore = store; - } - - @Override - protected void visit(ResourceInfo resource) { - visitedResource = resource; - } - }; + visitor = new AbstractCatalogVisitor() { + @Override + protected void visit(StoreInfo store) { + visitedStore = store; + } + + @Override + protected void visit(ResourceInfo resource) { + visitedResource = resource; + } + }; } @Test diff --git a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/CatalogConformanceTest.java b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/CatalogConformanceTest.java index 1d58619be..56d6c2919 100644 --- a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/CatalogConformanceTest.java +++ b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/CatalogConformanceTest.java @@ -5,7 +5,6 @@ package org.geoserver.catalog.plugin; import static com.google.common.collect.Sets.newHashSet; - import static org.geoserver.catalog.Predicates.acceptAll; import static org.geoserver.catalog.Predicates.asc; import static org.geoserver.catalog.Predicates.contains; @@ -32,7 +31,28 @@ import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Sets; - +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Set; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorCompletionService; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.logging.Level; +import java.util.logging.Logger; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogException; import org.geoserver.catalog.CatalogFactory; @@ -100,29 +120,6 @@ import org.junit.jupiter.api.io.TempDir; import org.mockito.Mockito; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.lang.reflect.Proxy; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Set; -import java.util.concurrent.CopyOnWriteArrayList; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorCompletionService; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.logging.Level; -import java.util.logging.Logger; - /** * Initially a verbatim copy of {@code gs-main}'s {@code * org.geoserver.catalog.impl.CatalogImplTest}, adapted to not subclass {@code @@ -140,7 +137,8 @@ public abstract class CatalogConformanceTest { private DataAccessRuleDAO dataAccessRuleDAO; - @TempDir public File tmpFolder; + @TempDir + public File tmpFolder; @BeforeAll static void beforeAll() { @@ -149,8 +147,8 @@ static void beforeAll() { Logging.getLogger("org.geoserver.catalog.impl").setLevel(Level.SEVERE); } - protected void addLayerAccessRule( - String workspace, String layer, AccessMode mode, String... roles) throws IOException { + protected void addLayerAccessRule(String workspace, String layer, AccessMode mode, String... roles) + throws IOException { DataAccessRuleDAO dao = this.dataAccessRuleDAO; DataAccessRule rule = new DataAccessRule(); rule.setRoot(workspace); @@ -172,9 +170,7 @@ protected void addLayerAccessRule( @BeforeEach public void setUp() { catalog = createCatalog(tmpFolder); - assertNotNull( - catalog.getResourceLoader(), - "Catalog must be supplied with a GeoServerResourceLoader"); + assertNotNull(catalog.getResourceLoader(), "Catalog must be supplied with a GeoServerResourceLoader"); dd = new GeoServerDataDirectory(catalog.getResourceLoader()); try { dataAccessRuleDAO = new DataAccessRuleDAO(dd, catalog); @@ -320,21 +316,14 @@ void testAddNamespace() { NamespaceInfo ns2 = catalog.getFactory().createNamespace(); assertThrows( - NullPointerException.class, - () -> catalog.add(ns2), - "adding without a prefix should throw exception"); + NullPointerException.class, () -> catalog.add(ns2), "adding without a prefix should throw exception"); ns2.setPrefix("ns2Prefix"); - assertThrows( - NullPointerException.class, - () -> catalog.add(ns2), - "adding without a uri should throw exception"); + assertThrows(NullPointerException.class, () -> catalog.add(ns2), "adding without a uri should throw exception"); ns2.setURI("bad uri"); assertThrows( - IllegalArgumentException.class, - () -> catalog.add(ns2), - "adding an invalid uri should throw exception"); + IllegalArgumentException.class, () -> catalog.add(ns2), "adding an invalid uri should throw exception"); ns2.setURI("ns2URI"); List namespaces = catalog.getNamespaces(); @@ -372,16 +361,14 @@ void testAddIsolatedNamespace() { assertThat(foundNamespace2.getURI(), is("http://www.isolated_namespace.com")); assertThat(foundNamespace2.isIsolated(), is(true)); // retrieve the namespace by URI, the non isolated one should be returned - NamespaceInfo foundNamespace3 = - catalog.getNamespaceByURI("http://www.isolated_namespace.com"); + NamespaceInfo foundNamespace3 = catalog.getNamespaceByURI("http://www.isolated_namespace.com"); assertThat(foundNamespace3.getPrefix(), is("isolated_namespace_1")); assertThat(foundNamespace3.getURI(), is("http://www.isolated_namespace.com")); assertThat(foundNamespace3.isIsolated(), is(false)); // remove the non isolated namespace catalog.remove(foundNamespace1); // retrieve the namespace by URI, NULL should be returned - NamespaceInfo foundNamespace4 = - catalog.getNamespaceByURI("http://www.isolated_namespace.com"); + NamespaceInfo foundNamespace4 = catalog.getNamespaceByURI("http://www.isolated_namespace.com"); assertThat(foundNamespace4, nullValue()); } finally { // remove the namespaces @@ -447,11 +434,10 @@ void testGetNamespaceByURI() { @Test void testSetDefaultNamespaceInvalid() { - IllegalArgumentException iae = - assertThrows( - IllegalArgumentException.class, - () -> catalog.setDefaultNamespace(data.namespaceA), - "Default namespace must exist in catalog"); + IllegalArgumentException iae = assertThrows( + IllegalArgumentException.class, + () -> catalog.setDefaultNamespace(data.namespaceA), + "Default namespace must exist in catalog"); assertEquals("No such namespace: 'wsName'", iae.getMessage()); } @@ -465,16 +451,11 @@ void testModifyNamespace() { ns2.setURI("ns2URI"); assertThrows( - NullPointerException.class, - () -> catalog.save(ns2), - "setting prefix to null should throw exception"); + NullPointerException.class, () -> catalog.save(ns2), "setting prefix to null should throw exception"); ns2.setPrefix("ns2Prefix"); ns2.setURI(null); - assertThrows( - NullPointerException.class, - () -> catalog.save(ns2), - "setting uri to null should throw exception"); + assertThrows(NullPointerException.class, () -> catalog.save(ns2), "setting uri to null should throw exception"); ns2.setURI("ns2URI"); @@ -508,7 +489,8 @@ void testNamespaceEvents() { assertEquals("defaultNamespace", l.modified.get(0).getPropertyNames().get(0)); assertEquals(1, l.postModified.size()); assertEquals(catalog, l.postModified.get(0).getSource()); - assertEquals("defaultNamespace", l.postModified.get(0).getPropertyNames().get(0)); + assertEquals( + "defaultNamespace", l.postModified.get(0).getPropertyNames().get(0)); ns = catalog.getNamespaceByPrefix("ns2Prefix"); ns.setURI("changed"); @@ -546,9 +528,7 @@ void testAddWorkspace() { "adding directly should throw an exception"); assertThrows( - NullPointerException.class, - () -> catalog.add(ws2), - "adding without a name should throw an exception"); + NullPointerException.class, () -> catalog.add(ws2), "adding without a name should throw an exception"); ws2.setName("ws2"); catalog.add(ws2); @@ -717,11 +697,10 @@ void testGetWorkspaceByName() { @Test void testSetDefaultWorkspaceInvalid() { - IllegalArgumentException iae = - assertThrows( - IllegalArgumentException.class, - () -> catalog.setDefaultWorkspace(data.workspaceA), - "Default workspace must exist in catalog"); + IllegalArgumentException iae = assertThrows( + IllegalArgumentException.class, + () -> catalog.setDefaultWorkspace(data.workspaceA), + "Default workspace must exist in catalog"); assertEquals("No such workspace: 'wsName'", iae.getMessage()); } @@ -732,9 +711,7 @@ void testModifyWorkspace() { WorkspaceInfo ws2 = catalog.getWorkspaceByName(data.workspaceA.getName()); ws2.setName(null); assertThrows( - NullPointerException.class, - () -> catalog.save(ws2), - "setting name to null should throw exception"); + NullPointerException.class, () -> catalog.save(ws2), "setting name to null should throw exception"); ws2.setName("ws2"); @@ -763,7 +740,8 @@ void testWorkspaceEvents() { assertEquals(catalog, l.modified.get(0).getSource()); assertEquals("defaultWorkspace", l.modified.get(0).getPropertyNames().get(0)); assertEquals(catalog, l.postModified.get(0).getSource()); - assertEquals("defaultWorkspace", l.postModified.get(0).getPropertyNames().get(0)); + assertEquals( + "defaultWorkspace", l.postModified.get(0).getPropertyNames().get(0)); ws = catalog.getWorkspaceByName("ws2"); ws.setName("changed"); @@ -805,9 +783,7 @@ void testAddDataStore() { DataStoreInfo ds2 = catalog.getFactory().createDataStore(); assertThrows( - IllegalArgumentException.class, - () -> catalog.add(ds2), - "adding without a name should throw exception"); + IllegalArgumentException.class, () -> catalog.add(ds2), "adding without a name should throw exception"); ds2.setName("ds2Name"); List dataStores = catalog.getDataStores(); @@ -990,8 +966,7 @@ void testChangeDataStoreWorkspace_fails_on_no_matching_namespace() { DataStoreInfo ds2 = catalog.getDataStoreByName(ds.getName()); ds2.setWorkspace(ws2); - IllegalArgumentException expected = - assertThrows(IllegalArgumentException.class, () -> catalog.save(ds2)); + IllegalArgumentException expected = assertThrows(IllegalArgumentException.class, () -> catalog.save(ds2)); assertThat( expected.getMessage(), containsString( @@ -1015,9 +990,7 @@ void testSaveDataStoreRollbacksStoreWhenFailsToUpdateResourcesNamespace() { catalog = Mockito.spy((CatalogImpl) this.catalog); // throw once the store's been saved and its resources are about to have the new namespace // set - doThrow(IllegalStateException.class) - .when((CatalogPlugin) catalog) - .updateNamespace(any(), any()); + doThrow(IllegalStateException.class).when((CatalogPlugin) catalog).updateNamespace(any(), any()); final String oldName = store.getName(); store.setName("newName"); @@ -1059,9 +1032,7 @@ protected void testSaveDataStoreRollbacksBothStoreAndResources() { catalog = Mockito.spy((CatalogPlugin) catalog); // let the first ft's namespace be updated, fail on the second - doThrow(IllegalStateException.class) - .when((CatalogPlugin) catalog) - .updateNamespace(eq(ft2), any()); + doThrow(IllegalStateException.class).when((CatalogPlugin) catalog).updateNamespace(eq(ft2), any()); final String oldName = store.getName(); store.setName("newName"); @@ -1071,14 +1042,12 @@ protected void testSaveDataStoreRollbacksBothStoreAndResources() { DataStoreInfo store2 = catalog.getDataStore(data.dataStoreA.getId()); assertEquals(oldName, store2.getName(), "store's not rolled back before throwing"); - assertEquals( - oldWorkspace, store2.getWorkspace(), "store's not rolled back before throwing"); + assertEquals(oldWorkspace, store2.getWorkspace(), "store's not rolled back before throwing"); List resources = catalog.getResourcesByStore(store2, ResourceInfo.class); assertFalse(resources.isEmpty()); for (ResourceInfo resource : resources) { - assertEquals( - oldNamespace, resource.getNamespace(), "ft's not rolled back before throwing"); + assertEquals(oldNamespace, resource.getNamespace(), "ft's not rolled back before throwing"); } } @@ -1108,9 +1077,8 @@ private void verifyNamespaceOfStoreResources(StoreInfo store) { for (ResourceInfo resource : resources) { NamespaceInfo actual = resource.getNamespace(); assertNotNull(actual); - String msg = - "resource %s of store %s did not get its namespace updated" - .formatted(resource.getName(), store.getName()); + String msg = "resource %s of store %s did not get its namespace updated" + .formatted(resource.getName(), store.getName()); assertEquals(expected, actual, msg); } } @@ -1177,17 +1145,12 @@ void testAddFeatureType() { assertEquals(1, catalog.getFeatureTypes().size()); FeatureTypeInfo ft2 = catalog.getFactory().createFeatureType(); - assertThrows( - NullPointerException.class, - () -> catalog.add(ft2), - "adding with no name should throw exception"); + assertThrows(NullPointerException.class, () -> catalog.add(ft2), "adding with no name should throw exception"); ft2.setName("ft2Name"); assertThrows( - IllegalArgumentException.class, - () -> catalog.add(ft2), - "adding with no store should throw exception"); + IllegalArgumentException.class, () -> catalog.add(ft2), "adding with no store should throw exception"); ft2.setStore(data.dataStoreA); ft2.getKeywords().add(new Keyword("keyword")); @@ -1216,16 +1179,11 @@ void testAddCoverage() { assertEquals(1, catalog.getCoverages().size()); CoverageInfo cv2 = catalog.getFactory().createCoverage(); - assertThrows( - NullPointerException.class, - () -> catalog.add(cv2), - "adding with no name should throw exception"); + assertThrows(NullPointerException.class, () -> catalog.add(cv2), "adding with no name should throw exception"); cv2.setName("cv2Name"); assertThrows( - IllegalArgumentException.class, - () -> catalog.add(cv2), - "adding with no store should throw exception"); + IllegalArgumentException.class, () -> catalog.add(cv2), "adding with no store should throw exception"); cv2.setStore(data.coverageStoreA); catalog.add(cv2); @@ -1537,25 +1495,19 @@ void testAddLayer() { assertEquals(1, catalog.getLayers().size()); LayerInfo l2 = catalog.getFactory().createLayer(); - assertThrows( - NullPointerException.class, - () -> catalog.add(l2), - "adding with no name should throw exception"); + assertThrows(NullPointerException.class, () -> catalog.add(l2), "adding with no name should throw exception"); assertThrows( - NullPointerException.class, - () -> catalog.add(l2), - "adding with no resource should throw exception"); + NullPointerException.class, () -> catalog.add(l2), "adding with no resource should throw exception"); l2.setResource(data.featureTypeA); l2.setDefaultStyle(data.style1); - IllegalArgumentException e = - assertThrows( - IllegalArgumentException.class, - () -> catalog.add(l2), - "Adding a second layer for the same resource should throw exception, layer name is tied to resource name and would end up with two layers named the same or a broken catalog"); + IllegalArgumentException e = assertThrows( + IllegalArgumentException.class, + () -> catalog.add(l2), + "Adding a second layer for the same resource should throw exception, layer name is tied to resource name and would end up with two layers named the same or a broken catalog"); assertTrue(e.getMessage().contains("already exists")); @@ -1740,8 +1692,7 @@ void testRemoveLayerAndAssociatedDataRules() throws IOException { catalog.removeListener(listener); } - private boolean layerHasSecurityRule( - DataAccessRuleDAO dao, String workspaceName, String layerName) { + private boolean layerHasSecurityRule(DataAccessRuleDAO dao, String workspaceName, String layerName) { List rules = dao.getRules(); for (DataAccessRule rule : rules) { @@ -1763,9 +1714,7 @@ void testModifyLayer() { assertEquals(data.layerFeatureTypeA.getName(), l3.getName()); assertThrows( - NullPointerException.class, - () -> catalog.save(l2), - "setting resource to null should throw exception"); + NullPointerException.class, () -> catalog.save(l2), "setting resource to null should throw exception"); l2.setResource(data.featureTypeA); catalog.save(l2); @@ -1859,23 +1808,16 @@ void testAddStyle() { assertEquals(1, catalog.getStyles().size()); StyleInfo s2 = catalog.getFactory().createStyle(); - assertThrows( - NullPointerException.class, - () -> catalog.add(s2), - "adding without name should throw exception"); + assertThrows(NullPointerException.class, () -> catalog.add(s2), "adding without name should throw exception"); s2.setName("s2Name"); assertThrows( - NullPointerException.class, - () -> catalog.add(s2), - "adding without fileName should throw exception"); + NullPointerException.class, () -> catalog.add(s2), "adding without fileName should throw exception"); s2.setFilename("s2Filename"); List styles = catalog.getStyles(); assertThrows( - UnsupportedOperationException.class, - () -> styles.add(s2), - "adding directly should throw exception"); + UnsupportedOperationException.class, () -> styles.add(s2), "adding directly should throw exception"); catalog.add(s2); assertEquals(2, catalog.getStyles().size()); @@ -2017,16 +1959,10 @@ void testModifyStyle() { StyleInfo s3 = catalog.getStyleByName(data.style1.getName()); assertEquals(data.style1, s3); - assertThrows( - NullPointerException.class, - () -> catalog.save(s2), - "setting name to null should fail"); + assertThrows(NullPointerException.class, () -> catalog.save(s2), "setting name to null should fail"); s2.setName(data.style1.getName()); - assertThrows( - NullPointerException.class, - () -> catalog.save(s2), - "setting filename to null should fail"); + assertThrows(NullPointerException.class, () -> catalog.save(s2), "setting filename to null should fail"); s2.setName("s2Name"); s2.setFilename("s2Name.sld"); @@ -2078,8 +2014,7 @@ protected void testModifyStyleChangeWorkspace() throws IOException { Resource origSldResource = dd.style(orig); assertFalse(Resources.exists(origSldResource)); - catalog.getResourcePool() - .writeStyle(orig, new ByteArrayInputStream(sld.getBytes(StandardCharsets.UTF_8))); + catalog.getResourcePool().writeStyle(orig, new ByteArrayInputStream(sld.getBytes(StandardCharsets.UTF_8))); assertTrue(Resources.exists(dd.style(orig))); Style style = catalog.getResourcePool().getStyle(orig); assertNotNull(style); @@ -2110,9 +2045,7 @@ void testModifyDefaultStyle() { s.setName("foo"); assertThrows( - IllegalArgumentException.class, - () -> catalog.save(s), - "changing name of default style should fail"); + IllegalArgumentException.class, () -> catalog.save(s), "changing name of default style should fail"); final StyleInfo s2 = catalog.getStyleByName(StyleInfo.DEFAULT_LINE); s2.setWorkspace(data.workspaceA); @@ -2137,10 +2070,7 @@ void testRemoveDefaultStyle() { addDefaultStyle(); StyleInfo s = catalog.getStyleByName(StyleInfo.DEFAULT_LINE); - assertThrows( - IllegalArgumentException.class, - () -> catalog.remove(s), - "removing default style should fail"); + assertThrows(IllegalArgumentException.class, () -> catalog.remove(s), "removing default style should fail"); } @Test @@ -2209,13 +2139,12 @@ void testProxyListBehaviour() { assertEquals(2, styles.size()); // test immutability - Comparator comparator = - new Comparator() { + Comparator comparator = new Comparator() { - public int compare(StyleInfo o1, StyleInfo o2) { - return o1.getName().compareTo(o2.getName()); - } - }; + public int compare(StyleInfo o1, StyleInfo o2) { + return o1.getName().compareTo(o2.getName()); + } + }; assertThrows( RuntimeException.class, () -> Collections.sort(styles, comparator), @@ -2246,9 +2175,7 @@ void testExceptionThrowingListener() { ws2.setName("bar"); CatalogException ce = assertThrows(CatalogException.class, () -> catalog.add(ws2)); - assertThat( - ce.getMessage(), - containsString("expected, testing Catalog's CatalogException handling")); + assertThat(ce.getMessage(), containsString("expected, testing Catalog's CatalogException handling")); } @Test @@ -2313,8 +2240,7 @@ void testGetLayerByIdWithConcurrentAdd() throws Exception { catalog.add(layer); String id = layer.getId(); - CountDownLatch ready = - new CountDownLatch(GET_LAYER_BY_ID_WITH_CONCURRENT_ADD_THREAD_COUNT + 1); + CountDownLatch ready = new CountDownLatch(GET_LAYER_BY_ID_WITH_CONCURRENT_ADD_THREAD_COUNT + 1); CountDownLatch done = new CountDownLatch(GET_LAYER_BY_ID_WITH_CONCURRENT_ADD_THREAD_COUNT); List runners = new ArrayList(); @@ -2399,9 +2325,7 @@ void testGetLayerGroupByName() { catalog.add(ws2); catalog.setDefaultWorkspace(ws2); - assertNull( - catalog.getLayerGroupByName("layerGroup2"), - "layerGroup2 is not global, should not be found"); + assertNull(catalog.getLayerGroupByName("layerGroup2"), "layerGroup2 is not global, should not be found"); assertNotNull(catalog.getLayerGroupByName(data.workspaceA.getName() + ":layerGroup2")); assertNotNull(catalog.getLayerGroupByName(data.workspaceA, "layerGroup2")); assertNull(catalog.getLayerGroupByName("cite", "layerGroup2")); @@ -2446,8 +2370,7 @@ void testGetLayerGroupByNameWithColon() { // lg is not global, should not be found at least we specify a prefixed name assertNull( - catalog.getLayerGroupByName(lgName), - "MyFakeWorkspace:layerGroup is not global, should not be found"); + catalog.getLayerGroupByName(lgName), "MyFakeWorkspace:layerGroup is not global, should not be found"); assertEquals(lg, catalog.getLayerGroupByName(data.workspaceA.getName(), lgName)); assertEquals(lg, catalog.getLayerGroupByName(data.workspaceA, lgName)); @@ -2530,7 +2453,8 @@ void testGetLayerGroupByNameWithWorkspace() { void testGetLayerGroups() { addLayerGroup(); assertEquals(1, catalog.getLayerGroups().size()); - assertEquals(0, catalog.getLayerGroupsByWorkspace(data.workspaceA.getName()).size()); + assertEquals( + 0, catalog.getLayerGroupsByWorkspace(data.workspaceA.getName()).size()); assertEquals(0, catalog.getLayerGroupsByWorkspace(data.workspaceA).size()); assertEquals(0, catalog.getLayerGroupsByWorkspace((WorkspaceInfo) null).size()); @@ -2542,7 +2466,8 @@ void testGetLayerGroups() { catalog.add(lg2); assertEquals(2, catalog.getLayerGroups().size()); - assertEquals(1, catalog.getLayerGroupsByWorkspace(data.workspaceA.getName()).size()); + assertEquals( + 1, catalog.getLayerGroupsByWorkspace(data.workspaceA.getName()).size()); assertEquals(1, catalog.getLayerGroupsByWorkspace(data.workspaceA).size()); assertEquals(1, catalog.getLayerGroupsByWorkspace((WorkspaceInfo) null).size()); } @@ -2626,34 +2551,23 @@ void testLayerGroupRootLayer() { lg2.setMode(LayerGroupInfo.Mode.SINGLE); assertThrows( - IllegalArgumentException.class, - () -> catalog.add(lg2), - "only EO layer groups can have a root layer"); + IllegalArgumentException.class, () -> catalog.add(lg2), "only EO layer groups can have a root layer"); lg2.setMode(LayerGroupInfo.Mode.NAMED); assertThrows( - IllegalArgumentException.class, - () -> catalog.add(lg2), - "only EO layer groups can have a root layer"); + IllegalArgumentException.class, () -> catalog.add(lg2), "only EO layer groups can have a root layer"); lg2.setMode(LayerGroupInfo.Mode.CONTAINER); assertThrows( - IllegalArgumentException.class, - () -> catalog.add(lg2), - "only EO layer groups can have a root layer"); + IllegalArgumentException.class, () -> catalog.add(lg2), "only EO layer groups can have a root layer"); lg2.setMode(LayerGroupInfo.Mode.EO); lg2.setRootLayer(null); - assertThrows( - IllegalArgumentException.class, - () -> catalog.add(lg2), - "EO layer groups must have a root layer"); + assertThrows(IllegalArgumentException.class, () -> catalog.add(lg2), "EO layer groups must have a root layer"); lg2.setRootLayer(data.layerFeatureTypeA); assertThrows( - IllegalArgumentException.class, - () -> catalog.add(lg2), - "EO layer groups must have a root layer style"); + IllegalArgumentException.class, () -> catalog.add(lg2), "EO layer groups must have a root layer style"); lg2.setRootLayerStyle(data.style1); @@ -2732,13 +2646,9 @@ void testLayerGroupRenderingLayers() { lg2.setMode(LayerGroupInfo.Mode.CONTAINER); assertThrows( - UnsupportedOperationException.class, - lg2::layers, - "Layer group of Type Container can not be rendered"); + UnsupportedOperationException.class, lg2::layers, "Layer group of Type Container can not be rendered"); assertThrows( - UnsupportedOperationException.class, - lg2::styles, - "Layer group of Type Container can not be rendered"); + UnsupportedOperationException.class, lg2::styles, "Layer group of Type Container can not be rendered"); lg2.setMode(LayerGroupInfo.Mode.EO); assertEquals(1, lg2.layers().size()); @@ -2967,7 +2877,8 @@ void testGet() { "Expected IAE on multiple results"); assertEquals( - s1.getId(), catalog.get(StyleInfo.class, equal("filename", "s1Filename")).getId()); + s1.getId(), + catalog.get(StyleInfo.class, equal("filename", "s1Filename")).getId()); filter = equal("defaultStyle.filename", "s1Filename"); assertEquals(l1.getId(), catalog.get(LayerInfo.class, filter).getId()); @@ -2977,8 +2888,7 @@ void testGet() { filter = equal("styles.id", s2.getId(), MatchAction.ONE); assertEquals(l1.getId(), catalog.get(LayerInfo.class, filter).getId()); - Filter filter2 = - equal("styles.id", s3.getId(), MatchAction.ANY); // s3 is shared by l1 and l2 + Filter filter2 = equal("styles.id", s3.getId(), MatchAction.ANY); // s3 is shared by l1 and l2 assertThrows( IllegalArgumentException.class, () -> catalog.get(LayerInfo.class, filter2), @@ -3049,8 +2959,7 @@ void testListPredicate() { assertEquals(expected, actual); filter = acceptAll(); - ArrayList naturalOrder = - Lists.newArrayList(catalog.list(LayerInfo.class, filter)); + ArrayList naturalOrder = Lists.newArrayList(catalog.list(LayerInfo.class, filter)); assertEquals(3, naturalOrder.size()); int offset = 0, limit = 2; @@ -3129,72 +3038,36 @@ void testListPredicateExtended() { assertEquals(expected, actual); // match action - filter = - factory.equal( - factory.literal(new Keyword("keyword1")), - factory.property("keywords"), - true, - MatchAction.ANY); + filter = factory.equal( + factory.literal(new Keyword("keyword1")), factory.property("keywords"), true, MatchAction.ANY); expected = Sets.newHashSet(ft1, ft2); actual = Sets.newHashSet(catalog.list(FeatureTypeInfo.class, filter)); assertEquals(expected, actual); - filter = - factory.equal( - factory.literal(new Keyword("keyword1")), - factory.property("keywords"), - true, - MatchAction.ALL); + filter = factory.equal( + factory.literal(new Keyword("keyword1")), factory.property("keywords"), true, MatchAction.ALL); expected = Sets.newHashSet(ft2); actual = Sets.newHashSet(catalog.list(FeatureTypeInfo.class, filter)); assertEquals(expected, actual); - filter = - factory.equal( - factory.literal(new Keyword("keyword1")), - factory.property("keywords"), - true, - MatchAction.ONE); + filter = factory.equal( + factory.literal(new Keyword("keyword1")), factory.property("keywords"), true, MatchAction.ONE); expected = Sets.newHashSet(ft1); actual = Sets.newHashSet(catalog.list(FeatureTypeInfo.class, filter)); assertEquals(expected, actual); // match action - like - filter = - factory.like( - factory.property("keywords"), - "key*d1", - "*", - "?", - "\\", - true, - MatchAction.ANY); + filter = factory.like(factory.property("keywords"), "key*d1", "*", "?", "\\", true, MatchAction.ANY); expected = Sets.newHashSet(ft1, ft2); actual = Sets.newHashSet(catalog.list(FeatureTypeInfo.class, filter)); assertEquals(expected, actual); - filter = - factory.like( - factory.property("keywords"), - "key*d1", - "*", - "?", - "\\", - true, - MatchAction.ALL); + filter = factory.like(factory.property("keywords"), "key*d1", "*", "?", "\\", true, MatchAction.ALL); expected = Sets.newHashSet(ft2); actual = Sets.newHashSet(catalog.list(FeatureTypeInfo.class, filter)); assertEquals(expected, actual); - filter = - factory.like( - factory.property("keywords"), - "key*d1", - "*", - "?", - "\\", - true, - MatchAction.ONE); + filter = factory.like(factory.property("keywords"), "key*d1", "*", "?", "\\", true, MatchAction.ONE); expected = Sets.newHashSet(ft1); actual = Sets.newHashSet(catalog.list(FeatureTypeInfo.class, filter)); assertEquals(expected, actual); @@ -3203,9 +3076,7 @@ void testListPredicateExtended() { List values = new ArrayList<>(); values.add("ft1"); values.add("ft2"); - filter = - factory.equal( - factory.literal(values), factory.property("name"), true, MatchAction.ANY); + filter = factory.equal(factory.literal(values), factory.property("name"), true, MatchAction.ANY); expected = Sets.newHashSet(ft1, ft2); actual = Sets.newHashSet(catalog.list(FeatureTypeInfo.class, filter)); assertEquals(expected, actual); @@ -3213,9 +3084,7 @@ void testListPredicateExtended() { values = new ArrayList<>(); values.add("ft1"); values.add("ft1"); - filter = - factory.equal( - factory.literal(values), factory.property("name"), true, MatchAction.ALL); + filter = factory.equal(factory.literal(values), factory.property("name"), true, MatchAction.ALL); expected = Sets.newHashSet(ft1); actual = Sets.newHashSet(catalog.list(FeatureTypeInfo.class, filter)); assertEquals(expected, actual); @@ -3223,9 +3092,7 @@ void testListPredicateExtended() { values = new ArrayList<>(); values.add("ft1"); values.add("ft2"); - filter = - factory.equal( - factory.literal(values), factory.property("name"), true, MatchAction.ALL); + filter = factory.equal(factory.literal(values), factory.property("name"), true, MatchAction.ALL); expected = Sets.newHashSet(); actual = Sets.newHashSet(catalog.list(FeatureTypeInfo.class, filter)); assertEquals(expected, actual); @@ -3234,9 +3101,7 @@ void testListPredicateExtended() { values.add("ft1"); values.add("ft1"); values.add("ft2"); - filter = - factory.equal( - factory.literal(values), factory.property("name"), true, MatchAction.ONE); + filter = factory.equal(factory.literal(values), factory.property("name"), true, MatchAction.ONE); expected = Sets.newHashSet(ft2); actual = Sets.newHashSet(catalog.list(FeatureTypeInfo.class, filter)); assertEquals(expected, actual); @@ -3246,12 +3111,7 @@ void testListPredicateExtended() { values = new ArrayList<>(); values.add(new Keyword("keyword1")); values.add(new Keyword("keyword2")); - filter = - factory.equal( - factory.literal(values), - factory.property("keywords"), - true, - MatchAction.ANY); + filter = factory.equal(factory.literal(values), factory.property("keywords"), true, MatchAction.ANY); expected = Sets.newHashSet(ft1, ft2); actual = Sets.newHashSet(catalog.list(FeatureTypeInfo.class, filter)); assertEquals(expected, actual); @@ -3259,12 +3119,7 @@ void testListPredicateExtended() { values = new ArrayList<>(); values.add(new Keyword("keyword1")); values.add(new Keyword("keyword1")); - filter = - factory.equal( - factory.literal(values), - factory.property("keywords"), - true, - MatchAction.ALL); + filter = factory.equal(factory.literal(values), factory.property("keywords"), true, MatchAction.ALL); expected = Sets.newHashSet(ft2); actual = Sets.newHashSet(catalog.list(FeatureTypeInfo.class, filter)); assertEquals(expected, actual); @@ -3272,12 +3127,7 @@ void testListPredicateExtended() { values = new ArrayList<>(); values.add(new Keyword("keyword1")); values.add(new Keyword("blah")); - filter = - factory.equal( - factory.literal(values), - factory.property("keywords"), - true, - MatchAction.ONE); + filter = factory.equal(factory.literal(values), factory.property("keywords"), true, MatchAction.ONE); expected = Sets.newHashSet(ft1); actual = Sets.newHashSet(catalog.list(FeatureTypeInfo.class, filter)); assertEquals(expected, actual); @@ -3356,12 +3206,7 @@ void testOrderBy() { } private void testOrderBy( - Class clazz, - Filter filter, - Integer offset, - Integer limit, - SortBy sortOrder, - List expected) { + Class clazz, Filter filter, Integer offset, Integer limit, SortBy sortOrder, List expected) { CatalogPropertyAccessor pe = new CatalogPropertyAccessor(); @@ -3407,35 +3252,26 @@ void testFullTextSearch() { catalog.add(l2); Filter filter = Predicates.fullTextSearch("Description"); - assertEquals( - newHashSet(data.featureTypeA, data.coverageA), - asSet(catalog.list(ResourceInfo.class, filter))); + assertEquals(newHashSet(data.featureTypeA, data.coverageA), asSet(catalog.list(ResourceInfo.class, filter))); assertEquals(2, catalog.count(ResourceInfo.class, filter)); assertEquals(1, catalog.count(CoverageInfo.class, filter)); - assertEquals( - newHashSet(data.featureTypeA), asSet(catalog.list(FeatureTypeInfo.class, filter))); + assertEquals(newHashSet(data.featureTypeA), asSet(catalog.list(FeatureTypeInfo.class, filter))); assertEquals(newHashSet(data.coverageA), asSet(catalog.list(CoverageInfo.class, filter))); - assertEquals( - newHashSet(data.layerFeatureTypeA, l2), - asSet(catalog.list(LayerInfo.class, filter))); + assertEquals(newHashSet(data.layerFeatureTypeA, l2), asSet(catalog.list(LayerInfo.class, filter))); filter = Predicates.fullTextSearch("opensource"); - assertEquals( - newHashSet(data.layerFeatureTypeA), asSet(catalog.list(LayerInfo.class, filter))); + assertEquals(newHashSet(data.layerFeatureTypeA), asSet(catalog.list(LayerInfo.class, filter))); filter = Predicates.fullTextSearch("geotools"); assertEquals(newHashSet(l2), asSet(catalog.list(LayerInfo.class, filter))); filter = Predicates.fullTextSearch("Global"); - assertEquals( - newHashSet(data.layerFeatureTypeA, l2), - asSet(catalog.list(LayerInfo.class, filter))); + assertEquals(newHashSet(data.layerFeatureTypeA, l2), asSet(catalog.list(LayerInfo.class, filter))); filter = Predicates.fullTextSearch("Temperature"); - assertEquals( - newHashSet(data.layerFeatureTypeA), asSet(catalog.list(LayerInfo.class, filter))); + assertEquals(newHashSet(data.layerFeatureTypeA), asSet(catalog.list(LayerInfo.class, filter))); filter = Predicates.fullTextSearch("Depression"); assertEquals(newHashSet(l2), asSet(catalog.list(LayerInfo.class, filter))); @@ -3450,8 +3286,7 @@ void testFullTextSearchLayerGroupTitle() { // test layer group title and abstract search Filter filter = Predicates.fullTextSearch("title"); - assertEquals( - newHashSet(data.layerGroup1), asSet(catalog.list(LayerGroupInfo.class, filter))); + assertEquals(newHashSet(data.layerGroup1), asSet(catalog.list(LayerGroupInfo.class, filter))); } @Test @@ -3460,8 +3295,7 @@ void testFullTextSearchLayerGroupName() { // geos-6882 catalog.add(data.layerGroup1); Filter filter = Predicates.fullTextSearch("Group"); - assertEquals( - newHashSet(data.layerGroup1), asSet(catalog.list(LayerGroupInfo.class, filter))); + assertEquals(newHashSet(data.layerGroup1), asSet(catalog.list(LayerGroupInfo.class, filter))); } @Test @@ -3470,8 +3304,7 @@ void testFullTextSearchLayerGroupAbstract() { data.layerGroup1.setAbstract("GeoServer OpenSource GIS"); catalog.add(data.layerGroup1); Filter filter = Predicates.fullTextSearch("geoserver"); - assertEquals( - newHashSet(data.layerGroup1), asSet(catalog.list(LayerGroupInfo.class, filter))); + assertEquals(newHashSet(data.layerGroup1), asSet(catalog.list(LayerGroupInfo.class, filter))); } @Test @@ -3489,23 +3322,15 @@ void testFullTextSearchKeywords() { catalog.add(l2); Filter filter = Predicates.fullTextSearch("temperature"); - assertEquals( - newHashSet(data.layerFeatureTypeA, l2), - asSet(catalog.list(LayerInfo.class, filter))); - assertEquals( - newHashSet(data.featureTypeA, data.coverageA), - asSet(catalog.list(ResourceInfo.class, filter))); - assertEquals( - newHashSet(data.featureTypeA), asSet(catalog.list(FeatureTypeInfo.class, filter))); + assertEquals(newHashSet(data.layerFeatureTypeA, l2), asSet(catalog.list(LayerInfo.class, filter))); + assertEquals(newHashSet(data.featureTypeA, data.coverageA), asSet(catalog.list(ResourceInfo.class, filter))); + assertEquals(newHashSet(data.featureTypeA), asSet(catalog.list(FeatureTypeInfo.class, filter))); assertEquals(newHashSet(data.coverageA), asSet(catalog.list(CoverageInfo.class, filter))); filter = Predicates.fullTextSearch("air"); - assertEquals( - newHashSet(data.layerFeatureTypeA), asSet(catalog.list(LayerInfo.class, filter))); - assertEquals( - newHashSet(data.featureTypeA), asSet(catalog.list(ResourceInfo.class, filter))); - assertEquals( - newHashSet(data.featureTypeA), asSet(catalog.list(FeatureTypeInfo.class, filter))); + assertEquals(newHashSet(data.layerFeatureTypeA), asSet(catalog.list(LayerInfo.class, filter))); + assertEquals(newHashSet(data.featureTypeA), asSet(catalog.list(ResourceInfo.class, filter))); + assertEquals(newHashSet(data.featureTypeA), asSet(catalog.list(FeatureTypeInfo.class, filter))); assertEquals(newHashSet(), asSet(catalog.list(CoverageInfo.class, filter))); filter = Predicates.fullTextSearch("dewpoint"); @@ -3550,8 +3375,7 @@ private Set asSet(CloseableIterator list) { return set; } - protected LayerInfo newLayer( - ResourceInfo resource, StyleInfo defStyle, StyleInfo... extraStyles) { + protected LayerInfo newLayer(ResourceInfo resource, StyleInfo defStyle, StyleInfo... extraStyles) { LayerInfo l2 = catalog.getFactory().createLayer(); l2.setResource(resource); l2.setDefaultStyle(defStyle); @@ -3589,8 +3413,7 @@ void testConcurrentCatalogModification() throws InterruptedException, ExecutionE try { // disable logging for this test, it will stay a while in case of failure otherwise logger.setLevel(Level.OFF); - ExecutorCompletionService completionService = - new ExecutorCompletionService<>(executor); + ExecutorCompletionService completionService = new ExecutorCompletionService<>(executor); for (int i = 0; i < tasks; i++) { completionService.submit( () -> { @@ -3609,8 +3432,7 @@ void testConcurrentCatalogModification() throws InterruptedException, ExecutionE for (TestListener testListener : listeners) { assertTrue( testListener.removed.stream() - .anyMatch( - event -> event.getSource() == catalogInfo), + .anyMatch(event -> event.getSource() == catalogInfo), "Did not find the expected even in the listener"); } @@ -3681,36 +3503,30 @@ void testIterablesHaveCatalogSet() { stores.forEachRemaining(s -> assertSame(catalog, s.getCatalog())); } { - CloseableIterator resources = - catalog.list(ResourceInfo.class, acceptAll()); + CloseableIterator resources = catalog.list(ResourceInfo.class, acceptAll()); assertTrue(resources.hasNext()); resources.forEachRemaining(r -> assertSame(catalog, r.getCatalog())); } { CloseableIterator layers = catalog.list(LayerInfo.class, acceptAll()); assertTrue(layers.hasNext()); - layers.forEachRemaining( - r -> { - assertSame(catalog, r.getResource().getCatalog()); - assertSame(catalog, r.getResource().getStore().getCatalog()); - }); + layers.forEachRemaining(r -> { + assertSame(catalog, r.getResource().getCatalog()); + assertSame(catalog, r.getResource().getStore().getCatalog()); + }); } { - CloseableIterator groups = - catalog.list(LayerGroupInfo.class, acceptAll()); + CloseableIterator groups = catalog.list(LayerGroupInfo.class, acceptAll()); assertTrue(groups.hasNext()); - groups.forEachRemaining( - g -> { - List layers = g.getLayers(); - layers.forEach( - p -> { - if (p instanceof LayerInfo l) { - assertSame(catalog, l.getResource().getCatalog()); - assertSame( - catalog, l.getResource().getStore().getCatalog()); - } - }); - }); + groups.forEachRemaining(g -> { + List layers = g.getLayers(); + layers.forEach(p -> { + if (p instanceof LayerInfo l) { + assertSame(catalog, l.getResource().getCatalog()); + assertSame(catalog, l.getResource().getStore().getCatalog()); + } + }); + }); } } @@ -3748,8 +3564,7 @@ void testCountIdFilter() { assertEquals(1, catalog.count(StoreInfo.class, equal("id", data.dataStoreB.getId()))); assertEquals(1, catalog.count(DataStoreInfo.class, equal("id", data.dataStoreB.getId()))); - assertEquals( - 0, catalog.count(CoverageStoreInfo.class, equal("id", data.dataStoreB.getId()))); + assertEquals(0, catalog.count(CoverageStoreInfo.class, equal("id", data.dataStoreB.getId()))); } @Test @@ -3771,8 +3586,7 @@ void testListPublishedInfos() { assertEquals(5, catalog.getLayers().size()); assertEquals(5, catalog.getLayerGroups().size()); - testListPublishedInfos( - acceptAll(), null, null, List.of(l1, g1, l2, g2, l3, g3, l4, g4, l5, g5)); + testListPublishedInfos(acceptAll(), null, null, List.of(l1, g1, l2, g2, l3, g3, l4, g4, l5, g5)); testListPublishedInfos(acceptAll(), 3, 4, List.of(g2, l3, g3, l4)); testListPublishedInfos(acceptAll(), 8, 4, List.of(l5, g5)); @@ -3788,12 +3602,12 @@ void testListPublishedInfos() { } // sorts by name - private void testListPublishedInfos( - Filter filter, Integer offset, Integer limit, List expected) { + private void testListPublishedInfos(Filter filter, Integer offset, Integer limit, List expected) { List result = listPublishedInfos(filter, offset, limit); assertEquals(expected.size(), result.size()); - List expectedNames = expected.stream().map(PublishedInfo::getName).toList(); + List expectedNames = + expected.stream().map(PublishedInfo::getName).toList(); List actualNames = result.stream().map(PublishedInfo::getName).toList(); assertEquals(expectedNames, actualNames); diff --git a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/CatalogFacadeExtensionAdapterTest.java b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/CatalogFacadeExtensionAdapterTest.java index 12820e8e8..39eb347b5 100644 --- a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/CatalogFacadeExtensionAdapterTest.java +++ b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/CatalogFacadeExtensionAdapterTest.java @@ -9,6 +9,7 @@ import static org.junit.jupiter.api.Assertions.assertNotSame; import static org.junit.jupiter.api.Assertions.assertSame; +import java.io.File; import org.geoserver.catalog.CatalogFacade; import org.geoserver.catalog.impl.DefaultCatalogFacade; import org.geoserver.catalog.plugin.CatalogFacadeExtensionAdapter.SilentCatalog; @@ -16,8 +17,6 @@ import org.geoserver.platform.GeoServerResourceLoader; import org.junit.jupiter.api.Test; -import java.io.File; - /** * Asserts that a {@link CatalogFacadeExtensionAdapter} does not result in double publishing of * catalog events, and that {@link CatalogFacadeExtensionAdapter#update} correctly forwards to @@ -43,13 +42,11 @@ void testCatalogDecoratesLegacyFacade() { catalog.setFacade(legacyFacade); assertSame(legacyFacade, catalog.getRawFacade()); assertThat(catalog.getFacade(), instanceOf(ResolvingCatalogFacadeDecorator.class)); - ResolvingCatalogFacadeDecorator resolving = - (ResolvingCatalogFacadeDecorator) catalog.getFacade(); + ResolvingCatalogFacadeDecorator resolving = (ResolvingCatalogFacadeDecorator) catalog.getFacade(); assertThat(resolving.getSubject(), instanceOf(IsolatedCatalogFacade.class)); IsolatedCatalogFacade isolated = (IsolatedCatalogFacade) resolving.getSubject(); assertThat(isolated.getSubject(), instanceOf(CatalogFacadeExtensionAdapter.class)); - CatalogFacadeExtensionAdapter adapter = - (CatalogFacadeExtensionAdapter) isolated.getSubject(); + CatalogFacadeExtensionAdapter adapter = (CatalogFacadeExtensionAdapter) isolated.getSubject(); assertSame(legacyFacade, adapter.getSubject()); } @@ -59,8 +56,7 @@ void testProvidedDecorator() { catalog.setFacade(adapter); assertSame(adapter, catalog.getRawFacade()); assertThat(catalog.getFacade(), instanceOf(ResolvingCatalogFacadeDecorator.class)); - ResolvingCatalogFacadeDecorator resolving = - (ResolvingCatalogFacadeDecorator) catalog.getFacade(); + ResolvingCatalogFacadeDecorator resolving = (ResolvingCatalogFacadeDecorator) catalog.getFacade(); IsolatedCatalogFacade isolated = (IsolatedCatalogFacade) resolving.getSubject(); assertSame(adapter, isolated.getSubject()); } @@ -71,16 +67,12 @@ void testAdapterReplacesLegacyCatalogFacadeCatalog() { assertSame(legacyFacade, adapter.getSubject()); assertNotSame(catalog, legacyFacade.getCatalog()); - assertThat( - legacyFacade.getCatalog(), - instanceOf(CatalogFacadeExtensionAdapter.SilentCatalog.class)); + assertThat(legacyFacade.getCatalog(), instanceOf(CatalogFacadeExtensionAdapter.SilentCatalog.class)); SilentCatalog decoratorAtFacadeConstructor = (SilentCatalog) legacyFacade.getCatalog(); catalog.setFacade(adapter); assertSame(adapter, catalog.getRawFacade()); - assertThat( - legacyFacade.getCatalog(), - instanceOf(CatalogFacadeExtensionAdapter.SilentCatalog.class)); + assertThat(legacyFacade.getCatalog(), instanceOf(CatalogFacadeExtensionAdapter.SilentCatalog.class)); assertNotSame(decoratorAtFacadeConstructor, legacyFacade.getCatalog()); } } diff --git a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/CatalogPluginConformanceTest.java b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/CatalogPluginConformanceTest.java index f7a46070b..28dca34e7 100644 --- a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/CatalogPluginConformanceTest.java +++ b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/CatalogPluginConformanceTest.java @@ -4,9 +4,8 @@ */ package org.geoserver.catalog.plugin; -import org.geoserver.platform.GeoServerResourceLoader; - import java.io.File; +import org.geoserver.platform.GeoServerResourceLoader; class CatalogPluginConformanceTest extends CatalogConformanceTest { diff --git a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/NamespaceInfoLookupTest.java b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/NamespaceInfoLookupTest.java index d6d7b2a43..f0414b7d8 100644 --- a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/NamespaceInfoLookupTest.java +++ b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/NamespaceInfoLookupTest.java @@ -9,14 +9,13 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.util.List; import org.geoserver.catalog.NamespaceInfo; import org.geoserver.catalog.impl.NamespaceInfoImpl; import org.geoserver.catalog.plugin.CatalogInfoLookup.NamespaceInfoLookup; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.List; - /** Test suite for {@link NamespaceInfoLookup} */ class NamespaceInfoLookupTest { diff --git a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/PropertyDiffTest.java b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/PropertyDiffTest.java index ef8c36ed7..d36e39a81 100644 --- a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/PropertyDiffTest.java +++ b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/PropertyDiffTest.java @@ -4,14 +4,19 @@ */ package org.geoserver.catalog.plugin; +import static java.util.Collections.singletonList; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -import static java.util.Collections.singletonList; - +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogTestData; import org.geoserver.catalog.MetadataMap; @@ -23,13 +28,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Date; -import java.util.HashMap; -import java.util.HashSet; - class PropertyDiffTest { private PropertyDiffTestSupport support = new PropertyDiffTestSupport(); @@ -37,7 +35,9 @@ class PropertyDiffTest { public @BeforeEach void setup() { Catalog catalog = new CatalogPlugin(); - data = CatalogTestData.empty(() -> catalog, () -> null).initConfig(false).initialize(); + data = CatalogTestData.empty(() -> catalog, () -> null) + .initConfig(false) + .initialize(); } @Test @@ -60,30 +60,29 @@ void simpleStringProp() { @Test void cleanToEmpty() { - PropertyDiff diff = - support.createTestDiff( // - "leftListNull", - null, - new ArrayList<>(), // - "rightListNull", - new ArrayList<>(), - null, // - "bothListsEmpty", - new ArrayList<>(), - new ArrayList<>(), // - "bothListsEqual", - singletonList("val"), - singletonList("val"), // - "leftMapNull", - null, - new HashMap<>(), // - "rightMapNull", - new HashMap<>(), - null, // - "bothMapsEmpty", - new HashMap<>(), - new HashMap<>() // - ); + PropertyDiff diff = support.createTestDiff( // + "leftListNull", + null, + new ArrayList<>(), // + "rightListNull", + new ArrayList<>(), + null, // + "bothListsEmpty", + new ArrayList<>(), + new ArrayList<>(), // + "bothListsEqual", + singletonList("val"), + singletonList("val"), // + "leftMapNull", + null, + new HashMap<>(), // + "rightMapNull", + new HashMap<>(), + null, // + "bothMapsEmpty", + new HashMap<>(), + new HashMap<>() // + ); assertEquals(7, diff.size()); PropertyDiff clean = diff.clean(); assertTrue(clean.isEmpty()); @@ -93,21 +92,20 @@ void cleanToEmpty() { @Test void cleanToEmpty_InternationalString() { - PropertyDiff diff = - support.createTestDiff( // - "leftListNull", - null, - new SimpleInternationalString(""), // - "rightListNull", - new SimpleInternationalString(""), // - null, // - "bothEmpty", - new SimpleInternationalString(""), // - new GrowableInternationalString(), // - "bothEmpty2", - new GrowableInternationalString(), // - new SimpleInternationalString("") // - ); + PropertyDiff diff = support.createTestDiff( // + "leftListNull", + null, + new SimpleInternationalString(""), // + "rightListNull", + new SimpleInternationalString(""), // + null, // + "bothEmpty", + new SimpleInternationalString(""), // + new GrowableInternationalString(), // + "bothEmpty2", + new GrowableInternationalString(), // + new SimpleInternationalString("") // + ); PropertyDiff clean = diff.clean(); assertTrue(clean.isEmpty()); @@ -117,20 +115,19 @@ void cleanToEmpty_InternationalString() { @Test void clean() { - PropertyDiff diff = - support.createTestDiff( // - "prop1", - null, - new ArrayList<>(), // - "prop2", - new HashMap<>(), - null, // - "prop3", - new HashSet<>(), - new HashSet(Arrays.asList("val1", "val2")), // - "prop4", - "val1", - Integer.valueOf(2)); + PropertyDiff diff = support.createTestDiff( // + "prop1", + null, + new ArrayList<>(), // + "prop2", + new HashMap<>(), + null, // + "prop3", + new HashSet<>(), + new HashSet(Arrays.asList("val1", "val2")), // + "prop4", + "val1", + Integer.valueOf(2)); assertEquals(4, diff.size()); PropertyDiff clean = diff.clean(); @@ -153,13 +150,12 @@ void builderToEmpty() { WorkspaceInfo ws = data.workspaceA; ws.setDateCreated(new Date()); - PropertyDiff diff = - PropertyDiff.builder(ws) - .with("name", ws.getName()) - .with("isolated", ws.isIsolated()) - .with("dateCreated", ws.getDateCreated()) - .with("dateModified", ws.getDateModified()) - .build(); + PropertyDiff diff = PropertyDiff.builder(ws) + .with("name", ws.getName()) + .with("isolated", ws.isIsolated()) + .with("dateCreated", ws.getDateCreated()) + .with("dateModified", ws.getDateModified()) + .build(); assertEquals(4, diff.size()); assertTrue(diff.clean().isEmpty()); } @@ -185,14 +181,13 @@ void applyWorkspace() { metadata.put("k1", "v1"); metadata.put("k2", Long.MAX_VALUE); - diff = - PropertyDiff.builder(ws) - .with("name", "newname2") - .with("isolated", true) - .with("dateCreated", created) - .with("dateModified", modified) - .with("metadata", metadata) - .build(); + diff = PropertyDiff.builder(ws) + .with("name", "newname2") + .with("isolated", true) + .with("dateCreated", created) + .with("dateModified", modified) + .with("metadata", metadata) + .build(); diff.toPatch().applyTo(copy); diff --git a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/XmlCatalogInfoLookup.java b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/XmlCatalogInfoLookup.java index 254aaa555..ff175d1da 100644 --- a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/XmlCatalogInfoLookup.java +++ b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/XmlCatalogInfoLookup.java @@ -5,7 +5,20 @@ package org.geoserver.catalog.plugin; import com.google.common.collect.Ordering; - +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.lang.reflect.Proxy; +import java.nio.charset.StandardCharsets; +import java.util.Comparator; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.function.Predicate; +import java.util.logging.Logger; +import java.util.stream.Stream; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.DataStoreInfo; import org.geoserver.catalog.Info; @@ -25,21 +38,6 @@ import org.geotools.api.filter.sort.SortOrder; import org.geotools.util.logging.Logging; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.lang.reflect.Proxy; -import java.nio.charset.StandardCharsets; -import java.util.Comparator; -import java.util.NoSuchElementException; -import java.util.Optional; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; -import java.util.function.Predicate; -import java.util.logging.Logger; -import java.util.stream.Stream; - /** * Exemplar alternative implementations of {@link CatalogInfoRepository} that store serialized * string versions of {@link CatalogInfo} objects in memory, to validate the API and showcase the @@ -73,8 +71,7 @@ static final Predicate alwaysTrue() { private static void checkNotAProxy(CatalogInfo value) { if (Proxy.isProxyClass(value.getClass())) { - throw new IllegalArgumentException( - "Proxy values shall not be passed to CatalogInfoLookup"); + throw new IllegalArgumentException("Proxy values shall not be passed to CatalogInfoLookup"); } } @@ -92,8 +89,7 @@ protected I deserialize(String serialized, Class type) { if (serialized == null) return null; I loaded; try { - ByteArrayInputStream in = - new ByteArrayInputStream(serialized.getBytes(StandardCharsets.UTF_8)); + ByteArrayInputStream in = new ByteArrayInputStream(serialized.getBytes(StandardCharsets.UTF_8)); loaded = codec.load(in, type); } catch (IOException e) { throw new UncheckedIOException(e); @@ -112,9 +108,8 @@ public void add(T value) { String serialized = serialize(value); if (null != idMap.putIfAbsent(value.getId(), serialized)) { - String msg = - "%s:%s already exists, not replaced" - .formatted(getContentType().getSimpleName(), value.getId()); + String msg = "%s:%s already exists, not replaced" + .formatted(getContentType().getSimpleName(), value.getId()); LOGGER.warning(msg); } } @@ -134,15 +129,9 @@ public I update(final I value, Patch patch) { @SuppressWarnings("unchecked") Class type = (Class) ClassMappings.fromImpl(value.getClass()).getInterface(); synchronized (idMap) { - storedValue = - this.findById(value.getId(), type) - .orElseThrow( - () -> - new NoSuchElementException( - "%s with id %s does not exist" - .formatted( - type.getSimpleName(), - value.getId()))); + storedValue = this.findById(value.getId(), type) + .orElseThrow(() -> new NoSuchElementException( + "%s with id %s does not exist".formatted(type.getSimpleName(), value.getId()))); patch.applyTo(storedValue); idMap.put(value.getId(), serialize(storedValue)); @@ -188,9 +177,7 @@ public static Comparator toComparator(Query query) Comparator comparator = providedOrder(); for (SortBy sortBy : query.getSortBy()) { comparator = - (comparator == PROVIDED_ORDER) - ? comparator(sortBy) - : comparator.thenComparing(comparator(sortBy)); + (comparator == PROVIDED_ORDER) ? comparator(sortBy) : comparator.thenComparing(comparator(sortBy)); } return comparator; } @@ -205,36 +192,34 @@ protected Predicate toPredicate(Filter filter) { } private static Comparator comparator(final SortBy sortOrder) { - Comparator comparator = - new Comparator<>() { - @Override - public int compare(U o1, U o2) { - Object v1 = OwsUtils.get(o1, sortOrder.getPropertyName().getPropertyName()); - Object v2 = OwsUtils.get(o2, sortOrder.getPropertyName().getPropertyName()); - if (v1 == null) { - if (v2 == null) { - return 0; - } else { - return -1; - } - } else if (v2 == null) { - return 1; - } - @SuppressWarnings({"rawtypes", "unchecked"}) - Comparable c1 = (Comparable) v1; - @SuppressWarnings({"rawtypes", "unchecked"}) - Comparable c2 = (Comparable) v2; - return c1.compareTo(c2); + Comparator comparator = new Comparator<>() { + @Override + public int compare(U o1, U o2) { + Object v1 = OwsUtils.get(o1, sortOrder.getPropertyName().getPropertyName()); + Object v2 = OwsUtils.get(o2, sortOrder.getPropertyName().getPropertyName()); + if (v1 == null) { + if (v2 == null) { + return 0; + } else { + return -1; } - }; + } else if (v2 == null) { + return 1; + } + @SuppressWarnings({"rawtypes", "unchecked"}) + Comparable c1 = (Comparable) v1; + @SuppressWarnings({"rawtypes", "unchecked"}) + Comparable c2 = (Comparable) v2; + return c1.compareTo(c2); + } + }; if (SortOrder.DESCENDING.equals(sortOrder.getSortOrder())) { comparator = comparator.reversed(); } return comparator; } - Stream list( - Class clazz, Predicate predicate, Comparator comparator) { + Stream list(Class clazz, Predicate predicate, Comparator comparator) { Stream stream = all().filter(clazz::isInstance).map(clazz::cast).filter(predicate); if (comparator != CatalogInfoLookup.PROVIDED_ORDER) { @@ -247,8 +232,7 @@ Stream list( @Override public Optional findById(String id, Class clazz) { T deserialized = deserialize(idMap.get(id)); - return Optional.ofNullable( - clazz.isInstance(deserialized) ? clazz.cast(deserialized) : null); + return Optional.ofNullable(clazz.isInstance(deserialized) ? clazz.cast(deserialized) : null); } Optional findFirst(Class clazz, Predicate predicate) { @@ -260,8 +244,7 @@ public void syncTo(CatalogInfoRepository target) { all().forEach(target::add); } - public static class NamespaceInfoLookup extends XmlCatalogInfoLookup - implements NamespaceRepository { + public static class NamespaceInfoLookup extends XmlCatalogInfoLookup implements NamespaceRepository { public NamespaceInfoLookup(XStreamPersister codec) { super(codec); @@ -271,17 +254,14 @@ public NamespaceInfoLookup(XStreamPersister codec) { @Override public void setDefaultNamespace(NamespaceInfo namespace) { - this.defaultNamespaceId = - findById(namespace.getId(), NamespaceInfo.class) - .map(NamespaceInfo::getId) - .orElseThrow(NoSuchElementException::new); + this.defaultNamespaceId = findById(namespace.getId(), NamespaceInfo.class) + .map(NamespaceInfo::getId) + .orElseThrow(NoSuchElementException::new); } @Override public Optional getDefaultNamespace() { - return defaultNamespaceId == null - ? Optional.empty() - : findById(defaultNamespaceId, NamespaceInfo.class); + return defaultNamespaceId == null ? Optional.empty() : findById(defaultNamespaceId, NamespaceInfo.class); } @Override @@ -310,8 +290,7 @@ public Optional findFirstByName(String name, Class< } } - public static class WorkspaceInfoLookup extends XmlCatalogInfoLookup - implements WorkspaceRepository { + public static class WorkspaceInfoLookup extends XmlCatalogInfoLookup implements WorkspaceRepository { public WorkspaceInfoLookup(XStreamPersister codec) { super(codec); @@ -322,8 +301,7 @@ public WorkspaceInfoLookup(XStreamPersister codec) { @Override public void setDefaultWorkspace(WorkspaceInfo workspace) { this.defaultWorkspace = - findById(workspace.getId(), WorkspaceInfo.class) - .orElseThrow(NoSuchElementException::new); + findById(workspace.getId(), WorkspaceInfo.class).orElseThrow(NoSuchElementException::new); } @Override @@ -347,8 +325,7 @@ public Optional findFirstByName(String name, Class< } } - public static class StoreInfoLookup extends XmlCatalogInfoLookup - implements StoreRepository { + public static class StoreInfoLookup extends XmlCatalogInfoLookup implements StoreRepository { public StoreInfoLookup(XStreamPersister codec) { super(codec); @@ -361,8 +338,7 @@ public StoreInfoLookup(XStreamPersister codec) { public void setDefaultDataStore(WorkspaceInfo workspace, DataStoreInfo store) { String wsId = workspace.getId(); final DataStoreInfo localStore = - super.findById(store.getId(), DataStoreInfo.class) - .orElseThrow(NoSuchElementException::new); + super.findById(store.getId(), DataStoreInfo.class).orElseThrow(NoSuchElementException::new); defaultStores.put(wsId, localStore.getId()); } @@ -389,8 +365,7 @@ public void dispose() { } @Override - public Stream findAllByWorkspace( - WorkspaceInfo workspace, Class clazz) { + public Stream findAllByWorkspace(WorkspaceInfo workspace, Class clazz) { return all().filter(clazz::isInstance) .map(clazz::cast) @@ -440,20 +415,19 @@ public Stream findAllByWorkspaceIsNull() { @Override public Stream findAllByWorkspace(WorkspaceInfo workspace) { Predicate predicate = - lg -> - lg.getWorkspace() != null - && lg.getWorkspace().getId().equals(workspace.getId()); + lg -> lg.getWorkspace() != null && lg.getWorkspace().getId().equals(workspace.getId()); return all().filter(predicate); } @Override public Optional findByNameAndWorkspaceIsNull(String name) { - return findAllByWorkspaceIsNull().filter(lg -> lg.getName().equals(name)).findFirst(); + return findAllByWorkspaceIsNull() + .filter(lg -> lg.getName().equals(name)) + .findFirst(); } @Override - public Optional findByNameAndWorkspace( - String name, WorkspaceInfo workspace) { + public Optional findByNameAndWorkspace(String name, WorkspaceInfo workspace) { return findAllByWorkspace(workspace) .filter(lg -> lg.getName().equals(name)) .findFirst(); @@ -473,8 +447,7 @@ public Optional findFirstByName(String name, Class } } - public static class MapInfoLookup extends XmlCatalogInfoLookup - implements MapRepository { + public static class MapInfoLookup extends XmlCatalogInfoLookup implements MapRepository { protected MapInfoLookup(XStreamPersister codec) { super(codec); @@ -494,8 +467,7 @@ public Optional findFirstByName(String name, Class cla } } - public static class ResourceInfoLookup extends XmlCatalogInfoLookup - implements ResourceRepository { + public static class ResourceInfoLookup extends XmlCatalogInfoLookup implements ResourceRepository { protected ResourceInfoLookup(XStreamPersister codec) { super(codec); @@ -507,17 +479,17 @@ public Stream findAllByType(Class clazz) { } @Override - public Stream findAllByNamespace( - NamespaceInfo ns, Class clazz) { + public Stream findAllByNamespace(NamespaceInfo ns, Class clazz) { return allOf(clazz).filter(r -> ns.getId().equals(r.getNamespace().getId())); } @Override - public Optional findByStoreAndName( - StoreInfo store, String name, Class clazz) { + public Optional findByStoreAndName(StoreInfo store, String name, Class clazz) { - return findAllByStore(store, clazz).filter(r -> name.equals(r.getName())).findFirst(); + return findAllByStore(store, clazz) + .filter(r -> name.equals(r.getName())) + .findFirst(); } @Override @@ -549,8 +521,7 @@ public Optional findFirstByName(String name, Class - implements LayerRepository { + public static class LayerInfoLookup extends XmlCatalogInfoLookup implements LayerRepository { public LayerInfoLookup(XStreamPersister codec) { super(codec); @@ -564,13 +535,9 @@ public Optional findOneByName(String name) { @Override public Stream findAllByDefaultStyleOrStyles(StyleInfo style) { String id = style.getId(); - Predicate predicate = - li -> - (li.getDefaultStyle() != null - && id.equals(li.getDefaultStyle().getId())) - || li.getStyles().stream() - .map(s -> s.getId()) - .anyMatch(id::equals); + Predicate predicate = li -> (li.getDefaultStyle() != null + && id.equals(li.getDefaultStyle().getId())) + || li.getStyles().stream().map(s -> s.getId()).anyMatch(id::equals); return all().filter(predicate); } @@ -592,8 +559,7 @@ public Optional findFirstByName(String name, Class c } } - public static class StyleInfoLookup extends XmlCatalogInfoLookup - implements StyleRepository { + public static class StyleInfoLookup extends XmlCatalogInfoLookup implements StyleRepository { public StyleInfoLookup(XStreamPersister codec) { super(codec); @@ -612,13 +578,17 @@ public Stream findAllByWorkspace(WorkspaceInfo ws) { @Override public Optional findByNameAndWordkspaceNull(String name) { - return findAllByNullWorkspace().filter(s -> s.getName().equals(name)).findFirst(); + return findAllByNullWorkspace() + .filter(s -> s.getName().equals(name)) + .findFirst(); } @Override public Optional findByNameAndWorkspace(String name, WorkspaceInfo workspace) { - return findAllByWorkspace(workspace).filter(s -> s.getName().equals(name)).findFirst(); + return findAllByWorkspace(workspace) + .filter(s -> s.getName().equals(name)) + .findFirst(); } @Override diff --git a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/XmlCatalogInfoLookupConformanceTest.java b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/XmlCatalogInfoLookupConformanceTest.java index 721429756..15af82977 100644 --- a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/XmlCatalogInfoLookupConformanceTest.java +++ b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/XmlCatalogInfoLookupConformanceTest.java @@ -4,6 +4,8 @@ */ package org.geoserver.catalog.plugin; +import java.io.File; +import java.util.function.UnaryOperator; import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.plugin.forwarding.ResolvingCatalogFacadeDecorator; import org.geoserver.catalog.plugin.resolving.CatalogPropertyResolver; @@ -14,9 +16,6 @@ import org.geoserver.platform.GeoServerResourceLoader; import org.junit.jupiter.api.Disabled; -import java.io.File; -import java.util.function.UnaryOperator; - class XmlCatalogInfoLookupConformanceTest extends CatalogConformanceTest { @Override @@ -39,11 +38,9 @@ protected CatalogPlugin createCatalog(File tmpFolder) { ResolvingCatalogFacadeDecorator resolving = new ResolvingCatalogFacadeDecorator(rawFacade); - UnaryOperator chainedResolver = - CatalogPropertyResolver.of(catalog) // - .andThen(ResolvingProxyResolver.of(catalog)) // - .andThen(CollectionPropertiesInitializer.instance()) - ::apply; + UnaryOperator chainedResolver = CatalogPropertyResolver.of(catalog) // + .andThen(ResolvingProxyResolver.of(catalog)) // + .andThen(CollectionPropertiesInitializer.instance())::apply; resolving.setOutboundResolver(chainedResolver); catalog.setFacade(resolving); catalog.setResourceLoader(new GeoServerResourceLoader(tmpFolder)); @@ -59,8 +56,7 @@ protected CatalogPlugin createCatalog(File tmpFolder) { @Override public void testSaveDataStoreRollbacksBothStoreAndResources() {} - @Disabled( - "don't care it can't save the resourceinfo when saving a layer, it's just a demo implementation") + @Disabled("don't care it can't save the resourceinfo when saving a layer, it's just a demo implementation") @Override public void testEnableLayer() {} } diff --git a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/locking/LockProviderGeoServerConfigurationLockTest.java b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/locking/LockProviderGeoServerConfigurationLockTest.java index 8c40a5b41..3684676bd 100644 --- a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/locking/LockProviderGeoServerConfigurationLockTest.java +++ b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/locking/LockProviderGeoServerConfigurationLockTest.java @@ -14,6 +14,10 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.io.File; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; import org.geoserver.GeoServerConfigurationLock.LockType; import org.geoserver.platform.resource.FileLockProvider; import org.geoserver.platform.resource.LockProvider; @@ -23,17 +27,13 @@ import org.junit.jupiter.api.Timeout; import org.junit.jupiter.api.io.TempDir; -import java.io.File; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; - /** * @since 1.0 */ class LockProviderGeoServerConfigurationLockTest { - @TempDir File mockDataDir; + @TempDir + File mockDataDir; private LockProviderGeoServerConfigurationLock lock; @@ -78,10 +78,7 @@ void testLock_ReadLock_preserves_write_lock_if_alread_held() { assertEquals(WRITE, lock.getCurrentLock()); lock.lock(READ); - assertEquals( - WRITE, - lock.getCurrentLock(), - "A read lock request shall preserve the write lock if already held"); + assertEquals(WRITE, lock.getCurrentLock(), "A read lock request shall preserve the write lock if already held"); lock.unlock(); } @@ -115,22 +112,17 @@ void testTryUpgradeLock() throws InterruptedException, ExecutionException { lock.lock(READ); secondThread - .submit( - () -> { - assertTrue(lock.tryLock(READ)); - }) + .submit(() -> { + assertTrue(lock.tryLock(READ)); + }) .get(); assertEquals(READ, lock.getCurrentLock()); RuntimeException ex = assertThrows(RuntimeException.class, () -> lock.tryUpgradeLock()); - assertThat( - ex.getMessage(), - containsString("Failed to upgrade lock from read to write state")); + assertThat(ex.getMessage(), containsString("Failed to upgrade lock from read to write state")); - assertNull( - lock.getCurrentLock(), - "lock should have been lost after a failed tryUpgradeLock()"); + assertNull(lock.getCurrentLock(), "lock should have been lost after a failed tryUpgradeLock()"); lock.lock(READ); @@ -180,9 +172,7 @@ void testTryLock_true_if_read_lock_requested_while_holding_a_write_lock() { assertTrue(lock.tryLock(READ)); assertEquals( - WRITE, - lock.getCurrentLock(), - "tryLock(READ) while holding a write lock shall preserve the write lock"); + WRITE, lock.getCurrentLock(), "tryLock(READ) while holding a write lock shall preserve the write lock"); lock.unlock(); assertNull(lock.getCurrentLock()); @@ -231,10 +221,7 @@ private void testLockIsReentrant(LockType lockType) { } finally { // first release lock.unlock(); - assertEquals( - lockType, - lock.getCurrentLock(), - "%s lock should still be held".formatted(lockType)); + assertEquals(lockType, lock.getCurrentLock(), "%s lock should still be held".formatted(lockType)); } } finally { // second release @@ -270,10 +257,7 @@ private void testTryLockIsReentrant(final LockType lockType) { } finally { // first release lock.unlock(); - assertEquals( - lockType, - lock.getCurrentLock(), - "%s lock should still be held".formatted(lockType)); + assertEquals(lockType, lock.getCurrentLock(), "%s lock should still be held".formatted(lockType)); } } finally { // second release diff --git a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/locking/LockingCatalogDataDirectoryTest.java b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/locking/LockingCatalogDataDirectoryTest.java index b8a98dc48..00f5e73fc 100644 --- a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/locking/LockingCatalogDataDirectoryTest.java +++ b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/locking/LockingCatalogDataDirectoryTest.java @@ -4,6 +4,7 @@ */ package org.geoserver.catalog.plugin.locking; +import java.io.File; import org.geoserver.GeoServerConfigurationLock; import org.geoserver.platform.resource.FileLockProvider; import org.geoserver.platform.resource.LockProvider; @@ -11,14 +12,13 @@ import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.io.TempDir; -import java.io.File; - /** * @since 1.0 */ class LockingCatalogDataDirectoryTest extends LockingCatalogTest { - @TempDir File tmpDir; + @TempDir + File tmpDir; static @BeforeAll void beforeAll() { System.setProperty("CONFIGURATION_TRYLOCK_TIMEOUT", "100"); diff --git a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/locking/LockingCatalogTest.java b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/locking/LockingCatalogTest.java index 0b268b9a3..3480476d7 100644 --- a/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/locking/LockingCatalogTest.java +++ b/src/catalog/plugin/src/test/java/org/geoserver/catalog/plugin/locking/LockingCatalogTest.java @@ -9,6 +9,12 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNull; +import java.util.Date; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.IntStream; +import java.util.stream.Stream; import org.geoserver.GeoServerConfigurationLock; import org.geoserver.GeoServerConfigurationLock.LockType; import org.geoserver.catalog.CascadeDeleteVisitor; @@ -26,13 +32,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.Date; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.IntStream; -import java.util.stream.Stream; - /** * @since 1.0 */ @@ -83,8 +82,10 @@ void testConfigLockIsReentrant() { @Test void simpleMultiThreadTest() { - List workspaces = - IntStream.range(0, 100).parallel().mapToObj(i -> faker.workspaceInfo()).toList(); + List workspaces = IntStream.range(0, 100) + .parallel() + .mapToObj(i -> faker.workspaceInfo()) + .toList(); workspaces.stream().forEach(catalog::add); @@ -96,18 +97,16 @@ void simpleMultiThreadTest() { @Test void preAcquiredLockMultiThreadTest() { - List workspaces = - IntStream.range(0, 100) - .parallel() - .mapToObj(i -> faker.workspaceInfo("ws-" + i)) - .toList(); - - List> created = - workspaces // - .stream() // - .parallel() // - .map(this::batchCreateSubTree) - .toList(); + List workspaces = IntStream.range(0, 100) + .parallel() + .mapToObj(i -> faker.workspaceInfo("ws-" + i)) + .toList(); + + List> created = workspaces // + .stream() // + .parallel() // + .map(this::batchCreateSubTree) + .toList(); assertNotNull(catalog.getDefaultWorkspace()); @@ -123,16 +122,13 @@ void preAcquiredLockMultiThreadTest() { .parallel() // .forEach(this::batchUpdate); - Stream> updated = - created // - .stream() - .map( - list -> - list.stream() - .map(CatalogInfo::getId) - .map(catalog::findById) - .map(Optional::orElseThrow) - .toList()); + Stream> updated = created // + .stream() + .map(list -> list.stream() + .map(CatalogInfo::getId) + .map(catalog::findById) + .map(Optional::orElseThrow) + .toList()); updated // .parallel() // @@ -167,8 +163,7 @@ else if (info instanceof StyleInfo s) { catalog.save(info); } } finally { - assertEquals( - LockType.WRITE, configLock.getCurrentLock(), "lock should have been upgraded"); + assertEquals(LockType.WRITE, configLock.getCurrentLock(), "lock should have been upgraded"); configLock.unlock(); } } @@ -176,20 +171,18 @@ else if (info instanceof StyleInfo s) { private void batchDelete(List infos) { configLock.lock(LockType.WRITE); try { - WorkspaceInfo ws = - infos.stream() - .filter(WorkspaceInfo.class::isInstance) - .map(WorkspaceInfo.class::cast) - .findFirst() - .orElseThrow(); + WorkspaceInfo ws = infos.stream() + .filter(WorkspaceInfo.class::isInstance) + .map(WorkspaceInfo.class::cast) + .findFirst() + .orElseThrow(); CascadeDeleteVisitor cascadeDeleteVisitor = new CascadeDeleteVisitor(catalog); ws.accept(cascadeDeleteVisitor); infos.stream().forEach(catalog::remove); } finally { - assertEquals( - LockType.WRITE, configLock.getCurrentLock(), "lock should have been upgraded"); + assertEquals(LockType.WRITE, configLock.getCurrentLock(), "lock should have been upgraded"); configLock.unlock(); } } @@ -221,8 +214,7 @@ private List batchCreateSubTree(WorkspaceInfo workspace) { return List.of(workspace, namespace, ds, ft, style, layer); } finally { - assertEquals( - LockType.WRITE, configLock.getCurrentLock(), "lock should have been upgraded"); + assertEquals(LockType.WRITE, configLock.getCurrentLock(), "lock should have been upgraded"); configLock.unlock(); } } diff --git a/src/catalog/plugin/src/test/java/org/geoserver/cloud/test/ApplicationEventCapturingListener.java b/src/catalog/plugin/src/test/java/org/geoserver/cloud/test/ApplicationEventCapturingListener.java index b93d13e4d..1249312fb 100644 --- a/src/catalog/plugin/src/test/java/org/geoserver/cloud/test/ApplicationEventCapturingListener.java +++ b/src/catalog/plugin/src/test/java/org/geoserver/cloud/test/ApplicationEventCapturingListener.java @@ -7,13 +7,12 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -import org.springframework.context.ApplicationEvent; -import org.springframework.context.event.EventListener; -import org.springframework.stereotype.Component; - import java.util.ArrayList; import java.util.List; import java.util.Optional; +import org.springframework.context.ApplicationEvent; +import org.springframework.context.event.EventListener; +import org.springframework.stereotype.Component; @Component public class ApplicationEventCapturingListener { @@ -53,7 +52,8 @@ public ApplicationEventCapturingListener restart() { } public Optional firstAndRemove(Class type) { - Optional first = captured.stream().filter(type::isInstance).map(type::cast).findFirst(); + Optional first = + captured.stream().filter(type::isInstance).map(type::cast).findFirst(); if (first.isPresent()) { assertTrue(captured.remove(first.get())); } diff --git a/src/catalog/plugin/src/test/java/org/geoserver/config/GeoServerConfigConformanceTest.java b/src/catalog/plugin/src/test/java/org/geoserver/config/GeoServerConfigConformanceTest.java index c3c1c8b9f..368fecfda 100644 --- a/src/catalog/plugin/src/test/java/org/geoserver/config/GeoServerConfigConformanceTest.java +++ b/src/catalog/plugin/src/test/java/org/geoserver/config/GeoServerConfigConformanceTest.java @@ -18,6 +18,12 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; +import java.lang.reflect.Proxy; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.config.impl.GeoServerImpl; import org.geoserver.config.impl.GeoServerInfoImpl; @@ -26,13 +32,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.lang.reflect.Proxy; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - public abstract class GeoServerConfigConformanceTest { protected GeoServer geoServer; @@ -173,10 +172,7 @@ static class TestListener extends ConfigurationListenerAdapter { @Override public void handleGlobalChange( - GeoServerInfo global, - List propertyNames, - List oldValues, - List newValues) { + GeoServerInfo global, List propertyNames, List oldValues, List newValues) { gPropertyNames.addAll(propertyNames); gOldValues.addAll(oldValues); gNewValues.addAll(newValues); @@ -184,10 +180,7 @@ public void handleGlobalChange( @Override public void handleServiceChange( - ServiceInfo service, - List propertyNames, - List oldValues, - List newValues) { + ServiceInfo service, List propertyNames, List oldValues, List newValues) { sPropertyNames.addAll(propertyNames); sOldValues.addAll(oldValues); @@ -300,9 +293,7 @@ void testServiceWithWorkspace() { newService2 = geoServer.getService(newService2.getId(), ServiceInfo.class); // Check that we get the services we expect to - assertThat( - geoServer.getServiceByName(globalService.getName(), ServiceInfo.class), - equalTo(globalService)); + assertThat(geoServer.getServiceByName(globalService.getName(), ServiceInfo.class), equalTo(globalService)); assertThat(geoServer.getService(ws1, ServiceInfo.class), equalTo(newService1)); assertThat(geoServer.getService(ws2, ServiceInfo.class), equalTo(newService2)); assertThat( diff --git a/src/catalog/plugin/src/test/java/org/geoserver/config/impl/CatalogImplConformanceTest.java b/src/catalog/plugin/src/test/java/org/geoserver/config/impl/CatalogImplConformanceTest.java index 1a6800421..8b4661a3c 100644 --- a/src/catalog/plugin/src/test/java/org/geoserver/config/impl/CatalogImplConformanceTest.java +++ b/src/catalog/plugin/src/test/java/org/geoserver/config/impl/CatalogImplConformanceTest.java @@ -4,14 +4,13 @@ */ package org.geoserver.config.impl; +import java.io.File; import org.geoserver.catalog.impl.CatalogImpl; import org.geoserver.catalog.impl.DefaultCatalogFacade; import org.geoserver.catalog.plugin.CatalogConformanceTest; import org.geoserver.config.GeoServerResourcePersister; import org.geoserver.platform.GeoServerResourceLoader; -import java.io.File; - /** * {@link CatalogConformanceTest} for the traditional {@link CatalogImpl} with {@link * DefaultCatalogFacade} diff --git a/src/catalog/plugin/src/test/java/org/geoserver/config/plugin/XmlSerializedConfigRepository.java b/src/catalog/plugin/src/test/java/org/geoserver/config/plugin/XmlSerializedConfigRepository.java index 9df0d67ea..53090f718 100644 --- a/src/catalog/plugin/src/test/java/org/geoserver/config/plugin/XmlSerializedConfigRepository.java +++ b/src/catalog/plugin/src/test/java/org/geoserver/config/plugin/XmlSerializedConfigRepository.java @@ -4,16 +4,6 @@ */ package org.geoserver.config.plugin; -import org.geoserver.catalog.Info; -import org.geoserver.catalog.WorkspaceInfo; -import org.geoserver.catalog.plugin.Patch; -import org.geoserver.config.GeoServerInfo; -import org.geoserver.config.LoggingInfo; -import org.geoserver.config.ServiceInfo; -import org.geoserver.config.SettingsInfo; -import org.geoserver.config.util.XStreamPersister; -import org.geoserver.ows.util.OwsUtils; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -24,6 +14,15 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.stream.Stream; +import org.geoserver.catalog.Info; +import org.geoserver.catalog.WorkspaceInfo; +import org.geoserver.catalog.plugin.Patch; +import org.geoserver.config.GeoServerInfo; +import org.geoserver.config.LoggingInfo; +import org.geoserver.config.ServiceInfo; +import org.geoserver.config.SettingsInfo; +import org.geoserver.config.util.XStreamPersister; +import org.geoserver.ows.util.OwsUtils; /** * Example {@link ConfigRepository} alternative that serializes to XML using {@link @@ -56,8 +55,7 @@ private I deserialize(String serialized, Class type) { if (serialized == null) return null; I loaded; try { - ByteArrayInputStream in = - new ByteArrayInputStream(serialized.getBytes(StandardCharsets.UTF_8)); + ByteArrayInputStream in = new ByteArrayInputStream(serialized.getBytes(StandardCharsets.UTF_8)); loaded = codec.load(in, type); } catch (IOException e) { throw new UncheckedIOException(e); @@ -81,8 +79,7 @@ public Optional getGlobal() { private static void checkNotAProxy(Info value) { if (Proxy.isProxyClass(value.getClass())) { - throw new IllegalArgumentException( - "Proxy values shall not be passed to DefaultConfigRepository"); + throw new IllegalArgumentException("Proxy values shall not be passed to DefaultConfigRepository"); } } @@ -189,8 +186,7 @@ public Optional getGlobalService(Class clazz) { } @Override - public Optional getServiceByWorkspace( - WorkspaceInfo workspace, Class clazz) { + public Optional getServiceByWorkspace(WorkspaceInfo workspace, Class clazz) { return getServicesByWorkspace(workspace) .filter(clazz::isInstance) diff --git a/src/catalog/plugin/src/test/java/org/geoserver/platform/config/UpdateSequenceConformanceTest.java b/src/catalog/plugin/src/test/java/org/geoserver/platform/config/UpdateSequenceConformanceTest.java index 23d8c38cf..71c02a3c7 100644 --- a/src/catalog/plugin/src/test/java/org/geoserver/platform/config/UpdateSequenceConformanceTest.java +++ b/src/catalog/plugin/src/test/java/org/geoserver/platform/config/UpdateSequenceConformanceTest.java @@ -6,11 +6,10 @@ import static org.junit.jupiter.api.Assertions.assertEquals; +import java.util.stream.IntStream; import org.geoserver.config.GeoServer; import org.junit.jupiter.api.Test; -import java.util.stream.IntStream; - /** * @since 1.2 */ diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnAzureBlobstoreEnabled.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnAzureBlobstoreEnabled.java index a407b1fa4..956672242 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnAzureBlobstoreEnabled.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnAzureBlobstoreEnabled.java @@ -4,17 +4,16 @@ */ package org.geoserver.cloud.autoconfigure.gwc; -import org.geoserver.cloud.gwc.config.blobstore.AzureBlobstoreConfiguration; -import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; -import org.geowebcache.azure.AzureBlobStoreConfigProvider; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.geoserver.cloud.gwc.config.blobstore.AzureBlobstoreConfiguration; +import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; +import org.geowebcache.azure.AzureBlobStoreConfigProvider; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; /** * Conditionals: diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnDirectWMSIntegrationEnabled.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnDirectWMSIntegrationEnabled.java index c60082369..27410f5fc 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnDirectWMSIntegrationEnabled.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnDirectWMSIntegrationEnabled.java @@ -4,14 +4,13 @@ */ package org.geoserver.cloud.autoconfigure.gwc; -import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; /** * @since 1.0 diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnDiskQuotaEnabled.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnDiskQuotaEnabled.java index bb19724b6..1922df405 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnDiskQuotaEnabled.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnDiskQuotaEnabled.java @@ -4,16 +4,15 @@ */ package org.geoserver.cloud.autoconfigure.gwc; -import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; -import org.geowebcache.diskquota.DiskQuotaConfig; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; +import org.geowebcache.diskquota.DiskQuotaConfig; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; /** * Disk Quota conditional, disabled by default diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnGeoServerWebUIEnabled.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnGeoServerWebUIEnabled.java index 0d322c771..30d2ae19c 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnGeoServerWebUIEnabled.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnGeoServerWebUIEnabled.java @@ -4,15 +4,14 @@ */ package org.geoserver.cloud.autoconfigure.gwc; -import org.geoserver.gwc.web.GWCSettingsPage; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.geoserver.gwc.web.GWCSettingsPage; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; /** * Conditionals: diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnGeoWebCacheEnabled.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnGeoWebCacheEnabled.java index dd03ce65e..0f538c17d 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnGeoWebCacheEnabled.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnGeoWebCacheEnabled.java @@ -4,16 +4,15 @@ */ package org.geoserver.cloud.autoconfigure.gwc; -import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; -import org.geoserver.gwc.GWC; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; +import org.geoserver.gwc.GWC; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnGeoWebCacheRestConfigEnabled.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnGeoWebCacheRestConfigEnabled.java index 95b1e8a2c..125ca6536 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnGeoWebCacheRestConfigEnabled.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnGeoWebCacheRestConfigEnabled.java @@ -4,15 +4,14 @@ */ package org.geoserver.cloud.autoconfigure.gwc; -import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.METHOD, ElementType.TYPE}) diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnS3BlobstoreEnabled.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnS3BlobstoreEnabled.java index d650d9785..e18812eca 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnS3BlobstoreEnabled.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnS3BlobstoreEnabled.java @@ -4,17 +4,16 @@ */ package org.geoserver.cloud.autoconfigure.gwc; -import org.geoserver.cloud.gwc.config.blobstore.S3BlobstoreGsWebUIConfiguration; -import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; -import org.geowebcache.s3.S3BlobStoreConfigProvider; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.geoserver.cloud.gwc.config.blobstore.S3BlobstoreGsWebUIConfiguration; +import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; +import org.geowebcache.s3.S3BlobStoreConfigProvider; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; /** * Conditionals: diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnWMTSIntegrationEnabled.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnWMTSIntegrationEnabled.java index 65cb2cb56..d8181224d 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnWMTSIntegrationEnabled.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnWMTSIntegrationEnabled.java @@ -4,14 +4,13 @@ */ package org.geoserver.cloud.autoconfigure.gwc; -import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; /** * Conditionals: diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnWebUIEnabled.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnWebUIEnabled.java index 4979a1fcf..cb8cea2a1 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnWebUIEnabled.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/ConditionalOnWebUIEnabled.java @@ -4,14 +4,13 @@ */ package org.geoserver.cloud.autoconfigure.gwc; -import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; /** * Conditionals: diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/GoServerWebUIConfigurationProperties.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/GoServerWebUIConfigurationProperties.java index 4d089fed5..6af41a64f 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/GoServerWebUIConfigurationProperties.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/GoServerWebUIConfigurationProperties.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.autoconfigure.gwc; import lombok.Data; - import org.springframework.boot.context.properties.ConfigurationProperties; /** diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/backend/DefaultTileLayerCatalogAutoConfiguration.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/backend/DefaultTileLayerCatalogAutoConfiguration.java index 6b22dccf5..985ffe2d3 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/backend/DefaultTileLayerCatalogAutoConfiguration.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/backend/DefaultTileLayerCatalogAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.gwc.backend; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.autoconfigure.gwc.ConditionalOnGeoWebCacheEnabled; import org.geoserver.cloud.gwc.config.core.DefaultTileLayerCatalogConfiguration; import org.geoserver.cloud.gwc.repository.GeoServerTileLayerConfiguration; @@ -15,8 +15,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Import; -import javax.annotation.PostConstruct; - /** * {@link AutoConfiguration @AutoConfiguration} to set up the GeoServer {@link TileLayerCatalog} * using the default implementation based on the {@link ResourceStore}. diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/backend/PgconfigGwcInitializer.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/backend/PgconfigGwcInitializer.java index af2fe4681..aa8eddb36 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/backend/PgconfigGwcInitializer.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/backend/PgconfigGwcInitializer.java @@ -6,7 +6,6 @@ import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.GeoServerConfigurationLock; import org.geoserver.cloud.gwc.backend.pgconfig.PgconfigTileLayerCatalog; import org.geoserver.cloud.gwc.event.TileLayerEvent; diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/backend/PgconfigTileLayerCatalogAutoConfiguration.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/backend/PgconfigTileLayerCatalogAutoConfiguration.java index 4d3560bf9..09b7a4331 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/backend/PgconfigTileLayerCatalogAutoConfiguration.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/backend/PgconfigTileLayerCatalogAutoConfiguration.java @@ -4,9 +4,13 @@ */ package org.geoserver.cloud.autoconfigure.gwc.backend; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Consumer; +import javax.annotation.PostConstruct; +import javax.sql.DataSource; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.GeoServerConfigurationLock; import org.geoserver.catalog.Catalog; import org.geoserver.cloud.autoconfigure.catalog.backend.pgconfig.ConditionalOnPgconfigBackendEnabled; @@ -32,13 +36,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.jdbc.core.JdbcTemplate; -import java.util.Objects; -import java.util.Optional; -import java.util.function.Consumer; - -import javax.annotation.PostConstruct; -import javax.sql.DataSource; - /** * {@link AutoConfiguration @AutoConfiguration} to set up the GeoServer {@link TileLayerCatalog} * using the "pgconfig" module implementation to store the tile layer configuration as part of the @@ -87,15 +84,13 @@ GeoServerTileLayerConfiguration pgconfigTileLayerCatalog( @Bean TileLayerInfoRepository pgconfigTileLayerRepository( - @Qualifier("pgconfigDataSource") DataSource dataSource, - Optional cacheManager) { + @Qualifier("pgconfigDataSource") DataSource dataSource, Optional cacheManager) { var pgrepo = new PgconfigTileLayerInfoRepository(new JdbcTemplate(dataSource)); return cacheManager.map(cm -> cachingTileLayerCatalog(pgrepo, cm)).orElse(pgrepo); } - TileLayerInfoRepository cachingTileLayerCatalog( - TileLayerInfoRepository delegate, CacheManager cacheManager) { + TileLayerInfoRepository cachingTileLayerCatalog(TileLayerInfoRepository delegate, CacheManager cacheManager) { log.info( "GeoWebCache Caching TileLayerInfoRepository enabled. Repository: {}, CacheManager: {}", diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/blobstore/AzureBlobstoreAutoConfiguration.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/blobstore/AzureBlobstoreAutoConfiguration.java index 492918dd4..fc98e24ff 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/blobstore/AzureBlobstoreAutoConfiguration.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/blobstore/AzureBlobstoreAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.gwc.blobstore; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.autoconfigure.gwc.ConditionalOnAzureBlobstoreEnabled; import org.geoserver.cloud.autoconfigure.gwc.ConditionalOnGeoServerWebUIEnabled; import org.geoserver.cloud.autoconfigure.gwc.blobstore.S3BlobstoreAutoConfiguration.GsWebUIAutoConfiguration; @@ -17,8 +17,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import javax.annotation.PostConstruct; - /** * @see ConditionalOnAzureBlobstoreEnabled * @since 1.0 diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/blobstore/S3BlobstoreAutoConfiguration.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/blobstore/S3BlobstoreAutoConfiguration.java index 9a20aa305..8e30a8bc2 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/blobstore/S3BlobstoreAutoConfiguration.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/blobstore/S3BlobstoreAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.gwc.blobstore; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.autoconfigure.gwc.ConditionalOnGeoServerWebUIEnabled; import org.geoserver.cloud.autoconfigure.gwc.ConditionalOnS3BlobstoreEnabled; import org.geoserver.cloud.autoconfigure.gwc.blobstore.S3BlobstoreAutoConfiguration.GsWebUIAutoConfiguration; @@ -17,8 +17,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import javax.annotation.PostConstruct; - /** * @since 1.0 */ diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/core/CacheSeedingWebMapServiceAutoConfiguration.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/core/CacheSeedingWebMapServiceAutoConfiguration.java index e686037c2..69cb383ac 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/core/CacheSeedingWebMapServiceAutoConfiguration.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/core/CacheSeedingWebMapServiceAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.gwc.core; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.autoconfigure.gwc.ConditionalOnGeoWebCacheEnabled; import org.geoserver.cloud.autoconfigure.gwc.core.CacheSeedingWebMapServiceAutoConfiguration.MinimalWebMapServiceAutoConfiguration; import org.geoserver.cloud.gwc.config.core.WebMapServiceCacheSeedingConfiguration; @@ -19,8 +19,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import javax.annotation.PostConstruct; - /** * {@link EnableAutoConfiguration Auto configuration} to make sure a minimal {@link WebMapService} * and the GeoWebCache-specific decorator exist, as expected by {@link GeoServerTileLayer#seedTile}. diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/core/GeoServerIntegrationAutoConfiguration.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/core/GeoServerIntegrationAutoConfiguration.java index 379fa5281..67d639c46 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/core/GeoServerIntegrationAutoConfiguration.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/core/GeoServerIntegrationAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.gwc.core; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.autoconfigure.gwc.ConditionalOnGeoWebCacheEnabled; import org.geoserver.cloud.autoconfigure.gwc.backend.DefaultTileLayerCatalogAutoConfiguration; import org.geoserver.cloud.gwc.config.core.GeoServerIntegrationConfiguration; @@ -13,8 +13,6 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.Import; -import javax.annotation.PostConstruct; - /** * {@link EnableAutoConfiguration Auto-Configuration} to integrated GeoServer-specific GWC * extensions, for example, to being able of configuring tile layers out of GeoServer Layers. diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/core/GeoWebCacheCoreAutoConfiguration.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/core/GeoWebCacheCoreAutoConfiguration.java index f7cf5c58c..45ba342b6 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/core/GeoWebCacheCoreAutoConfiguration.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/core/GeoWebCacheCoreAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.gwc.core; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.autoconfigure.gwc.ConditionalOnGeoWebCacheEnabled; import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; import org.geoserver.cloud.gwc.config.core.GeoWebCacheCoreConfiguration; @@ -13,8 +13,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import javax.annotation.PostConstruct; - /** * This auto-configuration only integrates the minimal components to have gwc integrated with * GeoServer, while allowing to disable certain components through {@link diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/integration/GeoWebCacheRemoteEventsAutoConfiguration.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/integration/GeoWebCacheRemoteEventsAutoConfiguration.java index 23b8ecd3f..3e18b4b46 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/integration/GeoWebCacheRemoteEventsAutoConfiguration.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/integration/GeoWebCacheRemoteEventsAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.gwc.integration; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.autoconfigure.event.bus.ConditionalOnGeoServerRemoteEventsEnabled; import org.geoserver.cloud.autoconfigure.gwc.ConditionalOnGeoWebCacheEnabled; import org.geoserver.cloud.gwc.config.bus.GeoWebCacheRemoteEventsConfiguration; @@ -13,8 +13,6 @@ import org.springframework.cloud.bus.BusAutoConfiguration; import org.springframework.context.annotation.Import; -import javax.annotation.PostConstruct; - /** * @see GeoWebCacheRemoteEventsConfiguration * @see ConditionalOnGeoWebCacheEnabled diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/integration/WMSIntegrationAutoConfiguration.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/integration/WMSIntegrationAutoConfiguration.java index 5d20f49de..674f76fa3 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/integration/WMSIntegrationAutoConfiguration.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/integration/WMSIntegrationAutoConfiguration.java @@ -6,12 +6,15 @@ import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; - import static org.geowebcache.conveyor.Conveyor.CacheResult.MISS; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.nio.channels.Channels; +import java.util.LinkedHashMap; +import javax.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; - import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; @@ -44,13 +47,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.nio.channels.Channels; -import java.util.LinkedHashMap; - -import javax.servlet.http.HttpServletResponse; - /** * Autoconfiguration to integrate GWC with GeoServer's WMS * @@ -60,10 +56,7 @@ * @since 1.0 */ @AutoConfiguration -@Import({ - WMSIntegrationAutoConfiguration.Enabled.class, - WMSIntegrationAutoConfiguration.Disabled.class -}) +@Import({WMSIntegrationAutoConfiguration.Enabled.class, WMSIntegrationAutoConfiguration.Disabled.class}) @Slf4j(topic = "org.geoserver.cloud.autoconfigure.gwc.integration") public class WMSIntegrationAutoConfiguration { @@ -160,8 +153,7 @@ public WebMap getMap(ProceedingJoinPoint joinPoint) throws Throwable { if (cachedTile == null) { WebMap dynamicResult = (WebMap) joinPoint.proceed(); dynamicResult.setResponseHeader("geowebcache-cache-result", MISS.toString()); - dynamicResult.setResponseHeader( - "geowebcache-miss-reason", requestMistmatchTarget.toString()); + dynamicResult.setResponseHeader("geowebcache-miss-reason", requestMistmatchTarget.toString()); return dynamicResult; } checkState(cachedTile.getTileLayer() != null); @@ -190,8 +182,7 @@ public WebMap getMap(ProceedingJoinPoint joinPoint) throws Throwable { LinkedHashMap headers = new LinkedHashMap<>(); GWC.setCacheControlHeaders(headers, layer, (int) cachedTile.getTileIndex()[2]); - GWC.setConditionalGetHeaders( - headers, cachedTile, etag, request.getHttpRequestHeader("If-Modified-Since")); + GWC.setConditionalGetHeaders(headers, cachedTile, etag, request.getHttpRequestHeader("If-Modified-Since")); GWC.setCacheMetadataHeaders(headers, cachedTile, layer); headers.forEach(map::setResponseHeader); diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/integration/WMTSIntegrationAutoConfiguration.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/integration/WMTSIntegrationAutoConfiguration.java index 9e1d85f43..2067cf323 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/integration/WMTSIntegrationAutoConfiguration.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/integration/WMTSIntegrationAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.gwc.integration; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.autoconfigure.gwc.ConditionalOnWMTSIntegrationEnabled; import org.geoserver.cloud.config.factory.FilteringXmlBeanDefinitionReader; import org.geowebcache.service.wmts.WMTSService; @@ -13,8 +13,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.ImportResource; -import javax.annotation.PostConstruct; - /** * @since 1.0 */ diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/GoogleMapsAutoConfiguration.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/GoogleMapsAutoConfiguration.java index 358d1942d..f28831d61 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/GoogleMapsAutoConfiguration.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/GoogleMapsAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.gwc.service; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; import org.geoserver.cloud.gwc.config.services.GoogleMapsConfiguration; import org.springframework.boot.autoconfigure.AutoConfiguration; @@ -13,8 +13,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Import; -import javax.annotation.PostConstruct; - /** * @since 1.0 */ diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/KMLAutoConfiguration.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/KMLAutoConfiguration.java index ff360700a..8dc85c915 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/KMLAutoConfiguration.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/KMLAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.gwc.service; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; import org.geoserver.cloud.gwc.config.services.KMLConfiguration; import org.springframework.boot.autoconfigure.AutoConfiguration; @@ -13,8 +13,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Import; -import javax.annotation.PostConstruct; - /** * @since 1.0 */ diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/MGMapsAutoConfiguration.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/MGMapsAutoConfiguration.java index fbfd982e7..f88c4d612 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/MGMapsAutoConfiguration.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/MGMapsAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.gwc.service; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; import org.geoserver.cloud.gwc.config.services.MGMapsConfiguration; import org.springframework.boot.autoconfigure.AutoConfiguration; @@ -13,8 +13,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Import; -import javax.annotation.PostConstruct; - /** * @since 1.0 */ diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/RESTConfigAutoConfiguration.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/RESTConfigAutoConfiguration.java index 7e9911f5e..638a549de 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/RESTConfigAutoConfiguration.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/RESTConfigAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.gwc.service; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.autoconfigure.gwc.ConditionalOnGeoWebCacheRestConfigEnabled; import org.geoserver.cloud.autoconfigure.gwc.core.DiskQuotaAutoConfiguration; import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; @@ -14,8 +14,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Import; -import javax.annotation.PostConstruct; - /** * The original {@literal geowebcache-rest-context.xml}: * diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/TileMapServiceAutoConfiguration.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/TileMapServiceAutoConfiguration.java index 343bb2103..411a1460e 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/TileMapServiceAutoConfiguration.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/TileMapServiceAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.gwc.service; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; import org.geoserver.cloud.gwc.config.services.TileMapServiceConfiguration; import org.springframework.boot.autoconfigure.AutoConfiguration; @@ -13,8 +13,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Import; -import javax.annotation.PostConstruct; - /** * @since 1.0 */ diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/WebMapServiceAutoConfiguration.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/WebMapServiceAutoConfiguration.java index 766946464..3449896bf 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/WebMapServiceAutoConfiguration.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/WebMapServiceAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.gwc.service; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; import org.geoserver.cloud.gwc.config.services.WebMapServiceConfiguration; import org.springframework.boot.autoconfigure.AutoConfiguration; @@ -13,8 +13,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Import; -import javax.annotation.PostConstruct; - /** * @since 1.0 */ diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/WebMapTileServiceAutoConfiguration.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/WebMapTileServiceAutoConfiguration.java index 221b14a17..bf609964c 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/WebMapTileServiceAutoConfiguration.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/gwc/service/WebMapTileServiceAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.gwc.service; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; import org.geoserver.cloud.gwc.config.services.WebMapTileServiceConfiguration; import org.springframework.boot.autoconfigure.AutoConfiguration; @@ -13,8 +13,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Import; -import javax.annotation.PostConstruct; - /** * @since 1.0 */ diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/web/gwc/CloudGWCServiceDescriptionProvider.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/web/gwc/CloudGWCServiceDescriptionProvider.java index 9020fabab..0797504e7 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/web/gwc/CloudGWCServiceDescriptionProvider.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/web/gwc/CloudGWCServiceDescriptionProvider.java @@ -1,7 +1,8 @@ package org.geoserver.cloud.autoconfigure.web.gwc; +import java.util.ArrayList; +import java.util.List; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.PublishedInfo; import org.geoserver.catalog.WorkspaceInfo; import org.geoserver.cloud.autoconfigure.gwc.GoServerWebUIConfigurationProperties; @@ -17,9 +18,6 @@ import org.geoserver.web.ServiceLinkDescription; import org.geotools.util.Version; -import java.util.ArrayList; -import java.util.List; - /** * GeoServer-Cloud replacement of {@link GWCServiceDescriptionProvider} *

    @@ -121,8 +119,7 @@ private String basePath(WorkspaceInfo workspace, PublishedInfo layer) { private String createLinkWMSC(WorkspaceInfo workspace, PublishedInfo layer) { String basePath = basePath(workspace, layer); - return "%s/wms?service=WMS&version=1.1.1&request=GetCapabilities&tiled=true" - .formatted(basePath); + return "%s/wms?service=WMS&version=1.1.1&request=GetCapabilities&tiled=true".formatted(basePath); } private String createLinkWMTS(WorkspaceInfo workspace, PublishedInfo layer) { @@ -136,8 +133,7 @@ private String createLinkTMS(WorkspaceInfo workspace, PublishedInfo layer) { } @Override - public List getServiceLinks( - WorkspaceInfo workspaceInfo, PublishedInfo layerInfo) { + public List getServiceLinks(WorkspaceInfo workspaceInfo, PublishedInfo layerInfo) { if (workspaceInfo == null && !geoserver.getGlobal().isGlobalServices()) { return List.of(); @@ -183,7 +179,6 @@ public List getServiceLinks( private ServiceLinkDescription serviceLink( String workspaceName, String layerName, Version version, String protocol, String link) { - return new ServiceLinkDescription( - SERVICE_TYPE, version, link, workspaceName, layerName, protocol); + return new ServiceLinkDescription(SERVICE_TYPE, version, link, workspaceName, layerName, protocol); } } diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/web/gwc/GeoServerWebUIAutoConfiguration.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/web/gwc/GeoServerWebUIAutoConfiguration.java index 471ae64a5..0d90f0e40 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/web/gwc/GeoServerWebUIAutoConfiguration.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/web/gwc/GeoServerWebUIAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.web.gwc; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.autoconfigure.gwc.ConditionalOnGeoServerWebUIEnabled; import org.geoserver.cloud.autoconfigure.gwc.GoServerWebUIConfigurationProperties; import org.geoserver.cloud.config.factory.FilteringXmlBeanDefinitionReader; @@ -16,8 +16,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; -import javax.annotation.PostConstruct; - /** * Auto configuration to enabled GWC Wicket Web UI components. * diff --git a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/web/gwc/GeoWebCacheUIAutoConfiguration.java b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/web/gwc/GeoWebCacheUIAutoConfiguration.java index 39f5aee81..3bd0a077a 100644 --- a/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/web/gwc/GeoWebCacheUIAutoConfiguration.java +++ b/src/gwc/autoconfigure/src/main/java/org/geoserver/cloud/autoconfigure/web/gwc/GeoWebCacheUIAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.web.gwc; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.autoconfigure.gwc.ConditionalOnGeoWebCacheRestConfigEnabled; import org.geoserver.cloud.autoconfigure.gwc.ConditionalOnWebUIEnabled; import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; @@ -16,8 +16,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; -import javax.annotation.PostConstruct; - @AutoConfiguration @ConditionalOnWebUIEnabled @Slf4j(topic = "org.geoserver.cloud.autoconfigure.web.gwc") diff --git a/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/GeoWebCacheContextRunner.java b/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/GeoWebCacheContextRunner.java index 8c19d6554..0b7a559d4 100644 --- a/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/GeoWebCacheContextRunner.java +++ b/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/GeoWebCacheContextRunner.java @@ -6,6 +6,7 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.io.File; import org.geoserver.GeoServerConfigurationLock; import org.geoserver.catalog.plugin.CatalogPlugin; import org.geoserver.cloud.autoconfigure.gwc.backend.DefaultTileLayerCatalogAutoConfiguration; @@ -28,8 +29,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Primary; -import java.io.File; - /** * @since 1.0 */ @@ -42,12 +41,9 @@ public static WebApplicationContextRunner newMinimalGeoWebCacheContextRunner(Fil assertThat(gwcCacheDir).isDirectory().isWritable(); return newMinimalGeoServerContextRunner(tmpDir) - .withConfiguration( - AutoConfigurations.of( - GeoWebCacheAutoConfiguration.class, - DefaultTileLayerCatalogAutoConfiguration.class)) - .withPropertyValues( - "gwc.cache-directory=%s".formatted(gwcCacheDir.getAbsolutePath())); + .withConfiguration(AutoConfigurations.of( + GeoWebCacheAutoConfiguration.class, DefaultTileLayerCatalogAutoConfiguration.class)) + .withPropertyValues("gwc.cache-directory=%s".formatted(gwcCacheDir.getAbsolutePath())); } public static WebApplicationContextRunner newMinimalGeoServerContextRunner(File tmpDir) { @@ -56,8 +52,7 @@ public static WebApplicationContextRunner newMinimalGeoServerContextRunner(File .withAllowCircularReferences(true) // tmpDir for AddGeoServerDependenciesConfiguration .withBean("tempDir", File.class, () -> tmpDir) - .withConfiguration( - AutoConfigurations.of(AddGeoServerDependenciesConfiguration.class)) + .withConfiguration(AutoConfigurations.of(AddGeoServerDependenciesConfiguration.class)) .withBean("extensions", GeoServerExtensions.class) .withBean("environments", GeoServerEnvironment.class) .withBean("xstreamPersisterFactory", XStreamPersisterFactory.class) @@ -112,8 +107,7 @@ GeoServerDataDirectory geoServerDataDirectory(GeoServerResourceLoader resourceLo @Bean @ConditionalOnMissingBean - GeoServerSecurityManager geoServerSecurityManager(GeoServerDataDirectory datadir) - throws Exception { + GeoServerSecurityManager geoServerSecurityManager(GeoServerDataDirectory datadir) throws Exception { return new GeoServerSecurityManager(datadir); } } diff --git a/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/backend/GwcCoreAutoConfigurationTest.java b/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/backend/GwcCoreAutoConfigurationTest.java index ab7671a98..676c3308c 100644 --- a/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/backend/GwcCoreAutoConfigurationTest.java +++ b/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/backend/GwcCoreAutoConfigurationTest.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.autoconfigure.gwc.backend; import static com.github.stefanbirkner.systemlambda.SystemLambda.withEnvironmentVariable; - import static org.assertj.core.api.Assertions.assertThat; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.MatcherAssert.assertThat; @@ -14,7 +13,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.base.Throwables; - +import java.io.File; +import java.io.IOException; import org.geoserver.cloud.autoconfigure.gwc.GeoWebCacheContextRunner; import org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties; import org.geoserver.cloud.gwc.repository.CloudDefaultStorageFinder; @@ -27,15 +27,14 @@ import org.springframework.beans.factory.BeanInitializationException; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; -import java.io.File; -import java.io.IOException; - /** * @since 1.0 */ class GwcCoreAutoConfigurationTest { - @TempDir File tmpDir; + @TempDir + File tmpDir; + WebApplicationContextRunner runner; @BeforeEach @@ -66,35 +65,25 @@ void defaultCacheDirectoryIsAFile() throws IOException { @Test void contextLoads() { - runner.run( - context -> { - assertThat(context.isTypeMatch("gwcXmlConfig", CloudGwcXmlConfiguration.class)) - .isTrue(); - assertThat( - context.isTypeMatch( - "gwcXmlConfigResourceProvider", - CloudXMLResourceProvider.class)) - .isTrue(); - assertThat( - context.isTypeMatch( - "gwcDefaultStorageFinder", - CloudDefaultStorageFinder.class)) - .isTrue(); - }); + runner.run(context -> { + assertThat(context.isTypeMatch("gwcXmlConfig", CloudGwcXmlConfiguration.class)) + .isTrue(); + assertThat(context.isTypeMatch("gwcXmlConfigResourceProvider", CloudXMLResourceProvider.class)) + .isTrue(); + assertThat(context.isTypeMatch("gwcDefaultStorageFinder", CloudDefaultStorageFinder.class)) + .isTrue(); + }); } - protected void assertContextLoadFails( - Class expectedException, String expectedMessage) { - runner.run( - c -> { - Throwable startupFailure = c.getStartupFailure(); - assertNotNull(startupFailure); - Throwable root = Throwables.getRootCause(startupFailure); - if (!expectedException.isInstance(root)) root.printStackTrace(); - assertInstanceOf(expectedException, root); - if (null != expectedMessage) - assertThat(root.getMessage(), containsString(expectedMessage)); - }); + protected void assertContextLoadFails(Class expectedException, String expectedMessage) { + runner.run(c -> { + Throwable startupFailure = c.getStartupFailure(); + assertNotNull(startupFailure); + Throwable root = Throwables.getRootCause(startupFailure); + if (!expectedException.isInstance(root)) root.printStackTrace(); + assertInstanceOf(expectedException, root); + if (null != expectedMessage) assertThat(root.getMessage(), containsString(expectedMessage)); + }); } /** @@ -106,25 +95,17 @@ void defaultCacheDirectoryFromEnvVariable() throws Exception { File dir = new File(tmpDir, "env_cachedir"); assertThat(dir).doesNotExist(); String dirpath = dir.getAbsolutePath(); - withEnvironmentVariable("GEOWEBCACHE_CACHE_DIR", dirpath) - .execute( - () -> { - assertThat(System.getenv("GEOWEBCACHE_CACHE_DIR")).isEqualTo(dirpath); - runner.withPropertyValues( - "gwc.cache-directory: ${GEOWEBCACHE_CACHE_DIR}") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(dir).isDirectory(); - - var gwcConfigProps = - context.getBean( - GeoWebCacheConfigurationProperties - .class); - assertThat(gwcConfigProps.getCacheDirectory()) - .isEqualTo(dir.toPath()); - }); - }); + withEnvironmentVariable("GEOWEBCACHE_CACHE_DIR", dirpath).execute(() -> { + assertThat(System.getenv("GEOWEBCACHE_CACHE_DIR")).isEqualTo(dirpath); + runner.withPropertyValues("gwc.cache-directory: ${GEOWEBCACHE_CACHE_DIR}") + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(dir).isDirectory(); + + var gwcConfigProps = context.getBean(GeoWebCacheConfigurationProperties.class); + assertThat(gwcConfigProps.getCacheDirectory()).isEqualTo(dir.toPath()); + }); + }); assertThat(System.getenv("GEOWEBCACHE_CACHE_DIR")).isNull(); } @@ -137,11 +118,10 @@ void defaultCacheDirectoryFromSystemProperty() { System.setProperty("GEOWEBCACHE_CACHE_DIR", dirpath); try { runner.withPropertyValues("gwc.cache-directory: ${GEOWEBCACHE_CACHE_DIR}") - .run( - context -> { - assertThat(context).hasNotFailed(); - assertThat(dir).isDirectory(); - }); + .run(context -> { + assertThat(context).hasNotFailed(); + assertThat(dir).isDirectory(); + }); } finally { System.clearProperty("GEOWEBCACHE_CACHE_DIR"); } diff --git a/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/backend/PgconfigTileLayerCatalogAutoConfigurationTest.java b/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/backend/PgconfigTileLayerCatalogAutoConfigurationTest.java index 3ed41b1a6..086dba0c5 100644 --- a/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/backend/PgconfigTileLayerCatalogAutoConfigurationTest.java +++ b/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/backend/PgconfigTileLayerCatalogAutoConfigurationTest.java @@ -2,6 +2,7 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.io.File; import org.geoserver.cloud.autoconfigure.catalog.backend.pgconfig.ConditionalOnPgconfigBackendEnabled; import org.geoserver.cloud.autoconfigure.catalog.backend.pgconfig.PgconfigBackendAutoConfiguration; import org.geoserver.cloud.autoconfigure.catalog.backend.pgconfig.PgconfigDataSourceAutoConfiguration; @@ -34,28 +35,27 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import java.io.File; - /** GWC integration test for {@link PgconfigTileLayerCatalogAutoConfiguration} */ @Testcontainers(disabledWithoutDocker = true) class PgconfigTileLayerCatalogAutoConfigurationTest { - @Container static PgConfigTestContainer container = new PgConfigTestContainer<>(); + @Container + static PgConfigTestContainer container = new PgConfigTestContainer<>(); + + @TempDir + File cacheDir; - @TempDir File cacheDir; private WebApplicationContextRunner runner; @BeforeEach void setUp() { - runner = - GeoWebCacheContextRunner.newMinimalGeoWebCacheContextRunner(cacheDir) - .withConfiguration( - AutoConfigurations.of( - PgconfigTileLayerCatalogAutoConfiguration.class, - PgconfigBackendAutoConfiguration.class, - PgconfigDataSourceAutoConfiguration.class, - PgconfigTransactionManagerAutoConfiguration.class, - PgconfigMigrationAutoConfiguration.class)); + runner = GeoWebCacheContextRunner.newMinimalGeoWebCacheContextRunner(cacheDir) + .withConfiguration(AutoConfigurations.of( + PgconfigTileLayerCatalogAutoConfiguration.class, + PgconfigBackendAutoConfiguration.class, + PgconfigDataSourceAutoConfiguration.class, + PgconfigTransactionManagerAutoConfiguration.class, + PgconfigMigrationAutoConfiguration.class)); runner = container.setUp().withJdbcUrlConfig(runner); } @@ -72,41 +72,33 @@ void tearDown() { */ @Test void testPgconfigTileLayerCatalogReplacesDefaultTileLayerCatalogAutoConfiguration() { - runner.run( - context -> { - assertThat(context) - .doesNotHaveBean(GWCInitializer.class) - .hasSingleBean(PgconfigGwcInitializer.class); - - assertThat(context) - .hasNotFailed() - .hasBean("gwcCatalogConfiguration") - .getBean("gwcCatalogConfiguration", TileLayerConfiguration.class) - .isInstanceOf(GeoServerTileLayerConfiguration.class); - - assertThat( - context.getBean( - "gwcCatalogConfiguration", - GeoServerTileLayerConfiguration.class) - .getSubject()) - .isInstanceOf(PgconfigTileLayerCatalog.class); - - assertThat(context) - .getBean("gwcXmlConfig", XMLConfiguration.class) - .isInstanceOf(CloudGwcXmlConfiguration.class); - - assertThat(context) - .getBean( - "gwcXmlConfigResourceProvider", - ConfigurationResourceProvider.class) - .isInstanceOf(CloudXMLResourceProvider.class); - - assertThat(context) - .getBean("gwcDefaultStorageFinder", DefaultStorageFinder.class) - .isInstanceOf(CloudDefaultStorageFinder.class); - - assertDefaultTileLayerCatalogConfigurationAbsent(context); - }); + runner.run(context -> { + assertThat(context).doesNotHaveBean(GWCInitializer.class).hasSingleBean(PgconfigGwcInitializer.class); + + assertThat(context) + .hasNotFailed() + .hasBean("gwcCatalogConfiguration") + .getBean("gwcCatalogConfiguration", TileLayerConfiguration.class) + .isInstanceOf(GeoServerTileLayerConfiguration.class); + + assertThat(context.getBean("gwcCatalogConfiguration", GeoServerTileLayerConfiguration.class) + .getSubject()) + .isInstanceOf(PgconfigTileLayerCatalog.class); + + assertThat(context) + .getBean("gwcXmlConfig", XMLConfiguration.class) + .isInstanceOf(CloudGwcXmlConfiguration.class); + + assertThat(context) + .getBean("gwcXmlConfigResourceProvider", ConfigurationResourceProvider.class) + .isInstanceOf(CloudXMLResourceProvider.class); + + assertThat(context) + .getBean("gwcDefaultStorageFinder", DefaultStorageFinder.class) + .isInstanceOf(CloudDefaultStorageFinder.class); + + assertDefaultTileLayerCatalogConfigurationAbsent(context); + }); } /** @@ -116,13 +108,10 @@ void testPgconfigTileLayerCatalogReplacesDefaultTileLayerCatalogAutoConfiguratio @Test void conditionalOnClass_PgconfigTileLayerCatalog() { runner.withClassLoader(new FilteredClassLoader(PgconfigTileLayerCatalog.class)) - .run( - context -> { - assertThat(context) - .hasNotFailed() - .doesNotHaveBean(PgconfigTileLayerCatalog.class); - assertDefaultTileLayerCatalogConfigurationPresent(context); - }); + .run(context -> { + assertThat(context).hasNotFailed().doesNotHaveBean(PgconfigTileLayerCatalog.class); + assertDefaultTileLayerCatalogConfigurationPresent(context); + }); } /** @@ -132,14 +121,10 @@ void conditionalOnClass_PgconfigTileLayerCatalog() { */ @Test void conditionalOnGeoWebCacheEnabled() { - runner.withPropertyValues("gwc.enabled: false") - .run( - context -> { - assertThat(context) - .hasNotFailed() - .doesNotHaveBean(PgconfigTileLayerCatalog.class); - assertDefaultTileLayerCatalogConfigurationAbsent(context); - }); + runner.withPropertyValues("gwc.enabled: false").run(context -> { + assertThat(context).hasNotFailed().doesNotHaveBean(PgconfigTileLayerCatalog.class); + assertDefaultTileLayerCatalogConfigurationAbsent(context); + }); } /** @@ -149,18 +134,13 @@ void conditionalOnGeoWebCacheEnabled() { */ @Test void conditionalOnPgconfigBackendEnabled() { - runner.withPropertyValues("geoserver.backend.pgconfig.enabled: false") - .run( - context -> { - assertThat(context) - .hasNotFailed() - .doesNotHaveBean(PgconfigTileLayerCatalog.class); - assertDefaultTileLayerCatalogConfigurationPresent(context); - }); + runner.withPropertyValues("geoserver.backend.pgconfig.enabled: false").run(context -> { + assertThat(context).hasNotFailed().doesNotHaveBean(PgconfigTileLayerCatalog.class); + assertDefaultTileLayerCatalogConfigurationPresent(context); + }); } - private void assertDefaultTileLayerCatalogConfigurationAbsent( - AssertableWebApplicationContext context) { + private void assertDefaultTileLayerCatalogConfigurationAbsent(AssertableWebApplicationContext context) { assertThat(context) .doesNotHaveBean(CloudCatalogConfiguration.class) @@ -168,8 +148,7 @@ private void assertDefaultTileLayerCatalogConfigurationAbsent( .doesNotHaveBean(CachingTileLayerCatalog.class); } - private void assertDefaultTileLayerCatalogConfigurationPresent( - AssertableWebApplicationContext context) { + private void assertDefaultTileLayerCatalogConfigurationPresent(AssertableWebApplicationContext context) { assertThat(context) .hasSingleBean(ResourceStoreTileLayerCatalog.class) @@ -178,11 +157,8 @@ private void assertDefaultTileLayerCatalogConfigurationPresent( .getBean("gwcCatalogConfiguration", TileLayerConfiguration.class) .isInstanceOf(GeoServerTileLayerConfiguration.class); - assertThat( - context.getBean( - "gwcCatalogConfiguration", - GeoServerTileLayerConfiguration.class) - .getSubject()) + assertThat(context.getBean("gwcCatalogConfiguration", GeoServerTileLayerConfiguration.class) + .getSubject()) .isInstanceOf(CloudCatalogConfiguration.class); } } diff --git a/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/blobstore/AzureBlobstoreAutoConfigurationTest.java b/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/blobstore/AzureBlobstoreAutoConfigurationTest.java index 647a37960..744bc730f 100644 --- a/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/blobstore/AzureBlobstoreAutoConfigurationTest.java +++ b/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/blobstore/AzureBlobstoreAutoConfigurationTest.java @@ -6,6 +6,7 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.io.File; import org.geoserver.cloud.autoconfigure.gwc.GeoWebCacheContextRunner; import org.geoserver.gwc.web.GWCSettingsPage; import org.geoserver.gwc.web.blob.AzureBlobStoreType; @@ -17,8 +18,6 @@ import org.springframework.boot.test.context.FilteredClassLoader; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; -import java.io.File; - /** * {@link AzureBlobstoreAutoConfiguration} tests * @@ -28,58 +27,52 @@ class AzureBlobstoreAutoConfigurationTest { WebApplicationContextRunner runner; - @TempDir File tmpDir; + @TempDir + File tmpDir; @BeforeEach void setUp() { - runner = - GeoWebCacheContextRunner.newMinimalGeoWebCacheContextRunner(tmpDir) - .withConfiguration( - AutoConfigurations.of(AzureBlobstoreAutoConfiguration.class)); + runner = GeoWebCacheContextRunner.newMinimalGeoWebCacheContextRunner(tmpDir) + .withConfiguration(AutoConfigurations.of(AzureBlobstoreAutoConfiguration.class)); } @Test void disabledByDefault() { - runner.run( - context -> { - assertThat(context).doesNotHaveBean(AzureBlobStoreConfigProvider.class); - assertThat(context).doesNotHaveBean(AzureBlobStoreType.class); - assertThat(context).doesNotHaveBean("gwcAzureExtension"); - }); + runner.run(context -> { + assertThat(context).doesNotHaveBean(AzureBlobStoreConfigProvider.class); + assertThat(context).doesNotHaveBean(AzureBlobStoreType.class); + assertThat(context).doesNotHaveBean("gwcAzureExtension"); + }); } @Test void blobstoreEnabledGeoServerWebUiDisabled() { runner.withPropertyValues("gwc.blobstores.azure=true", "geoserver.web-ui.gwc.enabled=false") - .run( - context -> { - assertThat(context).hasSingleBean(AzureBlobStoreConfigProvider.class); - assertThat(context).doesNotHaveBean(AzureBlobStoreType.class); - assertThat(context).doesNotHaveBean("gwcAzureExtension"); - }); + .run(context -> { + assertThat(context).hasSingleBean(AzureBlobStoreConfigProvider.class); + assertThat(context).doesNotHaveBean(AzureBlobStoreType.class); + assertThat(context).doesNotHaveBean("gwcAzureExtension"); + }); } @Test void blobstoreEnabledGeoServerWebUiEnabled() { runner.withPropertyValues("gwc.blobstores.azure=true", "geoserver.web-ui.gwc.enabled=true") - .run( - context -> { - assertThat(context).hasSingleBean(AzureBlobStoreConfigProvider.class); - assertThat(context).hasSingleBean(AzureBlobStoreType.class); - assertThat(context).hasBean("gwcAzureExtension"); - }); + .run(context -> { + assertThat(context).hasSingleBean(AzureBlobStoreConfigProvider.class); + assertThat(context).hasSingleBean(AzureBlobStoreType.class); + assertThat(context).hasBean("gwcAzureExtension"); + }); } @Test void blobstoreEnabledGeoServerWebUiEnabledGsWebGwcNotInClassPath() { runner.withClassLoader(new FilteredClassLoader(GWCSettingsPage.class)) - .withPropertyValues( - "gwc.blobstores.azure=true", "geoserver.web-ui.gwc.enabled=true") - .run( - context -> { - assertThat(context).hasSingleBean(AzureBlobStoreConfigProvider.class); - assertThat(context).doesNotHaveBean(AzureBlobStoreType.class); - assertThat(context).doesNotHaveBean("gwcAzureExtension"); - }); + .withPropertyValues("gwc.blobstores.azure=true", "geoserver.web-ui.gwc.enabled=true") + .run(context -> { + assertThat(context).hasSingleBean(AzureBlobStoreConfigProvider.class); + assertThat(context).doesNotHaveBean(AzureBlobStoreType.class); + assertThat(context).doesNotHaveBean("gwcAzureExtension"); + }); } } diff --git a/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/blobstore/S3BlobstoreAutoConfigurationTest.java b/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/blobstore/S3BlobstoreAutoConfigurationTest.java index fdfca5ca9..90a01692b 100644 --- a/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/blobstore/S3BlobstoreAutoConfigurationTest.java +++ b/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/blobstore/S3BlobstoreAutoConfigurationTest.java @@ -6,6 +6,7 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.io.File; import org.geoserver.cloud.autoconfigure.gwc.GeoWebCacheContextRunner; import org.geoserver.gwc.web.GWCSettingsPage; import org.geoserver.gwc.web.blob.S3BlobStoreType; @@ -17,8 +18,6 @@ import org.springframework.boot.test.context.FilteredClassLoader; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; -import java.io.File; - /** * {@link S3BlobstoreAutoConfiguration} tests * @@ -28,57 +27,52 @@ class S3BlobstoreAutoConfigurationTest { WebApplicationContextRunner runner; - @TempDir File tmpDir; + @TempDir + File tmpDir; @BeforeEach void setUp() { - runner = - GeoWebCacheContextRunner.newMinimalGeoWebCacheContextRunner(tmpDir) - .withConfiguration( - AutoConfigurations.of(S3BlobstoreAutoConfiguration.class)); + runner = GeoWebCacheContextRunner.newMinimalGeoWebCacheContextRunner(tmpDir) + .withConfiguration(AutoConfigurations.of(S3BlobstoreAutoConfiguration.class)); } @Test void disabledByDefault() { - runner.run( - context -> { - assertThat(context).doesNotHaveBean(S3BlobStoreConfigProvider.class); - assertThat(context).doesNotHaveBean(S3BlobStoreType.class); - assertThat(context).doesNotHaveBean("gwcS3Extension"); - }); + runner.run(context -> { + assertThat(context).doesNotHaveBean(S3BlobStoreConfigProvider.class); + assertThat(context).doesNotHaveBean(S3BlobStoreType.class); + assertThat(context).doesNotHaveBean("gwcS3Extension"); + }); } @Test void blobstoreEnabledGeoServerWebUiDisabled() { runner.withPropertyValues("gwc.blobstores.s3=true", "geoserver.web-ui.gwc.enabled=false") - .run( - context -> { - assertThat(context).hasSingleBean(S3BlobStoreConfigProvider.class); - assertThat(context).doesNotHaveBean(S3BlobStoreType.class); - assertThat(context).doesNotHaveBean("gwcS3Extension"); - }); + .run(context -> { + assertThat(context).hasSingleBean(S3BlobStoreConfigProvider.class); + assertThat(context).doesNotHaveBean(S3BlobStoreType.class); + assertThat(context).doesNotHaveBean("gwcS3Extension"); + }); } @Test void blobstoreEnabledGeoServerWebUiEnabled() { runner.withPropertyValues("gwc.blobstores.s3=true", "geoserver.web-ui.gwc.enabled=true") - .run( - context -> { - assertThat(context).hasSingleBean(S3BlobStoreConfigProvider.class); - assertThat(context).hasSingleBean(S3BlobStoreType.class); - assertThat(context).hasBean("gwcS3Extension"); - }); + .run(context -> { + assertThat(context).hasSingleBean(S3BlobStoreConfigProvider.class); + assertThat(context).hasSingleBean(S3BlobStoreType.class); + assertThat(context).hasBean("gwcS3Extension"); + }); } @Test void blobstoreEnabledGeoServerWebUiEnabledGsWebGwcNotInClassPath() { runner.withClassLoader(new FilteredClassLoader(GWCSettingsPage.class)) .withPropertyValues("gwc.blobstores.s3=true", "geoserver.web-ui.gwc.enabled=true") - .run( - context -> { - assertThat(context).hasSingleBean(S3BlobStoreConfigProvider.class); - assertThat(context).doesNotHaveBean(S3BlobStoreType.class); - assertThat(context).doesNotHaveBean("gwcS3Extension"); - }); + .run(context -> { + assertThat(context).hasSingleBean(S3BlobStoreConfigProvider.class); + assertThat(context).doesNotHaveBean(S3BlobStoreType.class); + assertThat(context).doesNotHaveBean("gwcS3Extension"); + }); } } diff --git a/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/core/GwcCoreAutoConfigurationTest.java b/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/core/GwcCoreAutoConfigurationTest.java index d6cf35b56..21f26c93e 100644 --- a/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/core/GwcCoreAutoConfigurationTest.java +++ b/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/core/GwcCoreAutoConfigurationTest.java @@ -12,7 +12,8 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import com.google.common.base.Throwables; - +import java.io.File; +import java.io.IOException; import org.geoserver.cloud.autoconfigure.gwc.GeoWebCacheContextRunner; import org.geoserver.cloud.gwc.repository.CloudDefaultStorageFinder; import org.geoserver.cloud.gwc.repository.CloudGwcXmlConfiguration; @@ -33,9 +34,6 @@ import org.springframework.beans.factory.BeanInitializationException; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; -import java.io.File; -import java.io.IOException; - /** * @since 1.0 */ @@ -74,71 +72,56 @@ void defaultCacheDirectoryIsAFile(@TempDir File tmpDir) throws IOException { @Test void lockProviderDelegatesStoGeoSeverLockProvider() { - runner.run( - context -> { - GeoServerExtensionsHelper.init(context); - assertThat(context) - .hasNotFailed() - .hasBean(AbstractGwcInitializer.GWC_LOCK_PROVIDER_BEAN_NAME) - .getBean(AbstractGwcInitializer.GWC_LOCK_PROVIDER_BEAN_NAME) - .isInstanceOf(GeoServerLockProvider.class); - - GWCConfigPersister persister = context.getBean(GWCConfigPersister.class); - GWCConfig config = persister.getConfig(); - assertThat(config.getLockProviderName()) - .isEqualTo(AbstractGwcInitializer.GWC_LOCK_PROVIDER_BEAN_NAME); - - GWC gwc = GWC.get(); - - LockProvider lockProvider = gwc.getLockProvider(); - assertThat(lockProvider).isInstanceOf(ConfigurableLockProvider.class); - GeoServerLockProvider expected = - context.getBean( - AbstractGwcInitializer.GWC_LOCK_PROVIDER_BEAN_NAME, - GeoServerLockProvider.class); - assertThat(((ConfigurableLockProvider) lockProvider).getDelegate()) - .isSameAs(expected); - }); + runner.run(context -> { + GeoServerExtensionsHelper.init(context); + assertThat(context) + .hasNotFailed() + .hasBean(AbstractGwcInitializer.GWC_LOCK_PROVIDER_BEAN_NAME) + .getBean(AbstractGwcInitializer.GWC_LOCK_PROVIDER_BEAN_NAME) + .isInstanceOf(GeoServerLockProvider.class); + + GWCConfigPersister persister = context.getBean(GWCConfigPersister.class); + GWCConfig config = persister.getConfig(); + assertThat(config.getLockProviderName()).isEqualTo(AbstractGwcInitializer.GWC_LOCK_PROVIDER_BEAN_NAME); + + GWC gwc = GWC.get(); + + LockProvider lockProvider = gwc.getLockProvider(); + assertThat(lockProvider).isInstanceOf(ConfigurableLockProvider.class); + GeoServerLockProvider expected = + context.getBean(AbstractGwcInitializer.GWC_LOCK_PROVIDER_BEAN_NAME, GeoServerLockProvider.class); + assertThat(((ConfigurableLockProvider) lockProvider).getDelegate()).isSameAs(expected); + }); } @Test void contextLoads() { - runner.run( - context -> { - GeoServerExtensionsHelper.init(context); - assertThat(context) - .hasNotFailed() - .hasBean("gwcInitializer") - .getBean("gwcInitializer") - .isInstanceOf(DefaultGwcInitializer.class); - - assertThat(context.isTypeMatch("gwcXmlConfig", CloudGwcXmlConfiguration.class)) - .isTrue(); - assertThat( - context.isTypeMatch( - "gwcXmlConfigResourceProvider", - CloudXMLResourceProvider.class)) - .isTrue(); - assertThat( - context.isTypeMatch( - "gwcDefaultStorageFinder", - CloudDefaultStorageFinder.class)) - .isTrue(); - }); + runner.run(context -> { + GeoServerExtensionsHelper.init(context); + assertThat(context) + .hasNotFailed() + .hasBean("gwcInitializer") + .getBean("gwcInitializer") + .isInstanceOf(DefaultGwcInitializer.class); + + assertThat(context.isTypeMatch("gwcXmlConfig", CloudGwcXmlConfiguration.class)) + .isTrue(); + assertThat(context.isTypeMatch("gwcXmlConfigResourceProvider", CloudXMLResourceProvider.class)) + .isTrue(); + assertThat(context.isTypeMatch("gwcDefaultStorageFinder", CloudDefaultStorageFinder.class)) + .isTrue(); + }); } - protected void assertContextLoadFails( - Class expectedException, String expectedMessage) { - runner.run( - context -> { - GeoServerExtensionsHelper.init(context); - Throwable startupFailure = context.getStartupFailure(); - assertNotNull(startupFailure); - Throwable root = Throwables.getRootCause(startupFailure); - if (!expectedException.isInstance(root)) root.printStackTrace(); - assertInstanceOf(expectedException, root); - if (null != expectedMessage) - assertThat(root.getMessage(), containsString(expectedMessage)); - }); + protected void assertContextLoadFails(Class expectedException, String expectedMessage) { + runner.run(context -> { + GeoServerExtensionsHelper.init(context); + Throwable startupFailure = context.getStartupFailure(); + assertNotNull(startupFailure); + Throwable root = Throwables.getRootCause(startupFailure); + if (!expectedException.isInstance(root)) root.printStackTrace(); + assertInstanceOf(expectedException, root); + if (null != expectedMessage) assertThat(root.getMessage(), containsString(expectedMessage)); + }); } } diff --git a/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/integration/WMSIntegrationAutoConfigurationTest.java b/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/integration/WMSIntegrationAutoConfigurationTest.java index e3c7c95b5..d05eb50fa 100644 --- a/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/integration/WMSIntegrationAutoConfigurationTest.java +++ b/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/integration/WMSIntegrationAutoConfigurationTest.java @@ -8,6 +8,7 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.mock; +import java.io.File; import org.geoserver.cloud.autoconfigure.gwc.GeoWebCacheContextRunner; import org.geoserver.cloud.autoconfigure.gwc.integration.WMSIntegrationAutoConfiguration.ForwardGetMapToGwcAspect; import org.geoserver.gwc.web.GWCSettingsPage; @@ -21,8 +22,6 @@ import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; -import java.io.File; - /** * Test suite for {@link WMSIntegrationAutoConfiguration} * @@ -30,15 +29,15 @@ */ class WMSIntegrationAutoConfigurationTest { - @TempDir File tmpDir; + @TempDir + File tmpDir; + WebApplicationContextRunner runner; @BeforeEach void setUp() { - runner = - GeoWebCacheContextRunner.newMinimalGeoWebCacheContextRunner(tmpDir) - .withConfiguration( - AutoConfigurations.of(WMSIntegrationAutoConfiguration.class)); + runner = GeoWebCacheContextRunner.newMinimalGeoWebCacheContextRunner(tmpDir) + .withConfiguration(AutoConfigurations.of(WMSIntegrationAutoConfiguration.class)); } /** @@ -53,72 +52,46 @@ private WebApplicationContextRunner withMockWMS() { return runner.withBean("wmsServiceTarget", DefaultWebMapService.class, () -> mockWms) .withBean( - "wms_1_1_1_GetCapabilitiesResponse", - GetCapabilitiesResponse.class, - () -> mockGetCapabilities); + "wms_1_1_1_GetCapabilitiesResponse", GetCapabilitiesResponse.class, () -> mockGetCapabilities); } @Test void disabledByDefault() { - withMockWMS() - .run( - context -> { - assertThat(context) - .doesNotHaveBean(CachingExtendedCapabilitiesProvider.class); - assertThat(context).doesNotHaveBean(ForwardGetMapToGwcAspect.class); - assertThat(context) - .doesNotHaveBean( - "gwcSettingsPageWMSIntegationDisabledCssContribution"); - }); + withMockWMS().run(context -> { + assertThat(context).doesNotHaveBean(CachingExtendedCapabilitiesProvider.class); + assertThat(context).doesNotHaveBean(ForwardGetMapToGwcAspect.class); + assertThat(context).doesNotHaveBean("gwcSettingsPageWMSIntegationDisabledCssContribution"); + }); } @Test void enabledByConfigAndGeoServerWebMapServiceNotFound() { - runner.withPropertyValues("gwc.wms-integration=true") - .run( - context -> { - assertThat(context) - .doesNotHaveBean(CachingExtendedCapabilitiesProvider.class); - assertThat(context).doesNotHaveBean(ForwardGetMapToGwcAspect.class); - assertThat(context) - .doesNotHaveBean( - "gwcSettingsPageWMSIntegationDisabledCssContribution"); - }); + runner.withPropertyValues("gwc.wms-integration=true").run(context -> { + assertThat(context).doesNotHaveBean(CachingExtendedCapabilitiesProvider.class); + assertThat(context).doesNotHaveBean(ForwardGetMapToGwcAspect.class); + assertThat(context).doesNotHaveBean("gwcSettingsPageWMSIntegationDisabledCssContribution"); + }); } @Test void enabledByConfigAndGeoServerWebMapServiceFound() { - withMockWMS() - .withPropertyValues("gwc.wms-integration=true") - .run( - context -> { - assertThat(context) - .hasSingleBean(CachingExtendedCapabilitiesProvider.class); - assertThat(context).hasSingleBean(ForwardGetMapToGwcAspect.class); - assertThat(context) - .doesNotHaveBean( - "gwcSettingsPageWMSIntegationDisabledCssContribution"); - }); + withMockWMS().withPropertyValues("gwc.wms-integration=true").run(context -> { + assertThat(context).hasSingleBean(CachingExtendedCapabilitiesProvider.class); + assertThat(context).hasSingleBean(ForwardGetMapToGwcAspect.class); + assertThat(context).doesNotHaveBean("gwcSettingsPageWMSIntegationDisabledCssContribution"); + }); } @Test void disabledContributesCssToHideWebUIComponents() { - withMockWMS() - .withPropertyValues("geoserver.web-ui.gwc.enabled=true") - .run( - context -> { - assertThat(context) - .doesNotHaveBean(CachingExtendedCapabilitiesProvider.class); - assertThat(context).doesNotHaveBean(ForwardGetMapToGwcAspect.class); - assertThat(context) - .hasBean("gwcSettingsPageWMSIntegationDisabledCssContribution"); - HeaderContribution contrib = - context.getBean( - "gwcSettingsPageWMSIntegationDisabledCssContribution", - HeaderContribution.class); - assertEquals(GWCSettingsPage.class, contrib.getScope()); - assertEquals( - "wms-integration-disabled.css", contrib.getCSS().getName()); - }); + withMockWMS().withPropertyValues("geoserver.web-ui.gwc.enabled=true").run(context -> { + assertThat(context).doesNotHaveBean(CachingExtendedCapabilitiesProvider.class); + assertThat(context).doesNotHaveBean(ForwardGetMapToGwcAspect.class); + assertThat(context).hasBean("gwcSettingsPageWMSIntegationDisabledCssContribution"); + HeaderContribution contrib = + context.getBean("gwcSettingsPageWMSIntegationDisabledCssContribution", HeaderContribution.class); + assertEquals(GWCSettingsPage.class, contrib.getScope()); + assertEquals("wms-integration-disabled.css", contrib.getCSS().getName()); + }); } } diff --git a/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/service/RESTConfigAutoConfigurationTest.java b/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/service/RESTConfigAutoConfigurationTest.java index 422eb23dc..99d476bed 100644 --- a/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/service/RESTConfigAutoConfigurationTest.java +++ b/src/gwc/autoconfigure/src/test/java/org/geoserver/cloud/autoconfigure/gwc/service/RESTConfigAutoConfigurationTest.java @@ -6,6 +6,7 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.io.File; import org.geoserver.cloud.autoconfigure.gwc.GeoWebCacheContextRunner; import org.geoserver.gwc.controller.GwcUrlHandlerMapping; import org.geoserver.gwc.layer.GWCGeoServerRESTConfigurationProvider; @@ -18,54 +19,48 @@ import org.springframework.boot.test.context.FilteredClassLoader; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; -import java.io.File; - /** * @since 1.0 */ class RESTConfigAutoConfigurationTest { - @TempDir File tmpDir; + @TempDir + File tmpDir; + WebApplicationContextRunner runner; @BeforeEach void setUp() { - runner = - GeoWebCacheContextRunner.newMinimalGeoWebCacheContextRunner(tmpDir) - .withConfiguration( - AutoConfigurations.of(RESTConfigAutoConfiguration.class)); + runner = GeoWebCacheContextRunner.newMinimalGeoWebCacheContextRunner(tmpDir) + .withConfiguration(AutoConfigurations.of(RESTConfigAutoConfiguration.class)); } @Test void disabledByDefault() { - runner.run( - context -> { - assertThat(context).doesNotHaveBean(GWCConverter.class); - assertThat(context).doesNotHaveBean(TileLayerController.class); - }); + runner.run(context -> { + assertThat(context).doesNotHaveBean(GWCConverter.class); + assertThat(context).doesNotHaveBean(TileLayerController.class); + }); } @Test void enabled() { - runner.withPropertyValues("gwc.rest-config=true") - .run( - context -> { - assertThat(context) - .hasSingleBean(GWCConverter.class) - .hasSingleBean(TileLayerController.class) - .hasSingleBean(GWCGeoServerRESTConfigurationProvider.class) - .hasSingleBean(GwcUrlHandlerMapping.class); - }); + runner.withPropertyValues("gwc.rest-config=true").run(context -> { + assertThat(context) + .hasSingleBean(GWCConverter.class) + .hasSingleBean(TileLayerController.class) + .hasSingleBean(GWCGeoServerRESTConfigurationProvider.class) + .hasSingleBean(GwcUrlHandlerMapping.class); + }); } @Test void enabledButGwcRestJarNotInClassPath() { runner.withClassLoader(new FilteredClassLoader(GWCConverter.class)) .withPropertyValues("gwc.rest-config=true") - .run( - context -> { - assertThat(context).doesNotHaveBean(GWCConverter.class); - assertThat(context).doesNotHaveBean(TileLayerController.class); - }); + .run(context -> { + assertThat(context).doesNotHaveBean(GWCConverter.class); + assertThat(context).doesNotHaveBean(TileLayerController.class); + }); } } diff --git a/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/CachingTileLayerInfoRepository.java b/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/CachingTileLayerInfoRepository.java index e257c1619..b851d778a 100644 --- a/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/CachingTileLayerInfoRepository.java +++ b/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/CachingTileLayerInfoRepository.java @@ -4,10 +4,13 @@ */ package org.geoserver.cloud.gwc.backend.pgconfig; +import java.io.Serializable; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Stream; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.event.info.InfoEvent; import org.geoserver.cloud.gwc.event.TileLayerEvent; import org.springframework.cache.Cache; @@ -15,11 +18,6 @@ import org.springframework.dao.DataAccessException; import org.springframework.lang.Nullable; -import java.io.Serializable; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Stream; - /** * {@link TileLayerInfoRepository} decorator cache {@link TileLayerInfo}s on demand, alleviating the * load on the delegate, especially under load. @@ -107,8 +105,7 @@ public boolean save(@NonNull TileLayerInfo tli) throws DataAccessException { } @Override - public boolean delete(@Nullable String workspace, @NonNull String name) - throws DataAccessException { + public boolean delete(@Nullable String workspace, @NonNull String name) throws DataAccessException { evict(name(workspace, name)); return repository.delete(workspace, name); @@ -120,8 +117,7 @@ public Stream findAll() throws DataAccessException { } @Override - public Optional find(@Nullable String workspace, @NonNull String layer) - throws DataAccessException { + public Optional find(@Nullable String workspace, @NonNull String layer) throws DataAccessException { NameKey key = name(workspace, layer); return Optional.ofNullable(nameCache.get(key, () -> load(workspace, layer))); @@ -155,13 +151,10 @@ public Set findAllNames() throws DataAccessException { @Override public boolean exists(String workspace, @NonNull String layer) throws DataAccessException { return findCached(workspace, layer) - .map( - tl -> { - log.trace( - "returning exists=true from cache for layer {}", - name(workspace, layer)); - return true; - }) + .map(tl -> { + log.trace("returning exists=true from cache for layer {}", name(workspace, layer)); + return true; + }) .orElseGet(() -> repository.exists(workspace, layer)); } } diff --git a/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/GeoServerTileLayerInfoMapper.java b/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/GeoServerTileLayerInfoMapper.java index 0a667732c..f015af568 100644 --- a/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/GeoServerTileLayerInfoMapper.java +++ b/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/GeoServerTileLayerInfoMapper.java @@ -6,8 +6,8 @@ import static com.google.common.base.Preconditions.checkNotNull; +import java.util.Objects; import lombok.Generated; - import org.geoserver.catalog.PublishedInfo; import org.geoserver.cloud.gwc.backend.pgconfig.TileLayerInfo.Bounds; import org.geoserver.cloud.gwc.backend.pgconfig.TileLayerInfo.GridSubset; @@ -23,8 +23,6 @@ import org.mapstruct.MappingTarget; import org.mapstruct.ReportingPolicy; -import java.util.Objects; - /** * @since 1.7 */ @@ -46,8 +44,7 @@ default TileLayerInfo map(GeoServerTileLayer tileLayer) { GeoServerTileLayerInfoImpl map(TileLayerInfo info); @AfterMapping - default void setIdAndName( - TileLayerInfo source, @MappingTarget GeoServerTileLayerInfoImpl target) { + default void setIdAndName(TileLayerInfo source, @MappingTarget GeoServerTileLayerInfoImpl target) { PublishedInfo published = source.getPublished(); Objects.requireNonNull(published, "publishedInfo"); diff --git a/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/ParameterFilterMapper.java b/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/ParameterFilterMapper.java index 6bbc0df5e..a3dcd21e2 100644 --- a/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/ParameterFilterMapper.java +++ b/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/ParameterFilterMapper.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.gwc.backend.pgconfig; import lombok.Generated; - import org.geoserver.cloud.gwc.backend.pgconfig.TileLayerInfo.FloatParamFilter; import org.geoserver.cloud.gwc.backend.pgconfig.TileLayerInfo.IntegerParamFilter; import org.geoserver.cloud.gwc.backend.pgconfig.TileLayerInfo.ParamFilter; diff --git a/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerCatalog.java b/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerCatalog.java index 7a737c3f8..2adefb7d2 100644 --- a/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerCatalog.java +++ b/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerCatalog.java @@ -5,9 +5,15 @@ package org.geoserver.cloud.gwc.backend.pgconfig; import com.google.common.annotations.VisibleForTesting; - +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.Set; +import java.util.function.Supplier; +import java.util.function.UnaryOperator; +import java.util.stream.Stream; +import javax.sql.DataSource; import lombok.NonNull; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.PublishedInfo; import org.geoserver.catalog.WorkspaceInfo; @@ -25,16 +31,6 @@ import org.mapstruct.factory.Mappers; import org.springframework.jdbc.core.JdbcTemplate; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Optional; -import java.util.Set; -import java.util.function.Supplier; -import java.util.function.UnaryOperator; -import java.util.stream.Stream; - -import javax.sql.DataSource; - /** * A {@link TileLayerConfiguration} is like the GeoServer {@link Catalog} for {@link TileLayer}; * this one runs against the PostgreSQL database set up for {@link PgconfigCatalogFacade}, and @@ -50,8 +46,7 @@ public class PgconfigTileLayerCatalog implements TileLayerConfiguration { final @NonNull GridSetBroker gridsetBroker; final @NonNull UnaryOperator publishedResolver; - final GeoServerTileLayerInfoMapper infoMapper = - Mappers.getMapper(GeoServerTileLayerInfoMapper.class); + final GeoServerTileLayerInfoMapper infoMapper = Mappers.getMapper(GeoServerTileLayerInfoMapper.class); public PgconfigTileLayerCatalog( @NonNull TileLayerInfoRepository repository, @@ -67,8 +62,7 @@ public PgconfigTileLayerCatalog( } @VisibleForTesting - PgconfigTileLayerCatalog( - DataSource dataSource, GridSetBroker gridsets, Supplier catalog) { + PgconfigTileLayerCatalog(DataSource dataSource, GridSetBroker gridsets, Supplier catalog) { this(new PgconfigTileLayerInfoRepository(new JdbcTemplate(dataSource)), gridsets, catalog); } @@ -144,8 +138,7 @@ public Optional getLayer(@NonNull String layerName) { @Override public void addLayer(@NonNull TileLayer tl) throws IllegalArgumentException { - GeoServerTileLayer tileLayer = - canSave(tl, "Can't add TileLayer of type: %s ", tl.getClass()); + GeoServerTileLayer tileLayer = canSave(tl, "Can't add TileLayer of type: %s ", tl.getClass()); TileLayerInfo pgInfo = toInfo(tileLayer); repository.add(pgInfo); } @@ -167,8 +160,7 @@ public void removeLayer(String layerName) { @Override public void modifyLayer(@NonNull TileLayer tl) throws NoSuchElementException { - GeoServerTileLayer tileLayer = - canSave(tl, "Can't save TileLayer of type: %s ", tl.getClass()); + GeoServerTileLayer tileLayer = canSave(tl, "Can't save TileLayer of type: %s ", tl.getClass()); TileLayerInfo pgInfo = toInfo(tileLayer); boolean updated = repository.save(pgInfo); @@ -207,8 +199,7 @@ public boolean canSave(TileLayer tl) { } private GeoServerTileLayer canSave(TileLayer tl, String message, Object... args) { - return supportedAndNonTransient(tl) - .orElseThrow(() -> new IllegalArgumentException(message.formatted(args))); + return supportedAndNonTransient(tl).orElseThrow(() -> new IllegalArgumentException(message.formatted(args))); } private Optional supportedAndNonTransient(TileLayer tl) { diff --git a/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerInfoRepository.java b/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerInfoRepository.java index 443131fda..8ab97cf41 100644 --- a/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerInfoRepository.java +++ b/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerInfoRepository.java @@ -4,9 +4,14 @@ */ package org.geoserver.cloud.gwc.backend.pgconfig; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; +import java.util.stream.Stream; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.PublishedInfo; import org.geoserver.cloud.backend.pgconfig.catalog.repository.LoggingTemplate; import org.geoserver.gwc.layer.CatalogConfiguration; @@ -17,13 +22,6 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.lang.Nullable; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.TreeSet; -import java.util.stream.Collectors; -import java.util.stream.Stream; - /** * Implementation of {@link TileLayerInfoRepository} for {@link CatalogConfiguration} to manage * {@link GeoServerTileLayerInfo}s directly from the database instead of going through {@link @@ -57,19 +55,17 @@ private boolean save(TileLayerInfo tli, final PublishedInfo published) { final String encoded = PgconfigTileLayerInfoRowMapper.encode(tli); log.debug("Saving TileLayer {}: {}", published.prefixedName(), encoded); - int updated = - template.update( - """ + int updated = template.update( + """ UPDATE publishedinfo SET tilelayer = to_json(?::json) WHERE id = ? """, - encoded, - published.getId()); + encoded, + published.getId()); return updated == 1; } @Override - public boolean delete(@Nullable String workspaceName, @NonNull String localName) - throws DataAccessException { + public boolean delete(@Nullable String workspaceName, @NonNull String localName) throws DataAccessException { int updateCount; if (null == workspaceName) { String query = @@ -95,8 +91,7 @@ public Stream findAll() throws DataAccessException { } @Override - public Optional find(String workspaceName, @NonNull String localName) - throws DataAccessException { + public Optional find(String workspaceName, @NonNull String localName) throws DataAccessException { String sql; Object[] args; if (workspaceName == null) { @@ -128,16 +123,13 @@ public int count() throws DataAccessException { @Override public Set findAllNames() throws DataAccessException { - try (var stream = - template.queryForStream( - "SELECT name FROM tilelayers", (rs, rn) -> rs.getString(1))) { + try (var stream = template.queryForStream("SELECT name FROM tilelayers", (rs, rn) -> rs.getString(1))) { return stream.collect(Collectors.toCollection(TreeSet::new)); } } @Override - public boolean exists(String workspaceName, @NonNull String localName) - throws DataAccessException { + public boolean exists(String workspaceName, @NonNull String localName) throws DataAccessException { String query; Object[] args; if (null == workspaceName) { diff --git a/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerInfoRowMapper.java b/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerInfoRowMapper.java index 8ccf722c6..3512cbdc6 100644 --- a/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerInfoRowMapper.java +++ b/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerInfoRowMapper.java @@ -6,10 +6,11 @@ import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; - +import java.io.UncheckedIOException; +import java.sql.ResultSet; +import java.sql.SQLException; import lombok.NonNull; import lombok.SneakyThrows; - import org.geoserver.catalog.PublishedInfo; import org.geoserver.cloud.backend.pgconfig.catalog.repository.CatalogInfoRowMapper; import org.geoserver.cloud.backend.pgconfig.catalog.repository.PgconfigObjectMapper; @@ -17,10 +18,6 @@ import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; -import java.io.UncheckedIOException; -import java.sql.ResultSet; -import java.sql.SQLException; - /** * @since 1.7 */ @@ -36,8 +33,7 @@ private PgconfigTileLayerInfoRowMapper(RowMapper publishedMapper) public static PgconfigTileLayerInfoRowMapper newInstance(@NonNull JdbcTemplate template) { PgconfigStyleRepository styleLoader = new PgconfigStyleRepository(template); - RowMapper publishedMapper = - CatalogInfoRowMapper.published(styleLoader::findById); + RowMapper publishedMapper = CatalogInfoRowMapper.published(styleLoader::findById); return new PgconfigTileLayerInfoRowMapper(publishedMapper); } diff --git a/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/TileLayerInfo.java b/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/TileLayerInfo.java index e260e6e92..0de45d0ca 100644 --- a/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/TileLayerInfo.java +++ b/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/TileLayerInfo.java @@ -7,23 +7,20 @@ import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; - +import java.util.List; +import java.util.Locale; +import java.util.Optional; +import java.util.Set; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; - import org.geoserver.catalog.LayerGroupInfo; import org.geoserver.catalog.LayerInfo; import org.geoserver.catalog.PublishedInfo; import org.geowebcache.util.GWCVars; -import java.util.List; -import java.util.Locale; -import java.util.Optional; -import java.util.Set; - /** * @since 1.7 */ @@ -31,7 +28,8 @@ @Accessors(chain = true) public class TileLayerInfo { - @JsonIgnore private PublishedInfo published; + @JsonIgnore + private PublishedInfo published; private boolean enabled; diff --git a/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/TileLayerInfoRepository.java b/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/TileLayerInfoRepository.java index 1d3a88439..88f0b8e4e 100644 --- a/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/TileLayerInfoRepository.java +++ b/src/gwc/backends/pgconfig/src/main/java/org/geoserver/cloud/gwc/backend/pgconfig/TileLayerInfoRepository.java @@ -4,11 +4,10 @@ */ package org.geoserver.cloud.gwc.backend.pgconfig; -import org.springframework.dao.DataAccessException; - import java.util.Optional; import java.util.Set; import java.util.stream.Stream; +import org.springframework.dao.DataAccessException; /** * {@code TileLayerInfoRepository} defines CRUD operations on {@link TileLayerInfo}. diff --git a/src/gwc/backends/pgconfig/src/test/java/org/geoserver/cloud/gwc/backend/pgconfig/GeoServerTileLayerInfoMapperTest.java b/src/gwc/backends/pgconfig/src/test/java/org/geoserver/cloud/gwc/backend/pgconfig/GeoServerTileLayerInfoMapperTest.java index c5b85bb5a..aed813639 100644 --- a/src/gwc/backends/pgconfig/src/test/java/org/geoserver/cloud/gwc/backend/pgconfig/GeoServerTileLayerInfoMapperTest.java +++ b/src/gwc/backends/pgconfig/src/test/java/org/geoserver/cloud/gwc/backend/pgconfig/GeoServerTileLayerInfoMapperTest.java @@ -9,6 +9,9 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import java.util.List; +import java.util.Locale; +import java.util.Set; import org.geoserver.catalog.LayerInfo; import org.geoserver.catalog.plugin.CatalogPlugin; import org.geoserver.cloud.gwc.backend.pgconfig.TileLayerInfo.ParamFilter; @@ -35,10 +38,6 @@ import org.junit.jupiter.api.Test; import org.mapstruct.factory.Mappers; -import java.util.List; -import java.util.Locale; -import java.util.Set; - /** * @since 1.7 */ @@ -51,8 +50,7 @@ class GeoServerTileLayerInfoMapperTest { @BeforeEach void before() { mapper = Mappers.getMapper(GeoServerTileLayerInfoMapper.class); - LayerInfo layerInfo = - new TileLayerMocking(new CatalogPlugin(), new GeoServerImpl()).layerInfo(); + LayerInfo layerInfo = new TileLayerMocking(new CatalogPlugin(), new GeoServerImpl()).layerInfo(); GWCConfig defaults = new GWCConfig(); info = TileLayerInfoUtil.loadOrCreate(layerInfo, defaults); info.setId(layerInfo.getId()); @@ -108,13 +106,12 @@ void testStyleParameterFilter() { @Test void testParameterFilters() { - testParameterFilters( - Set.of( - regexParameterFilter(), - stringParameterFilter(), - floatParameterFilter(), - integerParameterFilter(), - styleParameterFilter())); + testParameterFilters(Set.of( + regexParameterFilter(), + stringParameterFilter(), + floatParameterFilter(), + integerParameterFilter(), + styleParameterFilter())); } @Test @@ -161,8 +158,7 @@ void testGridSubsets() { @Test void testExpireCacheList() { - List rules = - List.of(new ExpirationRule(1, 100), new ExpirationRule(12, 200)); + List rules = List.of(new ExpirationRule(1, 100), new ExpirationRule(12, 200)); info.setExpireCacheList(rules); // ExpirationRule does not implement equals() diff --git a/src/gwc/backends/pgconfig/src/test/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerCatalogIT.java b/src/gwc/backends/pgconfig/src/test/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerCatalogIT.java index 1a6aebe3d..1eae16b55 100644 --- a/src/gwc/backends/pgconfig/src/test/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerCatalogIT.java +++ b/src/gwc/backends/pgconfig/src/test/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerCatalogIT.java @@ -6,6 +6,11 @@ import static org.assertj.core.api.Assertions.assertThat; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.IntStream; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.DataStoreInfo; import org.geoserver.catalog.FeatureTypeInfo; @@ -29,19 +34,14 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.IntStream; - /** * @since 1.7 */ @Testcontainers(disabledWithoutDocker = true) class PgconfigTileLayerCatalogIT { - @Container static PgConfigTestContainer container = new PgConfigTestContainer<>(); + @Container + static PgConfigTestContainer container = new PgConfigTestContainer<>(); private TileLayerMocking support; @@ -50,14 +50,12 @@ class PgconfigTileLayerCatalogIT { @BeforeEach void setUp() { container.setUp(); - PgconfigBackendBuilder backendBuilder = - new PgconfigBackendBuilder(container.getDataSource()); + PgconfigBackendBuilder backendBuilder = new PgconfigBackendBuilder(container.getDataSource()); CatalogPlugin catalog = backendBuilder.createCatalog(); GeoServerImpl geoServer = backendBuilder.createGeoServer(catalog); support = new TileLayerMocking(catalog, geoServer); GridSetBroker gridsets = support.getGridsets(); - tlCatalog = - new PgconfigTileLayerCatalog(container.getDataSource(), gridsets, () -> catalog); + tlCatalog = new PgconfigTileLayerCatalog(container.getDataSource(), gridsets, () -> catalog); } @AfterEach @@ -98,11 +96,10 @@ void testSimpleLayer() { gsl.removeGridSubset(gsl.getGridSubsets().iterator().next()); tlCatalog.modifyLayer(gsl); - GeoServerTileLayer modified = - tlCatalog - .getLayer(layerInfo.prefixedName()) - .map(GeoServerTileLayer.class::cast) - .orElseThrow(); + GeoServerTileLayer modified = tlCatalog + .getLayer(layerInfo.prefixedName()) + .map(GeoServerTileLayer.class::cast) + .orElseThrow(); assertThat(modified.getBlobStoreId()).isEqualTo("newBlobStore"); assertThat(modified.isEnabled()).isFalse(); assertThat(modified.getGridSubsets()).hasSize(1); @@ -110,8 +107,7 @@ void testSimpleLayer() { Catalog catalog = support.getFaker().catalog(); final String oldName = layerInfo.prefixedName(); - ResourceInfo resource = - catalog.getResource(layerInfo.getResource().getId(), ResourceInfo.class); + ResourceInfo resource = catalog.getResource(layerInfo.getResource().getId(), ResourceInfo.class); resource.setName("newName"); catalog.save(resource); @@ -171,17 +167,16 @@ private List addLayers(WorkspaceInfo workspace, int count) { return IntStream.range(0, count) .parallel() - .mapToObj( - i -> { - String name = faker.name() + "-" + i; - FeatureTypeInfo featureType = faker.featureTypeInfo(ds, name); - faker.catalog().add(featureType); + .mapToObj(i -> { + String name = faker.name() + "-" + i; + FeatureTypeInfo featureType = faker.featureTypeInfo(ds, name); + faker.catalog().add(featureType); - LayerInfo layer = faker.layerInfo(featureType, defaultStyle); - faker.catalog().add(layer); + LayerInfo layer = faker.layerInfo(featureType, defaultStyle); + faker.catalog().add(layer); - return support.geoServerTileLayer(layer); - }) + return support.geoServerTileLayer(layer); + }) .peek(tlCatalog::addLayer) .map(GeoServerTileLayer::getName) .toList(); diff --git a/src/gwc/backends/pgconfig/src/test/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerCatalogTest.java b/src/gwc/backends/pgconfig/src/test/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerCatalogTest.java index 3bf8113cb..be95fd905 100644 --- a/src/gwc/backends/pgconfig/src/test/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerCatalogTest.java +++ b/src/gwc/backends/pgconfig/src/test/java/org/geoserver/cloud/gwc/backend/pgconfig/PgconfigTileLayerCatalogTest.java @@ -15,8 +15,13 @@ import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.Set; +import java.util.function.Supplier; +import java.util.stream.Stream; import lombok.NonNull; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.LayerInfo; import org.geoserver.catalog.PublishedInfo; @@ -31,13 +36,6 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Optional; -import java.util.Set; -import java.util.function.Supplier; -import java.util.stream.Stream; - /** * @since 1.7 */ @@ -52,8 +50,7 @@ class PgconfigTileLayerCatalogTest { void setUp() { support = new TileLayerMocking(new CatalogPlugin(), new GeoServerImpl()); repository = mock(PgconfigTileLayerInfoRepository.class); - tlCatalog = - new PgconfigTileLayerCatalog(repository, support.getGridsets(), support.catalog()); + tlCatalog = new PgconfigTileLayerCatalog(repository, support.getGridsets(), support.catalog()); } @Test @@ -65,10 +62,7 @@ void testConstructor() { Supplier catalog = support.catalog(); Class npe = NullPointerException.class; assertThrows( - npe, - () -> - new PgconfigTileLayerCatalog( - (PgconfigTileLayerInfoRepository) null, gridsets, catalog)); + npe, () -> new PgconfigTileLayerCatalog((PgconfigTileLayerInfoRepository) null, gridsets, catalog)); assertThrows(npe, () -> new PgconfigTileLayerCatalog(repository, null, catalog)); assertThrows(npe, () -> new PgconfigTileLayerCatalog(repository, gridsets, null)); } @@ -103,10 +97,7 @@ void testDeinitializeIsNoOp() { @Test void testSetGridSetBroker() { GridSetBroker gridsets = support.getGridsets(); - var expected = - assertThrows( - UnsupportedOperationException.class, - () -> tlCatalog.setGridSetBroker(gridsets)); + var expected = assertThrows(UnsupportedOperationException.class, () -> tlCatalog.setGridSetBroker(gridsets)); assertThat(expected.getMessage()).contains("use constructor injection instead"); } @@ -135,8 +126,7 @@ void testGetLayers_PsqlTileLayerInfo_must_have_PublishedInfo() { tli.setPublished(null); when(repository.findAll()).thenReturn(Stream.of(tli)); - NullPointerException npe = - assertThrows(NullPointerException.class, () -> tlCatalog.getLayers()); + NullPointerException npe = assertThrows(NullPointerException.class, () -> tlCatalog.getLayers()); assertThat(npe.getMessage()).contains("publishedInfo"); } @@ -226,8 +216,7 @@ private void mockFind(TileLayerInfo info) { @Test void testAddLayer_not_a_GeoSeverTileLayer() { - assertThrows( - IllegalArgumentException.class, () -> tlCatalog.addLayer(mock(TileLayer.class))); + assertThrows(IllegalArgumentException.class, () -> tlCatalog.addLayer(mock(TileLayer.class))); } @Test @@ -273,8 +262,7 @@ void testRemoveLayer() { @Test void testModifyLayer_not_a_GeoSeverTileLayer() { - assertThrows( - IllegalArgumentException.class, () -> tlCatalog.modifyLayer(mock(TileLayer.class))); + assertThrows(IllegalArgumentException.class, () -> tlCatalog.modifyLayer(mock(TileLayer.class))); } @Test diff --git a/src/gwc/backends/pgconfig/src/test/java/org/geoserver/cloud/gwc/backend/pgconfig/TileLayerMocking.java b/src/gwc/backends/pgconfig/src/test/java/org/geoserver/cloud/gwc/backend/pgconfig/TileLayerMocking.java index f10e6fd62..5b17f2aa2 100644 --- a/src/gwc/backends/pgconfig/src/test/java/org/geoserver/cloud/gwc/backend/pgconfig/TileLayerMocking.java +++ b/src/gwc/backends/pgconfig/src/test/java/org/geoserver/cloud/gwc/backend/pgconfig/TileLayerMocking.java @@ -4,9 +4,12 @@ */ package org.geoserver.cloud.gwc.backend.pgconfig; +import java.util.List; +import java.util.Set; +import java.util.function.Supplier; +import java.util.stream.Collectors; import lombok.Getter; import lombok.NonNull; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.DataStoreInfo; import org.geoserver.catalog.FeatureTypeInfo; @@ -30,11 +33,6 @@ import org.geowebcache.grid.GridSetBroker; import org.mapstruct.factory.Mappers; -import java.util.List; -import java.util.Set; -import java.util.function.Supplier; -import java.util.stream.Collectors; - /** * @since 1.7 */ @@ -44,8 +42,7 @@ class TileLayerMocking { private @Getter CatalogFaker faker; - final GeoServerTileLayerInfoMapper infoMapper = - Mappers.getMapper(GeoServerTileLayerInfoMapper.class); + final GeoServerTileLayerInfoMapper infoMapper = Mappers.getMapper(GeoServerTileLayerInfoMapper.class); private Catalog catalog; @@ -72,8 +69,7 @@ public String workspaceName(PublishedInfo published) { } public GeoServerTileLayer geoServerTileLayer(PublishedInfo published) { - GeoServerTileLayerInfo tileLayerInfo = - TileLayerInfoUtil.loadOrCreate(published, new GWCConfig()); + GeoServerTileLayerInfo tileLayerInfo = TileLayerInfoUtil.loadOrCreate(published, new GWCConfig()); return new GeoServerTileLayer(published, gridsets, tileLayerInfo); } diff --git a/src/gwc/blobstores/src/test/java/org/geoserver/cloud/gwc/config/blobstore/AzureBlobStoreTest.java b/src/gwc/blobstores/src/test/java/org/geoserver/cloud/gwc/config/blobstore/AzureBlobStoreTest.java index bd3fdf121..20b5ea3ad 100644 --- a/src/gwc/blobstores/src/test/java/org/geoserver/cloud/gwc/config/blobstore/AzureBlobStoreTest.java +++ b/src/gwc/blobstores/src/test/java/org/geoserver/cloud/gwc/config/blobstore/AzureBlobStoreTest.java @@ -8,6 +8,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import java.util.Map; import org.geowebcache.GeoWebCacheEnvironment; import org.geowebcache.GeoWebCacheExtensions; import org.geowebcache.azure.AzureBlobStore; @@ -28,8 +29,6 @@ import org.testcontainers.junit.jupiter.Container; import org.testcontainers.junit.jupiter.Testcontainers; -import java.util.Map; - /** * Verify {@link AzureBlobStore} works by connecting to an Azurite container * @@ -39,7 +38,8 @@ @Disabled("disabled until https://github.com/GeoWebCache/geowebcache/pull/1298 is merged") class AzureBlobStoreTest { - @Container static AzuriteContainer azurite = new AzuriteContainer(); + @Container + static AzuriteContainer azurite = new AzuriteContainer(); protected AzureBlobStoreInfo newAzureBlobStoreInfo() { AzureBlobStoreInfo bsi = new AzureBlobStoreInfo(); @@ -77,8 +77,7 @@ protected AzureBlobStoreInfo newAzureBlobStoreInfo() { @Test void createBlobStore() throws StorageException { AzureBlobStoreInfo info = newAzureBlobStoreInfo(); - BlobStore store = - info.createInstance(mock(TileLayerDispatcher.class), new MemoryLockProvider()); + BlobStore store = info.createInstance(mock(TileLayerDispatcher.class), new MemoryLockProvider()); assertThat(store).isInstanceOf(AzureBlobStore.class); } @@ -87,8 +86,7 @@ void testPutGet() throws Exception { TileLayerDispatcher layers = mock(TileLayerDispatcher.class); AzureBlobStoreInfo info = newAzureBlobStoreInfo(); - AzureBlobStore store = - (AzureBlobStore) info.createInstance(layers, new MemoryLockProvider()); + AzureBlobStore store = (AzureBlobStore) info.createInstance(layers, new MemoryLockProvider()); final String layerName = "FakeLayer"; final long[] xyz = new long[] {0, 0, 0}; @@ -102,14 +100,11 @@ void testPutGet() throws Exception { when(tileLayer.getId()).thenReturn(layerName); when(layers.getTileLayer(layerName)).thenReturn(tileLayer); - TileObject tile = - TileObject.createCompleteTileObject( - layerName, xyz, gridSetId, format, parameters, blob); + TileObject tile = TileObject.createCompleteTileObject(layerName, xyz, gridSetId, format, parameters, blob); store.put(tile); @SuppressWarnings("unused") - TileObject query = - TileObject.createQueryTileObject(layerName, xyz, gridSetId, format, parameters); + TileObject query = TileObject.createQueryTileObject(layerName, xyz, gridSetId, format, parameters); // can't really test get, see https://github.com/Azure/Azurite/issues/217 /* diff --git a/src/gwc/blobstores/src/test/java/org/geoserver/cloud/gwc/config/blobstore/AzureBlobStoreXmlConfigurationTest.java b/src/gwc/blobstores/src/test/java/org/geoserver/cloud/gwc/config/blobstore/AzureBlobStoreXmlConfigurationTest.java index 47302a387..1f2389241 100644 --- a/src/gwc/blobstores/src/test/java/org/geoserver/cloud/gwc/config/blobstore/AzureBlobStoreXmlConfigurationTest.java +++ b/src/gwc/blobstores/src/test/java/org/geoserver/cloud/gwc/config/blobstore/AzureBlobStoreXmlConfigurationTest.java @@ -13,6 +13,11 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; import org.geoserver.cloud.gwc.event.BlobStoreEvent; import org.geoserver.cloud.gwc.event.GeoWebCacheEvent; import org.geoserver.cloud.gwc.repository.CloudGwcXmlConfiguration; @@ -30,12 +35,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import java.util.concurrent.atomic.AtomicReference; - /** * @since 1.0 */ @@ -63,15 +62,10 @@ void setUp() throws IOException, GeoWebCacheException { private CloudGwcXmlConfiguration createStubConfig() throws GeoWebCacheException { ApplicationContextProvider appCtx = mock(ApplicationContextProvider.class); - ConfigurationResourceProvider inFac = - new XMLFileResourceProvider( - "geowebcache.xml", - appCtx, - tmpdir.toAbsolutePath().toString(), - (DefaultStorageFinder) null); + ConfigurationResourceProvider inFac = new XMLFileResourceProvider( + "geowebcache.xml", appCtx, tmpdir.toAbsolutePath().toString(), (DefaultStorageFinder) null); - CloudGwcXmlConfiguration xmlConfig = - new CloudGwcXmlConfiguration(appCtx, inFac, mockEventPublisher::set); + CloudGwcXmlConfiguration xmlConfig = new CloudGwcXmlConfiguration(appCtx, inFac, mockEventPublisher::set); GridSetBroker broker = new GridSetBroker(List.of(defaultGridsets)); xmlConfig.setGridSetBroker(broker); xmlConfig.afterPropertiesSet(); diff --git a/src/gwc/blobstores/src/test/java/org/geoserver/cloud/gwc/config/blobstore/AzuriteContainer.java b/src/gwc/blobstores/src/test/java/org/geoserver/cloud/gwc/config/blobstore/AzuriteContainer.java index 80ed13b26..afdc1a1e5 100644 --- a/src/gwc/blobstores/src/test/java/org/geoserver/cloud/gwc/config/blobstore/AzuriteContainer.java +++ b/src/gwc/blobstores/src/test/java/org/geoserver/cloud/gwc/config/blobstore/AzuriteContainer.java @@ -2,7 +2,6 @@ import lombok.Getter; import lombok.NonNull; - import org.testcontainers.containers.GenericContainer; import org.testcontainers.containers.wait.strategy.Wait; import org.testcontainers.junit.jupiter.Testcontainers; diff --git a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/DefaultTileLayerCatalogConfiguration.java b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/DefaultTileLayerCatalogConfiguration.java index 7ff05adb6..f062880fb 100644 --- a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/DefaultTileLayerCatalogConfiguration.java +++ b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/DefaultTileLayerCatalogConfiguration.java @@ -4,6 +4,7 @@ */ package org.geoserver.cloud.gwc.config.core; +import java.util.Optional; import org.geoserver.GeoServerConfigurationLock; import org.geoserver.catalog.Catalog; import org.geoserver.cloud.gwc.repository.CachingTileLayerCatalog; @@ -29,8 +30,6 @@ import org.springframework.context.annotation.Primary; import org.springframework.web.context.WebApplicationContext; -import java.util.Optional; - /** * @since 1.0 */ @@ -80,8 +79,7 @@ GeoServerTileLayerConfiguration gwcCatalogConfiguration( // ApplicationEventPublisher eventPublisher) { var config = new CloudCatalogConfiguration(catalog, tld, gsb); - var eventAwareConfig = - new GeoServerTileLayerConfiguration(config, eventPublisher::publishEvent); + var eventAwareConfig = new GeoServerTileLayerConfiguration(config, eventPublisher::publishEvent); // tell GeoServerTileLayerConfiguration to relay TileLayerEvents to // CloudCatalogConfiguration, since it's not a spring bean can't listen itself. eventAwareConfig.setEventListener(config::onTileLayerEventEvict); @@ -98,8 +96,7 @@ TileLayerCatalog cachingTileLayerCatalog(ResourceStoreTileLayerCatalog delegate) @Bean ResourceStoreTileLayerCatalog resourceStoreTileLayerCatalog( - @Qualifier("resourceStoreImpl") ResourceStore resourceStore, - Optional webappCtx) { + @Qualifier("resourceStoreImpl") ResourceStore resourceStore, Optional webappCtx) { return new ResourceStoreTileLayerCatalog(resourceStore, webappCtx); } } diff --git a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/DiskQuotaConfiguration.java b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/DiskQuotaConfiguration.java index af58b85d3..d0b1a1755 100644 --- a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/DiskQuotaConfiguration.java +++ b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/DiskQuotaConfiguration.java @@ -21,9 +21,7 @@ @Configuration(proxyBeanMethods = false) @ImportResource( reader = FilteringXmlBeanDefinitionReader.class, // - locations = { - "jar:gs-gwc-[0-9]+.*!/geowebcache-diskquota-context.xml#name=^(?!DiskQuotaConfigLoader).*$" - }) + locations = {"jar:gs-gwc-[0-9]+.*!/geowebcache-diskquota-context.xml#name=^(?!DiskQuotaConfigLoader).*$"}) public class DiskQuotaConfiguration { static { @@ -46,7 +44,6 @@ org.geowebcache.diskquota.ConfigLoader diskQuotaConfigLoader( // TileLayerDispatcher tld) throws ConfigurationException { - return new org.geowebcache.diskquota.ConfigLoader( - diskQuotaConfigResourceProvider, storageFinder, tld); + return new org.geowebcache.diskquota.ConfigLoader(diskQuotaConfigResourceProvider, storageFinder, tld); } } diff --git a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/GeoServerIntegrationConfiguration.java b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/GeoServerIntegrationConfiguration.java index d09a4da44..d52433ddb 100644 --- a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/GeoServerIntegrationConfiguration.java +++ b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/GeoServerIntegrationConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.gwc.config.core; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.config.factory.FilteringXmlBeanDefinitionReader; import org.geoserver.cloud.gwc.event.ConfigChangeEvent; import org.geoserver.config.util.XStreamPersisterFactory; @@ -17,8 +17,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; -import javax.annotation.PostConstruct; - /** * @since 1.0 * @see DefaultTileLayerCatalogConfiguration @@ -61,9 +59,7 @@ public void log() { */ @Bean GWCConfigPersister gwcGeoServervConfigPersister( - XStreamPersisterFactory xsfp, - GeoServerResourceLoader resourceLoader, - ApplicationEventPublisher publisher) { + XStreamPersisterFactory xsfp, GeoServerResourceLoader resourceLoader, ApplicationEventPublisher publisher) { return new CloudGwcConfigPersister(xsfp, resourceLoader, publisher::publishEvent); } } diff --git a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/GeoWebCacheConfigurationProperties.java b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/GeoWebCacheConfigurationProperties.java index 3258c5136..44dc8ddf9 100644 --- a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/GeoWebCacheConfigurationProperties.java +++ b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/GeoWebCacheConfigurationProperties.java @@ -4,13 +4,11 @@ */ package org.geoserver.cloud.gwc.config.core; +import java.nio.file.Path; import lombok.Data; - import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; import org.springframework.boot.context.properties.ConfigurationProperties; -import java.nio.file.Path; - /** * Configuration properties for GeoWebcache * diff --git a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/GeoWebCacheCoreConfiguration.java b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/GeoWebCacheCoreConfiguration.java index 2c1e01836..2e65fe1f9 100644 --- a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/GeoWebCacheCoreConfiguration.java +++ b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/GeoWebCacheCoreConfiguration.java @@ -8,8 +8,19 @@ import static org.geoserver.cloud.gwc.config.core.GeoWebCacheConfigurationProperties.CONFIG_DIRECTORY; import static org.geowebcache.storage.DefaultStorageFinder.GWC_CACHE_DIR; +import java.io.IOException; +import java.nio.file.FileAlreadyExistsException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.function.Supplier; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletRequestWrapper; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.config.factory.FilteringXmlBeanDefinitionReader; import org.geoserver.cloud.gwc.repository.CloudDefaultStorageFinder; import org.geoserver.cloud.gwc.repository.CloudGwcXmlConfiguration; @@ -37,20 +48,6 @@ import org.springframework.core.env.Environment; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; -import java.io.IOException; -import java.nio.file.FileAlreadyExistsException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.function.Supplier; - -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletRequestWrapper; - /** * @since 1.0 */ @@ -104,17 +101,13 @@ RequestMappingHandlerMapping requestMappingHandlerMapping() { @Bean Path gwcDefaultCacheDirectory(GeoWebCacheConfigurationProperties config) { final Path directory = config.getCacheDirectory(); - log.debug( - "resolving default cache directory from configuration property {}={}", - CACHE_DIRECTORY, - directory); + log.debug("resolving default cache directory from configuration property {}={}", CACHE_DIRECTORY, directory); if (null == directory) { throw new InvalidPropertyException( GeoWebCacheConfigurationProperties.class, "cacheDirectory", - "%s is not set. The default cache directory MUST be provided." - .formatted(CACHE_DIRECTORY)); + "%s is not set. The default cache directory MUST be provided.".formatted(CACHE_DIRECTORY)); } validateDirectory(directory, CACHE_DIRECTORY); @@ -140,8 +133,7 @@ Path gwcDefaultCacheDirectory(GeoWebCacheConfigurationProperties config) { * gwc.config-directory} config property is invalid */ private Supplier gwcDefaultConfigDirectory( - GeoWebCacheConfigurationProperties config, - @Qualifier("resourceStoreImpl") ResourceStore resourceStore) + GeoWebCacheConfigurationProperties config, @Qualifier("resourceStoreImpl") ResourceStore resourceStore) throws FatalBeanException { final Path directory = config.getConfigDirectory(); @@ -181,11 +173,9 @@ private Supplier gwcDefaultConfigDirectory( */ @Bean ConfigurationResourceProvider gwcXmlConfigResourceProvider( - GeoWebCacheConfigurationProperties config, - @Qualifier("resourceStoreImpl") ResourceStore resourceStore) { + GeoWebCacheConfigurationProperties config, @Qualifier("resourceStoreImpl") ResourceStore resourceStore) { - Supplier configDirSupplier = - this.gwcDefaultConfigDirectory(config, resourceStore); + Supplier configDirSupplier = this.gwcDefaultConfigDirectory(config, resourceStore); return new CloudXMLResourceProvider(configDirSupplier); } @@ -223,8 +213,7 @@ XMLConfiguration gwcXmlConfig( // */ @Bean DefaultStorageFinder gwcDefaultStorageFinder( - @Qualifier("gwcDefaultCacheDirectory") Path defaultCacheDirectory, - Environment environment) { + @Qualifier("gwcDefaultCacheDirectory") Path defaultCacheDirectory, Environment environment) { return new CloudDefaultStorageFinder(defaultCacheDirectory, environment); } @@ -239,26 +228,19 @@ private void validateDirectory(Path directory, String configPropertyName) { if (!Files.exists(directory)) { try { Path created = Files.createDirectory(directory); - log.info( - "Created directory from config property {}: {}", - configPropertyName, - created); + log.info("Created directory from config property {}: {}", configPropertyName, created); } catch (FileAlreadyExistsException beatenByOtherInstance) { // continue } catch (IOException e) { throw new BeanInitializationException( - "%s does not exist and can't be created: %s" - .formatted(configPropertyName, directory), - e); + "%s does not exist and can't be created: %s".formatted(configPropertyName, directory), e); } } if (!Files.isDirectory(directory)) { - throw new BeanInitializationException( - "%s is not a directory: %s".formatted(configPropertyName, directory)); + throw new BeanInitializationException("%s is not a directory: %s".formatted(configPropertyName, directory)); } if (!Files.isWritable(directory)) { - throw new BeanInitializationException( - "%s is not writable: %s".formatted(configPropertyName, directory)); + throw new BeanInitializationException("%s is not writable: %s".formatted(configPropertyName, directory)); } } diff --git a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/WebMapServiceCacheSeedingConfiguration.java b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/WebMapServiceCacheSeedingConfiguration.java index c153712ac..c1ce117c9 100644 --- a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/WebMapServiceCacheSeedingConfiguration.java +++ b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/WebMapServiceCacheSeedingConfiguration.java @@ -6,6 +6,7 @@ import static com.google.common.base.Preconditions.checkArgument; +import java.util.Map; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; @@ -21,8 +22,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import java.util.Map; - /** * Configuration to create a decorator around {@link WebMapService} to set {@link * GeoServerTileLayer#WEB_MAP} as expected by {@link GeoServerTileLayer} when requested to seed a @@ -82,8 +81,7 @@ public WebMap getMap(ProceedingJoinPoint joinPoint) throws Throwable { protected boolean isInternalRequestForSeeding(final GetMapRequest request) { final Map rawKvp = request.getRawKvp(); - return rawKvp != null - && rawKvp.containsKey(GeoServerTileLayer.GWC_SEED_INTERCEPT_TOKEN); + return rawKvp != null && rawKvp.containsKey(GeoServerTileLayer.GWC_SEED_INTERCEPT_TOKEN); } } } diff --git a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/WebMapServiceMinimalConfiguration.java b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/WebMapServiceMinimalConfiguration.java index daf7280b2..1dc68f9cb 100644 --- a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/WebMapServiceMinimalConfiguration.java +++ b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/config/core/WebMapServiceMinimalConfiguration.java @@ -79,11 +79,9 @@ public class WebMapServiceMinimalConfiguration { ).*$\ """; - static final String GS_WMS_INCLUDES = - "jar:gs-wms-[0-9]+.*!/applicationContext.xml#name=" + WMS_BEANS_REGEX; + static final String GS_WMS_INCLUDES = "jar:gs-wms-[0-9]+.*!/applicationContext.xml#name=" + WMS_BEANS_REGEX; - static final String GS_WFS_INCLUDES = - "jar:gs-wfs-[0-9]+.*!/applicationContext.xml#name=" + WFS_BEANS_REGEX; + static final String GS_WFS_INCLUDES = "jar:gs-wfs-[0-9]+.*!/applicationContext.xml#name=" + WFS_BEANS_REGEX; @Bean @Autowired diff --git a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/event/BlobStoreEvent.java b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/event/BlobStoreEvent.java index 4b2bb5bf9..740b22707 100644 --- a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/event/BlobStoreEvent.java +++ b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/event/BlobStoreEvent.java @@ -27,8 +27,7 @@ public BlobStoreEvent(Object source, @NonNull Type eventType, @NonNull String bl this.blobStoreId = blobStoreName; } - public BlobStoreEvent( - Object source, @NonNull Type eventType, String oldName, @NonNull String blobStoreName) { + public BlobStoreEvent(Object source, @NonNull Type eventType, String oldName, @NonNull String blobStoreName) { super(source, eventType); this.oldName = oldName; this.blobStoreId = blobStoreName; diff --git a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/event/GeoWebCacheEvent.java b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/event/GeoWebCacheEvent.java index e684475d0..d7f26b9be 100644 --- a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/event/GeoWebCacheEvent.java +++ b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/event/GeoWebCacheEvent.java @@ -7,7 +7,6 @@ import lombok.Getter; import lombok.NonNull; import lombok.Setter; - import org.geoserver.gwc.layer.TileLayerCatalogListener; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationEvent; @@ -43,12 +42,7 @@ protected GeoWebCacheEvent(Object source, Type eventType) { @Override public String toString() { return "%s[%s '%s' id: %s timestamp: %s]" - .formatted( - getClass().getSimpleName(), - getEventType(), - getObjectId(), - getId(), - getTimestamp()); + .formatted(getClass().getSimpleName(), getEventType(), getObjectId(), getId(), getTimestamp()); } protected abstract String getObjectId(); diff --git a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/event/TileLayerEvent.java b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/event/TileLayerEvent.java index d799b0d2b..f4f6b50bc 100644 --- a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/event/TileLayerEvent.java +++ b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/event/TileLayerEvent.java @@ -7,7 +7,6 @@ import lombok.Getter; import lombok.NonNull; import lombok.Setter; - import org.geoserver.gwc.layer.TileLayerCatalogListener; import org.springframework.context.ApplicationContext; import org.springframework.lang.Nullable; @@ -31,11 +30,7 @@ public TileLayerEvent(Object source) { super(source); } - public TileLayerEvent( - Object source, - @NonNull Type eventType, - @NonNull String layerId, - @NonNull String layerName) { + public TileLayerEvent(Object source, @NonNull Type eventType, @NonNull String layerId, @NonNull String layerName) { super(source, eventType); this.publishedId = layerId; this.name = layerName; @@ -52,10 +47,7 @@ public static TileLayerEvent deleted( } public static TileLayerEvent modified( - @NonNull Object source, - @NonNull String publishedId, - @NonNull String layerName, - @Nullable String oldName) { + @NonNull Object source, @NonNull String publishedId, @NonNull String layerName, @Nullable String oldName) { return valueOf(source, Type.MODIFIED, publishedId, layerName, oldName); } @@ -74,18 +66,9 @@ private static TileLayerEvent valueOf( public String toString() { if (null == getOldName()) return "%s[%s id: %s, name: %s]" - .formatted( - getClass().getSimpleName(), - getEventType(), - getPublishedId(), - getName()); + .formatted(getClass().getSimpleName(), getEventType(), getPublishedId(), getName()); return "%s[%s id: %s, name: %s, oldname: %s]" - .formatted( - getClass().getSimpleName(), - getEventType(), - getPublishedId(), - getName(), - getOldName()); + .formatted(getClass().getSimpleName(), getEventType(), getPublishedId(), getName(), getOldName()); } protected @Override String getObjectId() { diff --git a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CachingTileLayerCatalog.java b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CachingTileLayerCatalog.java index eba96f1ab..16fd6c5d6 100644 --- a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CachingTileLayerCatalog.java +++ b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CachingTileLayerCatalog.java @@ -8,10 +8,11 @@ import com.google.common.collect.BiMap; import com.google.common.collect.HashBiMap; import com.google.common.collect.Maps; - +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.Set; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.gwc.event.GeoWebCacheEvent; import org.geoserver.cloud.gwc.event.TileLayerEvent; import org.geoserver.gwc.layer.GeoServerTileLayerInfo; @@ -19,10 +20,6 @@ import org.springframework.cache.CacheManager; import org.springframework.context.event.EventListener; -import java.util.NoSuchElementException; -import java.util.Optional; -import java.util.Set; - /** * Caching decorator for {@link ResourceStoreTileLayerCatalog} using a provided Spring {@link * CacheManager}. @@ -45,8 +42,7 @@ public class CachingTileLayerCatalog extends ForwardingTileLayerCatalog { Cache idCache; final BiMap namesById = Maps.synchronizedBiMap(HashBiMap.create()); - public CachingTileLayerCatalog( - CacheManager cacheManager, ResourceStoreTileLayerCatalog delegate) { + public CachingTileLayerCatalog(CacheManager cacheManager, ResourceStoreTileLayerCatalog delegate) { super(delegate); this.cacheManager = cacheManager; } @@ -63,10 +59,7 @@ public void onTileLayerEvent(TileLayerEvent event) { if (evict(infoId)) { log.debug("Evicted GeoServerTileLayerInfo[{}] upon event {}", infoId, event); } else { - log.trace( - "Event didn't result in evicting GeoServerTileLayerInfo[{}]: {}", - infoId, - event); + log.trace("Event didn't result in evicting GeoServerTileLayerInfo[{}]: {}", infoId, event); } } @@ -183,8 +176,7 @@ public GeoServerTileLayerInfo getLayerByName(@NonNull String layerName) { * @throws NoSuchElementException to prevent caching a {@code null} value */ private GeoServerTileLayerInfo loadLayerById(String id) { - return Optional.ofNullable(super.getLayerById(id)) - .orElseThrow(() -> new NoSuchElementException(id)); + return Optional.ofNullable(super.getLayerById(id)).orElseThrow(() -> new NoSuchElementException(id)); } /** @@ -193,7 +185,6 @@ private GeoServerTileLayerInfo loadLayerById(String id) { * @throws NoSuchElementException to prevent caching a {@code null} value */ private GeoServerTileLayerInfo loadLayerByName(String name) { - return Optional.ofNullable(super.getLayerByName(name)) - .orElseThrow(() -> new NoSuchElementException(name)); + return Optional.ofNullable(super.getLayerByName(name)).orElseThrow(() -> new NoSuchElementException(name)); } } diff --git a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CloudCatalogConfiguration.java b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CloudCatalogConfiguration.java index 052c6a240..ef3ac6590 100644 --- a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CloudCatalogConfiguration.java +++ b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CloudCatalogConfiguration.java @@ -8,10 +8,10 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.cache.LoadingCache; - +import java.util.List; +import java.util.Set; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.apache.commons.lang3.reflect.FieldUtils; import org.geoserver.catalog.Catalog; import org.geoserver.catalog.PublishedInfo; @@ -31,9 +31,6 @@ import org.geowebcache.layer.TileLayer; import org.springframework.context.event.EventListener; -import java.util.List; -import java.util.Set; - /** * @since 1.0 */ @@ -43,15 +40,12 @@ public class CloudCatalogConfiguration extends CatalogConfiguration { private LoadingCache spiedLayerCache; @SuppressWarnings("unchecked") - public CloudCatalogConfiguration( - Catalog catalog, TileLayerCatalog tileLayerCatalog, GridSetBroker gridSetBroker) { + public CloudCatalogConfiguration(Catalog catalog, TileLayerCatalog tileLayerCatalog, GridSetBroker gridSetBroker) { super(catalog, tileLayerCatalog, gridSetBroker); try { - spiedLayerCache = - (LoadingCache) - FieldUtils.readField(this, "layerCache", true); + spiedLayerCache = (LoadingCache) FieldUtils.readField(this, "layerCache", true); } catch (IllegalAccessException e) { throw new IllegalStateException(e); } @@ -94,8 +88,7 @@ private void completeWithDefaults(GeoServerTileLayer tileLayer) { GeoServerTileLayerInfo info = tileLayer.getInfo(); PublishedInfo publishedInfo = tileLayer.getPublishedInfo(); GWCConfig defaults = GWC.get().getConfig(); - GeoServerTileLayerInfo infoDefaults = - TileLayerInfoUtil.loadOrCreate(publishedInfo, defaults); + GeoServerTileLayerInfo infoDefaults = TileLayerInfoUtil.loadOrCreate(publishedInfo, defaults); setMissingConfig(info, infoDefaults); } @@ -118,8 +111,7 @@ private void setMissingConfig(GeoServerTileLayerInfo info, GeoServerTileLayerInf if (0 == info.getExpireCache()) info.setExpireCache(expireCache); if (null == info.getExpireCacheList()) info.setExpireCacheList(expireCacheList); if (0 == info.getExpireClients()) info.setExpireClients(expireClients); - if (null == info.getGridSubsets() || info.getGridSubsets().isEmpty()) - info.setGridSubsets(gridSubsets); + if (null == info.getGridSubsets() || info.getGridSubsets().isEmpty()) info.setGridSubsets(gridSubsets); if (0 == info.getGutter()) info.setGutter(gutter); if (0 == info.getMetaTilingX()) info.setMetaTilingX(metaTilingX); if (0 == info.getMetaTilingY()) info.setMetaTilingY(metaTilingY); diff --git a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CloudDefaultStorageFinder.java b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CloudDefaultStorageFinder.java index bf0e52b1b..1bee0519a 100644 --- a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CloudDefaultStorageFinder.java +++ b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CloudDefaultStorageFinder.java @@ -4,14 +4,13 @@ */ package org.geoserver.cloud.gwc.repository; +import java.nio.file.Path; import org.geowebcache.config.ConfigurationException; import org.geowebcache.storage.DefaultStorageFinder; import org.geowebcache.util.ApplicationContextProvider; import org.springframework.core.env.Environment; import org.springframework.web.context.WebApplicationContext; -import java.nio.file.Path; - /** * @since 1.0 */ @@ -19,13 +18,12 @@ public class CloudDefaultStorageFinder extends DefaultStorageFinder { private Environment environment; - static final ApplicationContextProvider NOOP = - new ApplicationContextProvider() { - @Override - public WebApplicationContext getApplicationContext() { - return null; - } - }; + static final ApplicationContextProvider NOOP = new ApplicationContextProvider() { + @Override + public WebApplicationContext getApplicationContext() { + return null; + } + }; private Path defaultCacheDirectory; diff --git a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CloudGwcXmlConfiguration.java b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CloudGwcXmlConfiguration.java index 46af45915..c397852ed 100644 --- a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CloudGwcXmlConfiguration.java +++ b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CloudGwcXmlConfiguration.java @@ -8,9 +8,18 @@ import static org.geoserver.cloud.gwc.event.GeoWebCacheEvent.Type.DELETED; import static org.geoserver.cloud.gwc.event.GeoWebCacheEvent.Type.MODIFIED; +import java.io.IOException; +import java.util.Collection; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.locks.ReadWriteLock; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.function.Consumer; +import java.util.function.Supplier; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.apache.commons.lang3.reflect.FieldUtils; import org.geoserver.cloud.gwc.event.BlobStoreEvent; import org.geoserver.cloud.gwc.event.GeoWebCacheEvent; @@ -28,17 +37,6 @@ import org.geowebcache.util.ApplicationContextProvider; import org.springframework.context.event.EventListener; -import java.io.IOException; -import java.util.Collection; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.locks.ReadWriteLock; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.function.Consumer; -import java.util.function.Supplier; - /** * @implNote there is a {@link BlobStoreConfigurationListener} abstraction, but no homologous one to * listen to gridset configuration changes, so for the sake of consistency, we're overriding the @@ -70,9 +68,8 @@ public CloudGwcXmlConfiguration( // this.publisher = publisher; try { - spiedListeners = - (ListenerCollection) - FieldUtils.readField(this, "blobStoreListeners", true); + spiedListeners = (ListenerCollection) + FieldUtils.readField(this, "blobStoreListeners", true); } catch (IllegalAccessException e) { throw new IllegalStateException(e); @@ -113,8 +110,7 @@ public boolean onBlobStoreEvent(BlobStoreEvent event) throws Exception { if (null == oldName) { spiedListeners.safeForEach(l -> l.handleModifyBlobStore(post.orElseThrow())); } else { - spiedListeners.safeForEach( - l -> l.handleRenameBlobStore(oldName, post.orElseThrow())); + spiedListeners.safeForEach(l -> l.handleRenameBlobStore(oldName, post.orElseThrow())); } break; default: @@ -303,8 +299,7 @@ public void modifyLayer(TileLayer tl) throws NoSuchElementException { } @Override - public void renameLayer(String oldName, String newName) - throws NoSuchElementException, IllegalArgumentException { + public void renameLayer(String oldName, String newName) throws NoSuchElementException, IllegalArgumentException { lock.writeLock().lock(); try { super.renameLayer(oldName, newName); @@ -314,8 +309,7 @@ public void renameLayer(String oldName, String newName) } @Override - public void removeLayer(final String layerName) - throws NoSuchElementException, IllegalArgumentException { + public void removeLayer(final String layerName) throws NoSuchElementException, IllegalArgumentException { lock.writeLock().lock(); try { super.removeLayer(layerName); diff --git a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CloudXMLResourceProvider.java b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CloudXMLResourceProvider.java index eb97c44fd..d396788c7 100644 --- a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CloudXMLResourceProvider.java +++ b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/CloudXMLResourceProvider.java @@ -4,16 +4,6 @@ */ package org.geoserver.cloud.gwc.repository; -import lombok.NonNull; -import lombok.extern.slf4j.Slf4j; - -import org.geoserver.platform.resource.Resource; -import org.geoserver.platform.resource.ResourceStore; -import org.geoserver.platform.resource.Resources; -import org.geoserver.util.IOUtils; -import org.geowebcache.config.ConfigurationException; -import org.geowebcache.config.ConfigurationResourceProvider; - import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; @@ -23,6 +13,14 @@ import java.util.List; import java.util.Objects; import java.util.function.Supplier; +import lombok.NonNull; +import lombok.extern.slf4j.Slf4j; +import org.geoserver.platform.resource.Resource; +import org.geoserver.platform.resource.ResourceStore; +import org.geoserver.platform.resource.Resources; +import org.geoserver.util.IOUtils; +import org.geowebcache.config.ConfigurationException; +import org.geowebcache.config.ConfigurationResourceProvider; /** * @since 1.0 @@ -115,26 +113,19 @@ private void backUpConfig(final Resource xmlFile) throws IOException { log.debug("Backing up config file {} to {}", xmlFile.name(), backUpFileName); - List previousBackUps = - Resources.list( - parentFile, - res -> { - String name = res.name(); - if (configFileName.equals(name)) { - return false; - } - return name.startsWith(configFileName) && name.endsWith(".bak"); - }); + List previousBackUps = Resources.list(parentFile, res -> { + String name = res.name(); + if (configFileName.equals(name)) { + return false; + } + return name.startsWith(configFileName) && name.endsWith(".bak"); + }); final int maxBackups = 10; if (previousBackUps.size() > maxBackups) { - Collections.sort( - previousBackUps, (o1, o2) -> (int) (o1.lastmodified() - o2.lastmodified())); + Collections.sort(previousBackUps, (o1, o2) -> (int) (o1.lastmodified() - o2.lastmodified())); Resource oldest = previousBackUps.get(0); - log.debug( - "Deleting oldest config backup {} to keep a maximum of {} backups.", - oldest, - maxBackups); + log.debug("Deleting oldest config backup {} to keep a maximum of {} backups.", oldest, maxBackups); oldest.delete(); } diff --git a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/ForwardingTileLayerCatalog.java b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/ForwardingTileLayerCatalog.java index d81a7572f..6439db4d3 100644 --- a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/ForwardingTileLayerCatalog.java +++ b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/ForwardingTileLayerCatalog.java @@ -8,7 +8,6 @@ import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.experimental.Delegate; - import org.geoserver.gwc.layer.TileLayerCatalog; /** Base class for {@link TileLayerCatalog} decorators */ @@ -16,5 +15,8 @@ public abstract class ForwardingTileLayerCatalog implements TileLayerCatalog { /** Note all {@link TileLayerCatalog} methods are delegated to this subject */ - @Getter @Delegate @NonNull protected final TileLayerCatalog delegate; + @Getter + @Delegate + @NonNull + protected final TileLayerCatalog delegate; } diff --git a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/ForwardingTileLayerConfiguration.java b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/ForwardingTileLayerConfiguration.java index f340f511f..53f23d79d 100644 --- a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/ForwardingTileLayerConfiguration.java +++ b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/ForwardingTileLayerConfiguration.java @@ -8,7 +8,6 @@ import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.experimental.Delegate; - import org.geowebcache.config.TileLayerConfiguration; /** Base class for {@link TileLayerConfiguration} decorators */ @@ -16,5 +15,8 @@ public class ForwardingTileLayerConfiguration implements TileLayerConfiguration { /** Note all {@link TileLayerConfiguration} methods are delegated to this subject */ - @Getter @Delegate @NonNull private final TileLayerConfiguration subject; + @Getter + @Delegate + @NonNull + private final TileLayerConfiguration subject; } diff --git a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/GeoServerTileLayerConfiguration.java b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/GeoServerTileLayerConfiguration.java index 539a8e936..cdab589ac 100644 --- a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/GeoServerTileLayerConfiguration.java +++ b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/GeoServerTileLayerConfiguration.java @@ -4,8 +4,9 @@ */ package org.geoserver.cloud.gwc.repository; +import java.util.Optional; +import java.util.function.Consumer; import lombok.NonNull; - import org.geoserver.catalog.Catalog; import org.geoserver.cloud.gwc.event.TileLayerEvent; import org.geoserver.gwc.layer.GeoServerTileLayer; @@ -13,9 +14,6 @@ import org.geowebcache.layer.TileLayer; import org.springframework.context.event.EventListener; -import java.util.Optional; -import java.util.function.Consumer; - /** * GeoWebCache {@link TileLayerConfiguration} decorator to publish {@link TileLayerEvent}s. * @@ -29,14 +27,16 @@ public class GeoServerTileLayerConfiguration extends ForwardingTileLayerConfigur /** * Event publisher, used to send events whenever a {@code TileLayer} is added, changed, deleted. */ - @NonNull private Consumer eventPublisher; + @NonNull + private Consumer eventPublisher; /** * Consumer of incoming events. * * @see #setEventListener */ - @NonNull private Consumer eventConsumer = e -> {}; + @NonNull + private Consumer eventConsumer = e -> {}; public GeoServerTileLayerConfiguration( @NonNull TileLayerConfiguration subject, Consumer eventPublisher) { diff --git a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/ResourceStoreTileLayerCatalog.java b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/ResourceStoreTileLayerCatalog.java index 34d0482c7..3b55b1d9e 100644 --- a/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/ResourceStoreTileLayerCatalog.java +++ b/src/gwc/core/src/main/java/org/geoserver/cloud/gwc/repository/ResourceStoreTileLayerCatalog.java @@ -9,27 +9,6 @@ import com.google.common.base.Preconditions; import com.google.common.collect.Streams; import com.thoughtworks.xstream.XStream; - -import lombok.NonNull; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; - -import org.geoserver.config.util.SecureXStream; -import org.geoserver.gwc.layer.DefaultTileLayerCatalog; -import org.geoserver.gwc.layer.GeoServerTileLayerInfo; -import org.geoserver.gwc.layer.TileLayerCatalog; -import org.geoserver.gwc.layer.TileLayerCatalogListener; -import org.geoserver.gwc.layer.TileLayerCatalogListener.Type; -import org.geoserver.platform.resource.FileSystemResourceStore; -import org.geoserver.platform.resource.Resource; -import org.geoserver.platform.resource.ResourceStore; -import org.geoserver.platform.resource.Resources; -import org.geoserver.util.DimensionWarning; -import org.geowebcache.config.ContextualConfigurationProvider.Context; -import org.geowebcache.config.XMLConfiguration; -import org.geowebcache.storage.blobstore.file.FilePathUtils; -import org.springframework.web.context.WebApplicationContext; - import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; @@ -54,6 +33,24 @@ import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.geoserver.config.util.SecureXStream; +import org.geoserver.gwc.layer.DefaultTileLayerCatalog; +import org.geoserver.gwc.layer.GeoServerTileLayerInfo; +import org.geoserver.gwc.layer.TileLayerCatalog; +import org.geoserver.gwc.layer.TileLayerCatalogListener; +import org.geoserver.gwc.layer.TileLayerCatalogListener.Type; +import org.geoserver.platform.resource.FileSystemResourceStore; +import org.geoserver.platform.resource.Resource; +import org.geoserver.platform.resource.ResourceStore; +import org.geoserver.platform.resource.Resources; +import org.geoserver.util.DimensionWarning; +import org.geowebcache.config.ContextualConfigurationProvider.Context; +import org.geowebcache.config.XMLConfiguration; +import org.geowebcache.storage.blobstore.file.FilePathUtils; +import org.springframework.web.context.WebApplicationContext; /** * {@link TileLayerCatalog} compatible with {@link DefaultTileLayerCatalog} in that it'll read from @@ -98,12 +95,8 @@ public void reset() { public void initialize() { if (initialized.compareAndSet(false, true)) { this.baseDirectory = "gwc-layers"; - this.xstreamProvider = - () -> - XMLConfiguration.getConfiguredXStreamWithContext( - new SecureXStream(), - applicationContext.orElse(null), - Context.PERSIST); + this.xstreamProvider = () -> XMLConfiguration.getConfiguredXStreamWithContext( + new SecureXStream(), applicationContext.orElse(null), Context.PERSIST); this.serializer = newXStream(); } } @@ -217,8 +210,7 @@ public String getPersistenceLocation() { * @throws IllegalStateException if this layer catalog has not been initialized yet */ private void checkInitialized() { - Preconditions.checkState( - this.initialized.get(), "DefaultTileLayerCatalog is not initialized"); + Preconditions.checkState(this.initialized.get(), "DefaultTileLayerCatalog is not initialized"); } private Resource baseDirectory() { @@ -284,8 +276,7 @@ private Stream findAllTileLayerResources() { private Stream findAllTileLayerResources(Path basePath) { final PathMatcher matcher = basePath.getFileSystem().getPathMatcher("glob:**.xml"); - DirectoryStream.Filter filter = - path -> matcher.matches(path) && Files.isRegularFile(path); + DirectoryStream.Filter filter = path -> matcher.matches(path) && Files.isRegularFile(path); DirectoryStream directoryStream; try { directoryStream = Files.newDirectoryStream(basePath, filter); @@ -298,11 +289,10 @@ private Stream findAllTileLayerResources(Path basePath) { .onClose(() -> closeSilently(directoryStream)) .map(Path::getFileName) .map(Path::toString) - .map( - name -> { - log.trace("found potential tile layer file {}", name); - return baseDir.get(name); - }); + .map(name -> { + log.trace("found potential tile layer file {}", name); + return baseDir.get(name); + }); } private void closeSilently(DirectoryStream directoryStream) { @@ -337,12 +327,7 @@ private void notify(TileLayerCatalogListener l, String layerId, Type eventType) l.onEvent(layerId, eventType); } catch (RuntimeException e) { String listener = l == null ? null : l.getClass().getCanonicalName(); - log.warn( - "Error notifying listener of {} change event for TileLayer {}", - listener, - eventType, - layerId, - e); + log.warn("Error notifying listener of {} change event for TileLayer {}", listener, eventType, layerId, e); } } diff --git a/src/gwc/core/src/main/java/org/geoserver/gwc/config/AbstractGwcInitializer.java b/src/gwc/core/src/main/java/org/geoserver/gwc/config/AbstractGwcInitializer.java index 3bdd25f36..d49b4268b 100644 --- a/src/gwc/core/src/main/java/org/geoserver/gwc/config/AbstractGwcInitializer.java +++ b/src/gwc/core/src/main/java/org/geoserver/gwc/config/AbstractGwcInitializer.java @@ -7,10 +7,14 @@ import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Stopwatch; - +import java.io.IOException; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.GeoServerConfigurationLock; import org.geoserver.GeoServerConfigurationLock.LockType; import org.geoserver.cloud.gwc.event.TileLayerEvent; @@ -33,13 +37,6 @@ import org.springframework.context.event.EventListener; import org.springframework.util.StringUtils; -import java.io.IOException; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - /** * Base class for replacements of {@link GWCInitializer}. * @@ -108,9 +105,7 @@ private void initializeGeoServerIntegrationConfigFile() throws IOException { if (configFileExists()) { updateLockProviderName(); } else { - logger().info( - "Initializing GeoServer specific GWC configuration {}", - configPersister.findConfigFile()); + logger().info("Initializing GeoServer specific GWC configuration {}", configPersister.findConfigFile()); GWCConfig defaults = new GWCConfig(); defaults.setVersion("1.1.0"); defaults.setLockProviderName(GWC_LOCK_PROVIDER_BEAN_NAME); @@ -131,9 +126,7 @@ private void updateLockProviderName() throws IOException { final GWCConfig gwcConfig = configPersister.getConfig(); if (!GWC_LOCK_PROVIDER_BEAN_NAME.equals(gwcConfig.getLockProviderName())) { if (null == gwcConfig.getLockProviderName()) { - logger().info( - "Setting GeoWebCache lock provider to {}", - GWC_LOCK_PROVIDER_BEAN_NAME); + logger().info("Setting GeoWebCache lock provider to {}", GWC_LOCK_PROVIDER_BEAN_NAME); } else { logger().warn( "Updating GeoWebCache lock provider from {} to {}", @@ -160,18 +153,13 @@ private void onTileLayerEvent(TileLayerEvent event, CacheProvider cache) { switch (event.getEventType()) { case DELETED: - logger().debug( - "TileLayer {} deleted, notifying in-memory CacheProvider", - layerName); + logger().debug("TileLayer {} deleted, notifying in-memory CacheProvider", layerName); cache.removeUncachedLayer(layerName); break; case MODIFIED: if (isRename(event)) { String oldName = event.getOldName(); - logger().info( - "TileLayer {} renamed to {}, notifying in-memory CacheProvider", - oldName, - layerName); + logger().info("TileLayer {} renamed to {}, notifying in-memory CacheProvider", oldName, layerName); cache.removeUncachedLayer(oldName); } setInMemoryLayerCaching(layerName); @@ -218,27 +206,20 @@ private void configureInMemoryCacheProvider(final GWCConfig gwcConfig) throws IO private void setInMemoryLayerCaching(@NonNull String layerName) { - layer(layerName) - .ifPresentOrElse(this::addUncachedLayer, () -> removeCachedLayer(layerName)); + layer(layerName).ifPresentOrElse(this::addUncachedLayer, () -> removeCachedLayer(layerName)); } private void removeCachedLayer(String layerName) { - cacheProvider() - .ifPresent( - cache -> { - logger().debug( - "TileLayer {} does not exist, notifying CacheProvider", - layerName); - cache.removeLayer(layerName); - cache.removeUncachedLayer(layerName); - }); + cacheProvider().ifPresent(cache -> { + logger().debug("TileLayer {} does not exist, notifying CacheProvider", layerName); + cache.removeLayer(layerName); + cache.removeUncachedLayer(layerName); + }); } private void addUncachedLayer(GeoServerTileLayer tl) { if (!tl.getInfo().isInMemoryCached()) { - logger().debug( - "TileLayer {} is not to be memory cached, notifying CacheProvider", - tl.getName()); + logger().debug("TileLayer {} is not to be memory cached, notifying CacheProvider", tl.getName()); cacheProvider().ifPresent(cache -> cache.addUncachedLayer(tl.getName())); } } @@ -255,23 +236,21 @@ private Optional layer(String layerName) { * instance. */ private void setUpNonMemoryCacheableLayers() { - cacheProvider() - .ifPresent( - cache -> { - // Add all the various Layers to avoid caching - logger().info("Adding Layers to avoid In Memory Caching"); - // it is ok to use the ForkJoinPool.commonPool() here, there's no I/O - // involved - Stopwatch sw = Stopwatch.createStarted(); - Collection layers = geoseverTileLayers.getLayers(); - logger().info("Queried {} tile layers in {}", layers.size(), sw.stop()); - layers.stream() - .filter(GeoServerTileLayer.class::isInstance) - .map(GeoServerTileLayer.class::cast) - .filter(l -> l.isEnabled() && !l.getInfo().isInMemoryCached()) - .map(GeoServerTileLayer::getName) - .forEach(cache::addUncachedLayer); - }); + cacheProvider().ifPresent(cache -> { + // Add all the various Layers to avoid caching + logger().info("Adding Layers to avoid In Memory Caching"); + // it is ok to use the ForkJoinPool.commonPool() here, there's no I/O + // involved + Stopwatch sw = Stopwatch.createStarted(); + Collection layers = geoseverTileLayers.getLayers(); + logger().info("Queried {} tile layers in {}", layers.size(), sw.stop()); + layers.stream() + .filter(GeoServerTileLayer.class::isInstance) + .map(GeoServerTileLayer.class::cast) + .filter(l -> l.isEnabled() && !l.getInfo().isInMemoryCached()) + .map(GeoServerTileLayer::getName) + .forEach(cache::addUncachedLayer); + }); } private Optional cacheProvider() { diff --git a/src/gwc/core/src/main/java/org/geoserver/gwc/config/CloudGwcConfigPersister.java b/src/gwc/core/src/main/java/org/geoserver/gwc/config/CloudGwcConfigPersister.java index 54733386e..629a669c1 100644 --- a/src/gwc/core/src/main/java/org/geoserver/gwc/config/CloudGwcConfigPersister.java +++ b/src/gwc/core/src/main/java/org/geoserver/gwc/config/CloudGwcConfigPersister.java @@ -5,9 +5,13 @@ package org.geoserver.gwc.config; import com.thoughtworks.xstream.XStream; - +import java.io.IOException; +import java.io.InputStream; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.Set; +import java.util.function.Consumer; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.gwc.event.ConfigChangeEvent; import org.geoserver.config.util.XStreamPersister; import org.geoserver.config.util.XStreamPersisterFactory; @@ -20,13 +24,6 @@ import org.geowebcache.storage.blobstore.memory.CacheConfiguration; import org.springframework.context.event.EventListener; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.Set; -import java.util.function.Consumer; - /** * extends {@link GWCConfigPersister} to send {@link ConfigChangeEvent}s upon {@link * #save(org.geoserver.gwc.config.GWCConfig)} @@ -91,8 +88,7 @@ public void reloadOnRemoteConfigChangeEvent(ConfigChangeEvent event) throws IOEx private synchronized GWCConfig reload() throws IOException { Resource configFile = findConfigFile(); if (configFile == null || configFile.getType() == Type.UNDEFINED) { - throw new IllegalStateException( - "gwc config resource does not exist: %s".formatted(GWC_CONFIG_FILE)); + throw new IllegalStateException("gwc config resource does not exist: %s".formatted(GWC_CONFIG_FILE)); } XStreamPersister xmlPersister = this.xspf.createXMLPersister(); @@ -111,10 +107,7 @@ private void configure(XStream xs) { xs.alias("defaultOtherCacheFormats", HashSet.class); xs.alias("InnerCacheConfiguration", CacheConfiguration.class); xs.alias("warning", DimensionWarning.WarningType.class); - xs.allowTypes( - new Class[] { - GWCConfig.class, CacheConfiguration.class, DimensionWarning.WarningType.class - }); + xs.allowTypes(new Class[] {GWCConfig.class, CacheConfiguration.class, DimensionWarning.WarningType.class}); xs.addDefaultImplementation(LinkedHashSet.class, Set.class); } } diff --git a/src/gwc/core/src/main/java/org/geoserver/gwc/config/DefaultGwcInitializer.java b/src/gwc/core/src/main/java/org/geoserver/gwc/config/DefaultGwcInitializer.java index 01c79b31d..d0d26a75a 100644 --- a/src/gwc/core/src/main/java/org/geoserver/gwc/config/DefaultGwcInitializer.java +++ b/src/gwc/core/src/main/java/org/geoserver/gwc/config/DefaultGwcInitializer.java @@ -6,7 +6,6 @@ import lombok.NonNull; import lombok.extern.slf4j.Slf4j; - import org.geoserver.GeoServerConfigurationLock; import org.geoserver.cloud.gwc.repository.GeoServerTileLayerConfiguration; import org.geoserver.gwc.ConfigurableBlobStore; diff --git a/src/gwc/core/src/test/java/org/geoserver/cloud/gwc/repository/CachingTileLayerCatalogTest.java b/src/gwc/core/src/test/java/org/geoserver/cloud/gwc/repository/CachingTileLayerCatalogTest.java index aafefa385..33c85c81b 100644 --- a/src/gwc/core/src/test/java/org/geoserver/cloud/gwc/repository/CachingTileLayerCatalogTest.java +++ b/src/gwc/core/src/test/java/org/geoserver/cloud/gwc/repository/CachingTileLayerCatalogTest.java @@ -8,6 +8,9 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import java.io.File; +import java.util.Map; +import java.util.Optional; import org.geoserver.cloud.gwc.event.TileLayerEvent; import org.geoserver.gwc.layer.GWCGeoServerConfigurationProvider; import org.geoserver.gwc.layer.GeoServerTileLayerInfo; @@ -24,10 +27,6 @@ import org.springframework.cache.caffeine.CaffeineCacheManager; import org.springframework.web.context.WebApplicationContext; -import java.io.File; -import java.util.Map; -import java.util.Optional; - class CachingTileLayerCatalogTest { private CachingTileLayerCatalog caching; @@ -45,8 +44,7 @@ void beforeEach() { WebApplicationContext context = mock(WebApplicationContext.class); - Map configProviders = - Map.of("gs", new GWCGeoServerConfigurationProvider()); + Map configProviders = Map.of("gs", new GWCGeoServerConfigurationProvider()); when(context.getBeansOfType(XMLConfigurationProvider.class)).thenReturn(configProviders); when(context.getBean("gs")).thenReturn(configProviders.get("gs")); @@ -91,21 +89,19 @@ public void reset() { public void onTileLayerEvent() { final String origName = "origName"; final String newName = "newName"; - catalog.addListener( - new TileLayerCatalogListener() { - @Override - public void onEvent(String layerId, Type type) { - TileLayerEvent event = - switch (type) { - case CREATE -> TileLayerEvent.created(this, layerId, origName); - case MODIFY -> TileLayerEvent.modified( - this, layerId, newName, origName); - case DELETE -> TileLayerEvent.deleted(this, layerId, newName); - default -> throw new IllegalStateException(); - }; - caching.onTileLayerEvent(event); - } - }); + catalog.addListener(new TileLayerCatalogListener() { + @Override + public void onEvent(String layerId, Type type) { + TileLayerEvent event = + switch (type) { + case CREATE -> TileLayerEvent.created(this, layerId, origName); + case MODIFY -> TileLayerEvent.modified(this, layerId, newName, origName); + case DELETE -> TileLayerEvent.deleted(this, layerId, newName); + default -> throw new IllegalStateException(); + }; + caching.onTileLayerEvent(event); + } + }); // do crud ops bypassing the caching decorator, expect the events have the desired effect assertThat(caching.idCache.get("tl1")).isNull(); @@ -114,7 +110,9 @@ public void onEvent(String layerId, Type type) { .as("create event should have added the id->name mapping") .isNotNull() .isEqualTo(origName); - assertThat(caching.idCache.get("tl1")).as("create event doesn't cache a value").isNull(); + assertThat(caching.idCache.get("tl1")) + .as("create event doesn't cache a value") + .isNull(); // force caching the entry caching.getLayerById("tl1"); @@ -127,14 +125,16 @@ public void onEvent(String layerId, Type type) { .as("update event should have updated the id->name mapping") .isEqualTo(newName); - assertThat(caching.idCache.get("tl1")).as("update event should have evicted").isNull(); + assertThat(caching.idCache.get("tl1")) + .as("update event should have evicted") + .isNull(); - assertThat(caching.getLayerById("tl1")) - .isNotNull() - .hasFieldOrPropertyWithValue("name", newName); + assertThat(caching.getLayerById("tl1")).isNotNull().hasFieldOrPropertyWithValue("name", newName); catalog.delete(tl1.getId()); - assertThat(caching.idCache.get("tl1")).as("delete event should have evicted").isNull(); + assertThat(caching.idCache.get("tl1")) + .as("delete event should have evicted") + .isNull(); assertThat(caching.namesById.get("tl1")).isNull(); } @@ -171,13 +171,15 @@ public void save() { caching.save(tl); assertThat(catalog.getLayerById(tl.getId())).isNotSameAs(tl).isEqualTo(tl); - assertThat(caching.idCache.get(tl.getId(), GeoServerTileLayerInfo.class)).isEqualTo(tl); + assertThat(caching.idCache.get(tl.getId(), GeoServerTileLayerInfo.class)) + .isEqualTo(tl); tl.setName("newname"); caching.save(tl); assertThat(caching.namesById.get(tl.getId())).isEqualTo("newname"); - assertThat(caching.idCache.get(tl.getId(), GeoServerTileLayerInfo.class)).isEqualTo(tl); + assertThat(caching.idCache.get(tl.getId(), GeoServerTileLayerInfo.class)) + .isEqualTo(tl); assertThat(catalog.getLayerById(tl.getId())).isNotSameAs(tl).isEqualTo(tl); } @@ -222,9 +224,7 @@ public void getLayerById() { add(catalog, "tl1", "name1"); add(catalog, "tl2", "name2"); - assertThat(caching.getLayerById("tl1")) - .isNotNull() - .hasFieldOrPropertyWithValue("name", "name1"); + assertThat(caching.getLayerById("tl1")).isNotNull().hasFieldOrPropertyWithValue("name", "name1"); assertThat(caching.getLayerById("tl3")).isNull(); } @@ -234,15 +234,11 @@ public void getLayerByName() { add(catalog, "tl1", "name1"); add(catalog, "tl2", "name2"); - assertThat(caching.getLayerByName("name1")) - .isNotNull() - .hasFieldOrPropertyWithValue("id", "tl1"); + assertThat(caching.getLayerByName("name1")).isNotNull().hasFieldOrPropertyWithValue("id", "tl1"); // simulate a cache evicted, id to name mapping exists but layer is not cached caching.namesById.put("tl2", "name2"); - assertThat(caching.getLayerByName("name2")) - .isNotNull() - .hasFieldOrPropertyWithValue("id", "tl2"); + assertThat(caching.getLayerByName("name2")).isNotNull().hasFieldOrPropertyWithValue("id", "tl2"); assertThat(caching.getLayerByName("name3")).isNull(); } diff --git a/src/gwc/core/src/test/java/org/geoserver/cloud/gwc/repository/CloudGwcXmlConfigurationTest.java b/src/gwc/core/src/test/java/org/geoserver/cloud/gwc/repository/CloudGwcXmlConfigurationTest.java index 6b8a75c53..80b782964 100644 --- a/src/gwc/core/src/test/java/org/geoserver/cloud/gwc/repository/CloudGwcXmlConfigurationTest.java +++ b/src/gwc/core/src/test/java/org/geoserver/cloud/gwc/repository/CloudGwcXmlConfigurationTest.java @@ -16,6 +16,12 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Set; +import java.util.concurrent.atomic.AtomicReference; import org.geoserver.cloud.gwc.event.BlobStoreEvent; import org.geoserver.cloud.gwc.event.GeoWebCacheEvent; import org.geoserver.cloud.gwc.event.GridsetEvent; @@ -34,13 +40,6 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import java.util.Set; -import java.util.concurrent.atomic.AtomicReference; - /** * @since 1.0 */ @@ -68,15 +67,10 @@ void setUp() throws IOException, GeoWebCacheException { private CloudGwcXmlConfiguration createStubConfig() throws GeoWebCacheException { ApplicationContextProvider appCtx = mock(ApplicationContextProvider.class); - ConfigurationResourceProvider inFac = - new XMLFileResourceProvider( - "geowebcache.xml", - appCtx, - tmpdir.toAbsolutePath().toString(), - (DefaultStorageFinder) null); + ConfigurationResourceProvider inFac = new XMLFileResourceProvider( + "geowebcache.xml", appCtx, tmpdir.toAbsolutePath().toString(), (DefaultStorageFinder) null); - CloudGwcXmlConfiguration xmlConfig = - new CloudGwcXmlConfiguration(appCtx, inFac, mockEventPublisher::set); + CloudGwcXmlConfiguration xmlConfig = new CloudGwcXmlConfiguration(appCtx, inFac, mockEventPublisher::set); GridSetBroker broker = new GridSetBroker(List.of(defaultGridsets)); xmlConfig.setGridSetBroker(broker); xmlConfig.afterPropertiesSet(); @@ -174,9 +168,7 @@ void testBlobStoreRemove() { @Test void testOnGridsetEvent_ignore_self_issued_event() throws Exception { // if event.getSource() == config, ignore it - assertFalse( - config.onGridsetEvent(new GridsetEvent(config)), - "self issued event should be ignored"); + assertFalse(config.onGridsetEvent(new GridsetEvent(config)), "self issued event should be ignored"); } @Test diff --git a/src/gwc/core/src/test/java/org/geoserver/cloud/gwc/repository/ResourceStoreTileLayerCatalogTest.java b/src/gwc/core/src/test/java/org/geoserver/cloud/gwc/repository/ResourceStoreTileLayerCatalogTest.java index 1834e6889..ea5a17451 100644 --- a/src/gwc/core/src/test/java/org/geoserver/cloud/gwc/repository/ResourceStoreTileLayerCatalogTest.java +++ b/src/gwc/core/src/test/java/org/geoserver/cloud/gwc/repository/ResourceStoreTileLayerCatalogTest.java @@ -14,6 +14,16 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.io.FileUtils; import org.geoserver.catalog.impl.ModificationProxy; import org.geoserver.gwc.layer.GWCGeoServerConfigurationProvider; @@ -31,17 +41,6 @@ import org.xmlunit.assertj.XmlAssert; import org.xmlunit.builder.Input; -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.atomic.AtomicBoolean; - /** * @since 1.0 */ @@ -60,8 +59,7 @@ void setUp() { WebApplicationContext context = mock(WebApplicationContext.class); - Map configProviders = - Map.of("gs", new GWCGeoServerConfigurationProvider()); + Map configProviders = Map.of("gs", new GWCGeoServerConfigurationProvider()); when(context.getBeansOfType(XMLConfigurationProvider.class)).thenReturn(configProviders); when(context.getBean("gs")).thenReturn(configProviders.get("gs")); @@ -242,22 +240,21 @@ void testEvents() { AtomicBoolean hasBeenModified = new AtomicBoolean(false); AtomicBoolean hasBeenDeleted = new AtomicBoolean(false); - catalog.addListener( - (layerId, type) -> { - switch (type) { - case CREATE: - hasBeenCreated.set(true); - break; - case DELETE: - hasBeenDeleted.set(true); - break; - case MODIFY: - hasBeenModified.set(true); - break; - default: - break; - } - }); + catalog.addListener((layerId, type) -> { + switch (type) { + case CREATE: + hasBeenCreated.set(true); + break; + case DELETE: + hasBeenDeleted.set(true); + break; + case MODIFY: + hasBeenModified.set(true); + break; + default: + break; + } + }); final GeoServerTileLayerInfo l = new GeoServerTileLayerInfoImpl(); l.setId("l1"); @@ -318,8 +315,7 @@ void testSavedXML() throws IOException { catalog.save(original); String actual = - FileUtils.readFileToString( - new File(baseDirectory, "gwc-layers/id1.xml"), StandardCharsets.UTF_8); + FileUtils.readFileToString(new File(baseDirectory, "gwc-layers/id1.xml"), StandardCharsets.UTF_8); String expected = """ diff --git a/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/GeoWebCacheRemoteEventsBroker.java b/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/GeoWebCacheRemoteEventsBroker.java index a34d0622f..6faaa0863 100644 --- a/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/GeoWebCacheRemoteEventsBroker.java +++ b/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/GeoWebCacheRemoteEventsBroker.java @@ -4,10 +4,12 @@ */ package org.geoserver.cloud.gwc.bus; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; - import org.geoserver.catalog.CatalogException; import org.geoserver.cloud.gwc.event.GeoWebCacheEvent; import org.mapstruct.factory.Mappers; @@ -15,10 +17,6 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.event.EventListener; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Supplier; - /** * Listens to local {@link GeoWebCacheEvent}s produced by this service instance and broadcasts them * to the cluster as {@link RemoteGeoWebCacheEvent} on the event bus, and vice-versa. diff --git a/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteBlobStoreEvent.java b/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteBlobStoreEvent.java index 70ca071b1..25fe7f7c9 100644 --- a/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteBlobStoreEvent.java +++ b/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteBlobStoreEvent.java @@ -27,10 +27,7 @@ public RemoteBlobStoreEvent(Object source, @NonNull String originService) { } public RemoteBlobStoreEvent( - Object source, - @NonNull String originService, - @NonNull String blobStoreId, - @NonNull Type eventType) { + Object source, @NonNull String originService, @NonNull String blobStoreId, @NonNull Type eventType) { super(source, originService, eventType); this.blobStoreId = blobStoreId; } diff --git a/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteConfigChangeEvent.java b/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteConfigChangeEvent.java index 533494eb0..e7fe0e754 100644 --- a/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteConfigChangeEvent.java +++ b/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteConfigChangeEvent.java @@ -7,7 +7,6 @@ import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.NonNull; - import org.geoserver.cloud.gwc.event.ConfigChangeEvent; /** diff --git a/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteEventMapper.java b/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteEventMapper.java index 672a8cf0e..07e4e7789 100644 --- a/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteEventMapper.java +++ b/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteEventMapper.java @@ -6,7 +6,6 @@ import lombok.Generated; import lombok.NonNull; - import org.geoserver.cloud.gwc.event.BlobStoreEvent; import org.geoserver.cloud.gwc.event.ConfigChangeEvent; import org.geoserver.cloud.gwc.event.GeoWebCacheEvent; @@ -26,51 +25,42 @@ interface RemoteEventMapper { default RemoteGeoWebCacheEvent toRemote( - @NonNull GeoWebCacheEvent local, - @NonNull Object source, - @NonNull String originService) { + @NonNull GeoWebCacheEvent local, @NonNull Object source, @NonNull String originService) { return switch (local) { case TileLayerEvent tle -> toRemote(tle, source, originService); case GridsetEvent gse -> toRemote(gse, source, originService); case BlobStoreEvent bse -> toRemote(bse, source, originService); case ConfigChangeEvent ce -> toRemote(ce, source, originService); - default -> throw new IllegalArgumentException( - "unknown GeoWebCacheEvent type: " + local); + default -> throw new IllegalArgumentException("unknown GeoWebCacheEvent type: " + local); }; } - default GeoWebCacheEvent toLocal( - @NonNull RemoteGeoWebCacheEvent remote, @NonNull Object source) { + default GeoWebCacheEvent toLocal(@NonNull RemoteGeoWebCacheEvent remote, @NonNull Object source) { return switch (remote) { case RemoteTileLayerEvent tle -> toLocal(tle, source); case RemoteGridsetEvent gse -> toLocal(gse, source); case RemoteBlobStoreEvent bse -> toLocal(bse, source); case RemoteConfigChangeEvent ce -> toLocal(ce, source); - default -> throw new IllegalArgumentException( - "unknown RemoteGeoWebCacheEvent type: " + remote); + default -> throw new IllegalArgumentException("unknown RemoteGeoWebCacheEvent type: " + remote); }; } TileLayerEvent toLocal(RemoteTileLayerEvent remote, @Context Object source); - RemoteTileLayerEvent toRemote( - TileLayerEvent local, @Context Object source, @Context String originService); + RemoteTileLayerEvent toRemote(TileLayerEvent local, @Context Object source, @Context String originService); GridsetEvent toLocal(RemoteGridsetEvent remote, @Context Object source); - RemoteGridsetEvent toRemote( - GridsetEvent local, @Context Object source, @Context String originService); + RemoteGridsetEvent toRemote(GridsetEvent local, @Context Object source, @Context String originService); BlobStoreEvent toLocal(RemoteBlobStoreEvent remote, @Context Object source); - RemoteBlobStoreEvent toRemote( - BlobStoreEvent local, @Context Object source, @Context String originService); + RemoteBlobStoreEvent toRemote(BlobStoreEvent local, @Context Object source, @Context String originService); ConfigChangeEvent toLocal(RemoteConfigChangeEvent remote, @Context Object source); - RemoteConfigChangeEvent toRemote( - ConfigChangeEvent local, @Context Object source, @Context String originService); + RemoteConfigChangeEvent toRemote(ConfigChangeEvent local, @Context Object source, @Context String originService); @ObjectFactory default TileLayerEvent newTileEvent(@Context Object source) { @@ -78,8 +68,7 @@ default TileLayerEvent newTileEvent(@Context Object source) { } @ObjectFactory - default RemoteTileLayerEvent newRemoteTileEvent( - @Context Object source, @Context String originService) { + default RemoteTileLayerEvent newRemoteTileEvent(@Context Object source, @Context String originService) { return new RemoteTileLayerEvent(source, originService); } @@ -89,8 +78,7 @@ default GridsetEvent newGridsetEvent(@Context Object source) { } @ObjectFactory - default RemoteGridsetEvent newRemoteGridsetEvent( - @Context Object source, @Context String originService) { + default RemoteGridsetEvent newRemoteGridsetEvent(@Context Object source, @Context String originService) { return new RemoteGridsetEvent(source, originService); } @@ -100,8 +88,7 @@ default BlobStoreEvent newBlobStoreEvent(@Context Object source) { } @ObjectFactory - default RemoteBlobStoreEvent newRemoteBlobStoreEvent( - @Context Object source, @Context String originService) { + default RemoteBlobStoreEvent newRemoteBlobStoreEvent(@Context Object source, @Context String originService) { return new RemoteBlobStoreEvent(source, originService); } @@ -111,8 +98,7 @@ default ConfigChangeEvent newConfigChangeEvent(@Context Object source) { } @ObjectFactory - default RemoteConfigChangeEvent newConfigChangeEvent( - @Context Object source, @Context String originService) { + default RemoteConfigChangeEvent newConfigChangeEvent(@Context Object source, @Context String originService) { return new RemoteConfigChangeEvent(source, originService); } } diff --git a/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteGeoWebCacheEvent.java b/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteGeoWebCacheEvent.java index d59fbc62c..827b7becc 100644 --- a/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteGeoWebCacheEvent.java +++ b/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteGeoWebCacheEvent.java @@ -9,7 +9,6 @@ import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.Setter; - import org.springframework.cloud.bus.event.Destination; import org.springframework.cloud.bus.event.RemoteApplicationEvent; @@ -36,8 +35,7 @@ protected RemoteGeoWebCacheEvent(Object source, @NonNull String originService) { super(source, originService, ALL); } - protected RemoteGeoWebCacheEvent( - Object source, @NonNull String originService, @NonNull Type eventType) { + protected RemoteGeoWebCacheEvent(Object source, @NonNull String originService, @NonNull Type eventType) { super(source, originService, ALL); this.eventType = eventType; } diff --git a/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteGridsetEvent.java b/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteGridsetEvent.java index cc35dafb9..a5290f728 100644 --- a/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteGridsetEvent.java +++ b/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteGridsetEvent.java @@ -26,10 +26,7 @@ public RemoteGridsetEvent(Object source, @NonNull String originService) { } public RemoteGridsetEvent( - Object source, - @NonNull String originService, - @NonNull String gridsetId, - @NonNull Type eventType) { + Object source, @NonNull String originService, @NonNull String gridsetId, @NonNull Type eventType) { super(source, originService, eventType); this.gridsetId = gridsetId; } diff --git a/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteTileLayerEvent.java b/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteTileLayerEvent.java index ff972f505..12d0fd65c 100644 --- a/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteTileLayerEvent.java +++ b/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/bus/RemoteTileLayerEvent.java @@ -9,7 +9,6 @@ import lombok.NoArgsConstructor; import lombok.NonNull; import lombok.Setter; - import org.geoserver.gwc.layer.TileLayerCatalogListener; import org.springframework.context.ApplicationContext; diff --git a/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/config/bus/GeoWebCacheRemoteEventsConfiguration.java b/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/config/bus/GeoWebCacheRemoteEventsConfiguration.java index 970682c51..c0d2c97cf 100644 --- a/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/config/bus/GeoWebCacheRemoteEventsConfiguration.java +++ b/src/gwc/integration-bus/src/main/java/org/geoserver/cloud/gwc/config/bus/GeoWebCacheRemoteEventsConfiguration.java @@ -4,6 +4,9 @@ */ package org.geoserver.cloud.gwc.config.bus; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Supplier; import org.geoserver.cloud.gwc.bus.GeoWebCacheRemoteEventsBroker; import org.geoserver.cloud.gwc.bus.RemoteGeoWebCacheEvent; import org.springframework.boot.autoconfigure.AutoConfigureAfter; @@ -15,10 +18,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Supplier; - /** * @since 1.0 */ diff --git a/src/gwc/services/src/main/java/org/geoserver/cloud/gwc/config/services/KMLConfiguration.java b/src/gwc/services/src/main/java/org/geoserver/cloud/gwc/config/services/KMLConfiguration.java index e73225299..6137b9830 100644 --- a/src/gwc/services/src/main/java/org/geoserver/cloud/gwc/config/services/KMLConfiguration.java +++ b/src/gwc/services/src/main/java/org/geoserver/cloud/gwc/config/services/KMLConfiguration.java @@ -20,6 +20,5 @@ @ComponentScan(basePackageClasses = KMLController.class) @ImportResource( reader = FilteringXmlBeanDefinitionReader.class, - locations = - "jar:gs-gwc-[0-9]+.*!/geowebcache-kmlservice-context.xml#name=gwcServiceKMLTarget") + locations = "jar:gs-gwc-[0-9]+.*!/geowebcache-kmlservice-context.xml#name=gwcServiceKMLTarget") public class KMLConfiguration {} diff --git a/src/gwc/services/src/main/java/org/geoserver/cloud/gwc/config/services/MGMapsConfiguration.java b/src/gwc/services/src/main/java/org/geoserver/cloud/gwc/config/services/MGMapsConfiguration.java index f3f36cb68..52f39bbdc 100644 --- a/src/gwc/services/src/main/java/org/geoserver/cloud/gwc/config/services/MGMapsConfiguration.java +++ b/src/gwc/services/src/main/java/org/geoserver/cloud/gwc/config/services/MGMapsConfiguration.java @@ -20,6 +20,5 @@ @ComponentScan(basePackageClasses = MGMapsController.class) @ImportResource( reader = FilteringXmlBeanDefinitionReader.class, - locations = - "jar:gs-gwc-[0-9]+.*!/geowebcache-gmaps-context.xml#name=gwcServiceMGMapsTarget") + locations = "jar:gs-gwc-[0-9]+.*!/geowebcache-gmaps-context.xml#name=gwcServiceMGMapsTarget") public class MGMapsConfiguration {} diff --git a/src/gwc/services/src/main/java/org/gwc/web/gmaps/GoogleMapsController.java b/src/gwc/services/src/main/java/org/gwc/web/gmaps/GoogleMapsController.java index 0cd7191c4..8ab5b8775 100644 --- a/src/gwc/services/src/main/java/org/gwc/web/gmaps/GoogleMapsController.java +++ b/src/gwc/services/src/main/java/org/gwc/web/gmaps/GoogleMapsController.java @@ -4,17 +4,15 @@ */ package org.gwc.web.gmaps; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.ows.Dispatcher; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - @Controller @RequestMapping( path = { @@ -28,8 +26,7 @@ public class GoogleMapsController { private final @NonNull Dispatcher geoserverDispatcher; @GetMapping(path = "/**") - public void serviceRequest(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void serviceRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { geoserverDispatcher.handleRequest(request, response); } } diff --git a/src/gwc/services/src/main/java/org/gwc/web/kml/KMLController.java b/src/gwc/services/src/main/java/org/gwc/web/kml/KMLController.java index 0f0a8c26a..ad6adf039 100644 --- a/src/gwc/services/src/main/java/org/gwc/web/kml/KMLController.java +++ b/src/gwc/services/src/main/java/org/gwc/web/kml/KMLController.java @@ -4,32 +4,25 @@ */ package org.gwc.web.kml; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.ows.Dispatcher; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - @Controller @RequestMapping( - path = { - "/gwc/service/kml", - "/{virtualservice}/gwc/service/kml", - "/{virtualservice}/{layer}/gwc/service/kml" - }) + path = {"/gwc/service/kml", "/{virtualservice}/gwc/service/kml", "/{virtualservice}/{layer}/gwc/service/kml"}) @RequiredArgsConstructor public class KMLController { private final @NonNull Dispatcher geoserverDispatcher; @GetMapping(path = "/**") - public void serviceRequest(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void serviceRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { geoserverDispatcher.handleRequest(request, response); } } diff --git a/src/gwc/services/src/main/java/org/gwc/web/mgmaps/MGMapsController.java b/src/gwc/services/src/main/java/org/gwc/web/mgmaps/MGMapsController.java index 36ee05611..bbd62ab91 100644 --- a/src/gwc/services/src/main/java/org/gwc/web/mgmaps/MGMapsController.java +++ b/src/gwc/services/src/main/java/org/gwc/web/mgmaps/MGMapsController.java @@ -4,17 +4,15 @@ */ package org.gwc.web.mgmaps; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.ows.Dispatcher; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - @Controller @RequestMapping( path = { @@ -28,8 +26,7 @@ public class MGMapsController { private final @NonNull Dispatcher geoserverDispatcher; @GetMapping(path = "/**") - public void serviceRequest(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void serviceRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { geoserverDispatcher.handleRequest(request, response); } } diff --git a/src/gwc/services/src/main/java/org/gwc/web/rest/GeoWebCacheController.java b/src/gwc/services/src/main/java/org/gwc/web/rest/GeoWebCacheController.java index 021920b80..75b419680 100644 --- a/src/gwc/services/src/main/java/org/gwc/web/rest/GeoWebCacheController.java +++ b/src/gwc/services/src/main/java/org/gwc/web/rest/GeoWebCacheController.java @@ -4,9 +4,10 @@ */ package org.gwc.web.rest; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.gwc.dispatch.GeoServerGWCDispatcherController; import org.geowebcache.GeoWebCacheDispatcher; import org.geowebcache.controller.GeoWebCacheDispatcherController; @@ -14,9 +15,6 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - /** * Modified top-level dispatcher controller for use by GeoServer. Same as {@link * GeoWebCacheDispatcherController}, except the "/service/**" endpoint is excluded. This is handled @@ -38,8 +36,7 @@ public class GeoWebCacheController { "/demo/**", "/proxy/**", }) - public void handleGet(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void handleGet(HttpServletRequest request, HttpServletResponse response) throws Exception { gwcDispatcher.handleRequest(request, response); } } diff --git a/src/gwc/services/src/main/java/org/gwc/web/tms/TMSController.java b/src/gwc/services/src/main/java/org/gwc/web/tms/TMSController.java index d3347658a..469211a4e 100644 --- a/src/gwc/services/src/main/java/org/gwc/web/tms/TMSController.java +++ b/src/gwc/services/src/main/java/org/gwc/web/tms/TMSController.java @@ -4,32 +4,25 @@ */ package org.gwc.web.tms; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.ows.Dispatcher; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - @Controller @RequestMapping( - path = { - "/gwc/service/tms", - "/{virtualservice}/gwc/service/tms", - "/{virtualservice}/{layer}/gwc/service/tms" - }) + path = {"/gwc/service/tms", "/{virtualservice}/gwc/service/tms", "/{virtualservice}/{layer}/gwc/service/tms"}) @RequiredArgsConstructor public class TMSController { private final @NonNull Dispatcher geoserverDispatcher; @GetMapping(path = "/**") - public void serviceRequest(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void serviceRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { geoserverDispatcher.handleRequest(request, response); } } diff --git a/src/gwc/services/src/main/java/org/gwc/web/wms/WMSController.java b/src/gwc/services/src/main/java/org/gwc/web/wms/WMSController.java index dad13fade..a1fad11f1 100644 --- a/src/gwc/services/src/main/java/org/gwc/web/wms/WMSController.java +++ b/src/gwc/services/src/main/java/org/gwc/web/wms/WMSController.java @@ -4,32 +4,25 @@ */ package org.gwc.web.wms; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.ows.Dispatcher; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - @Controller @RequestMapping( - path = { - "/gwc/service/wms", - "/{virtualservice}/gwc/service/wms", - "/{virtualservice}/{layer}/gwc/service/wms" - }) + path = {"/gwc/service/wms", "/{virtualservice}/gwc/service/wms", "/{virtualservice}/{layer}/gwc/service/wms"}) @RequiredArgsConstructor public class WMSController { private final @NonNull Dispatcher geoserverDispatcher; @GetMapping(path = "/**") - public void serviceRequest(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void serviceRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { geoserverDispatcher.handleRequest(request, response); } } diff --git a/src/gwc/services/src/main/java/org/gwc/web/wmts/WMTSController.java b/src/gwc/services/src/main/java/org/gwc/web/wmts/WMTSController.java index e7de24e61..9165346e5 100644 --- a/src/gwc/services/src/main/java/org/gwc/web/wmts/WMTSController.java +++ b/src/gwc/services/src/main/java/org/gwc/web/wmts/WMTSController.java @@ -4,23 +4,18 @@ */ package org.gwc.web.wmts; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.ows.Dispatcher; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - @Controller @RequestMapping( - path = { - "/gwc/service/wmts", - "/{virtualservice}/gwc/service/wmts", - "/{virtualservice}/{layer}/gwc/service/wmts" + path = {"/gwc/service/wmts", "/{virtualservice}/gwc/service/wmts", "/{virtualservice}/{layer}/gwc/service/wmts" }) @RequiredArgsConstructor public class WMTSController { @@ -28,8 +23,7 @@ public class WMTSController { private final @NonNull Dispatcher geoserverDispatcher; @GetMapping(path = "/**") - public void serviceRequest(HttpServletRequest request, HttpServletResponse response) - throws Exception { + public void serviceRequest(HttpServletRequest request, HttpServletResponse response) throws Exception { geoserverDispatcher.handleRequest(request, response); } } diff --git a/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/autoconfigure/jndi/SimpleJNDIStaticContextInitializer.java b/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/autoconfigure/jndi/SimpleJNDIStaticContextInitializer.java index 4416db3f4..a1872aa60 100644 --- a/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/autoconfigure/jndi/SimpleJNDIStaticContextInitializer.java +++ b/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/autoconfigure/jndi/SimpleJNDIStaticContextInitializer.java @@ -4,16 +4,14 @@ */ package org.geoserver.cloud.autoconfigure.jndi; +import javax.naming.NamingException; +import javax.naming.spi.NamingManager; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.jndi.SimpleNamingContextBuilder; import org.springframework.context.ApplicationContextException; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; -import javax.naming.NamingException; -import javax.naming.spi.NamingManager; - /** * {@link ApplicationContextInitializer} setting {@link SimpleNamingContextBuilder} as the JNDI * implementation. @@ -57,8 +55,7 @@ public void initialize(ConfigurableApplicationContext applicationContext) { NamingManager.setInitialContextFactoryBuilder(new SimpleNamingContextBuilder()); log.info("Registered JNDI implementation using " + builderClassName); } catch (NamingException e) { - throw new ApplicationContextException( - "Unexpected error installing JNDI " + builderClassName, e); + throw new ApplicationContextException("Unexpected error installing JNDI " + builderClassName, e); } } } diff --git a/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/config/jndi/JNDIDataSourcesConfigurationProperties.java b/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/config/jndi/JNDIDataSourcesConfigurationProperties.java index 5c2598662..12f641ab2 100644 --- a/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/config/jndi/JNDIDataSourcesConfigurationProperties.java +++ b/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/config/jndi/JNDIDataSourcesConfigurationProperties.java @@ -4,12 +4,10 @@ */ package org.geoserver.cloud.config.jndi; -import lombok.Data; - -import org.springframework.boot.context.properties.ConfigurationProperties; - import java.util.Map; import java.util.TreeMap; +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; /** * @since 1.0 diff --git a/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/config/jndi/JNDIDatasourceConfig.java b/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/config/jndi/JNDIDatasourceConfig.java index 058ef26bd..7ccb12c2a 100644 --- a/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/config/jndi/JNDIDatasourceConfig.java +++ b/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/config/jndi/JNDIDatasourceConfig.java @@ -6,7 +6,6 @@ import lombok.Data; import lombok.EqualsAndHashCode; - import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties; /** diff --git a/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/config/jndi/JNDIInitializer.java b/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/config/jndi/JNDIInitializer.java index f1c128931..bc3c5b4ae 100644 --- a/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/config/jndi/JNDIInitializer.java +++ b/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/config/jndi/JNDIInitializer.java @@ -5,20 +5,16 @@ package org.geoserver.cloud.config.jndi; import com.zaxxer.hikari.HikariDataSource; - -import lombok.extern.slf4j.Slf4j; - -import org.springframework.beans.factory.InitializingBean; -import org.springframework.context.ApplicationContextException; -import org.springframework.jdbc.support.DatabaseStartupValidator; -import org.springframework.util.StringUtils; - import java.util.Map; - import javax.naming.Context; import javax.naming.NamingException; import javax.naming.spi.NamingManager; import javax.sql.DataSource; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.InitializingBean; +import org.springframework.context.ApplicationContextException; +import org.springframework.jdbc.support.DatabaseStartupValidator; +import org.springframework.util.StringUtils; /** * @since 1.0 @@ -36,8 +32,7 @@ public class JNDIInitializer implements InitializingBean { @Override public void afterPropertiesSet() throws Exception { - if (initialized) - throw new IllegalStateException("JNDI already initialized or failed. Giving up."); + if (initialized) throw new IllegalStateException("JNDI already initialized or failed. Giving up."); initialized = true; Map configs = config.getDatasources(); @@ -48,18 +43,15 @@ public void afterPropertiesSet() throws Exception { } // Assign the datasource a name from the mappings key - configs.entrySet() - .forEach( - e -> { - var name = e.getKey(); - var props = e.getValue(); - if (null == props.getName()) { - props.setName(name); - } - }); + configs.entrySet().forEach(e -> { + var name = e.getKey(); + var props = e.getValue(); + if (null == props.getName()) { + props.setName(name); + } + }); try { - configs.entrySet() - .forEach(e -> setUpDataSource(toJndiDatasourceName(e.getKey()), e.getValue())); + configs.entrySet().forEach(e -> setUpDataSource(toJndiDatasourceName(e.getKey()), e.getValue())); } catch (Exception e) { throw new IllegalStateException(e); } @@ -113,8 +105,7 @@ void setUpDataSource(String jndiName, JNDIDatasourceConfig props) { private void waitForIt(String jndiName, DataSource dataSource, JNDIDatasourceConfig props) { if (props.isWaitForIt()) { - log.info( - "Waiting up to {} seconds for datasource {}", props.getWaitTimeout(), jndiName); + log.info("Waiting up to {} seconds for datasource {}", props.getWaitTimeout(), jndiName); DatabaseStartupValidator validator = new DatabaseStartupValidator(); validator.setDataSource(dataSource); validator.setTimeout(props.getWaitTimeout()); @@ -123,10 +114,9 @@ private void waitForIt(String jndiName, DataSource dataSource, JNDIDatasourceCon } protected DataSource createDataSource(JNDIDatasourceConfig props) { - HikariDataSource dataSource = - props.initializeDataSourceBuilder() // - .type(HikariDataSource.class) - .build(); + HikariDataSource dataSource = props.initializeDataSourceBuilder() // + .type(HikariDataSource.class) + .build(); String dataSourceName = props.getName(); if (null != dataSourceName) { diff --git a/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/jndi/SimpleNameClassPair.java b/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/jndi/SimpleNameClassPair.java index effe4382c..98616b9f2 100644 --- a/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/jndi/SimpleNameClassPair.java +++ b/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/jndi/SimpleNameClassPair.java @@ -20,8 +20,7 @@ public SimpleNameClassPair(String name, String className) { @Override public boolean equals(Object o) { if (o instanceof javax.naming.NameClassPair p) { - return Objects.equals(getName(), p.getName()) - && Objects.equals(getClassName(), p.getClassName()); + return Objects.equals(getName(), p.getName()) && Objects.equals(getClassName(), p.getClassName()); } return false; } diff --git a/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/jndi/SimpleNamingContext.java b/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/jndi/SimpleNamingContext.java index 839cd2a55..24e0b9d07 100644 --- a/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/jndi/SimpleNamingContext.java +++ b/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/jndi/SimpleNamingContext.java @@ -4,15 +4,12 @@ */ package org.geoserver.cloud.jndi; -import lombok.NonNull; - import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; - import javax.naming.Binding; import javax.naming.Context; import javax.naming.Name; @@ -22,6 +19,7 @@ import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.OperationNotSupportedException; +import lombok.NonNull; /** * Simple implementation of a JNDI naming context. Only supports binding plain Objects to String @@ -50,9 +48,7 @@ public SimpleNamingContext() { } SimpleNamingContext( - @NonNull String root, - @NonNull Map boundObjects, - @NonNull Map env) { + @NonNull String root, @NonNull Map boundObjects, @NonNull Map env) { this.contextRoot = root; this.bindings.putAll(boundObjects); @@ -91,8 +87,7 @@ public Object lookup(@NonNull String lookupName) throws NameNotFoundException { return new SimpleNamingContext(root, this.bindings, this.environment); } - throw new NameNotFoundException( - "'%s' not bound. Bindings: %s".formatted(name, this.bindings.keySet())); + throw new NameNotFoundException("'%s' not bound. Bindings: %s".formatted(name, this.bindings.keySet())); } @Override @@ -125,8 +120,7 @@ public void rename(String oldName, String newName) throws NameNotFoundException @Override public Context createSubcontext(String name) { final String subcontextName = rootName(this.contextRoot + name); - Context subcontext = - new SimpleNamingContext(subcontextName, this.bindings, this.environment); + Context subcontext = new SimpleNamingContext(subcontextName, this.bindings, this.environment); bind(name, subcontext); return subcontext; } @@ -282,8 +276,7 @@ private abstract static class BaseNamingEnumeration implements NamingEnumerat private final Iterator iterator; - private BaseNamingEnumeration(SimpleNamingContext context, final String root) - throws NamingException { + private BaseNamingEnumeration(SimpleNamingContext context, final String root) throws NamingException { if (!root.equals(ROOT_NAME) && !root.endsWith("/")) { throw new IllegalArgumentException("root must end with /: " + root); @@ -306,9 +299,7 @@ private BaseNamingEnumeration(SimpleNamingContext context, final String root) protected String extractSimpleName(final String contextRoot, String boundName) { int startIndex = contextRoot.length(); int endIndex = boundName.indexOf('/', startIndex); - return (endIndex != -1 - ? boundName.substring(startIndex, endIndex) - : boundName.substring(startIndex)); + return (endIndex != -1 ? boundName.substring(startIndex, endIndex) : boundName.substring(startIndex)); } private T lookup(String root, String name, SimpleNamingContext context) { @@ -316,8 +307,7 @@ private T lookup(String root, String name, SimpleNamingContext context) { try { lookup = context.lookup(root + name); } catch (NameNotFoundException shouldNotHappen) { - throw new IllegalStateException( - "Subcontext lookup should not fail at this point", shouldNotHappen); + throw new IllegalStateException("Subcontext lookup should not fail at this point", shouldNotHappen); } return createObject(name, lookup); } @@ -348,11 +338,9 @@ public T nextElement() { public void close() {} } - private static final class NameClassPairEnumeration - extends BaseNamingEnumeration { + private static final class NameClassPairEnumeration extends BaseNamingEnumeration { - private NameClassPairEnumeration(SimpleNamingContext context, String root) - throws NamingException { + private NameClassPairEnumeration(SimpleNamingContext context, String root) throws NamingException { super(context, root); } @@ -364,8 +352,7 @@ private NameClassPairEnumeration(SimpleNamingContext context, String root) private static final class BindingEnumeration extends BaseNamingEnumeration { - private BindingEnumeration(SimpleNamingContext context, String root) - throws NamingException { + private BindingEnumeration(SimpleNamingContext context, String root) throws NamingException { super(context, root); } diff --git a/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/jndi/SimpleNamingContextBuilder.java b/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/jndi/SimpleNamingContextBuilder.java index 6d0ad9d21..27659e968 100644 --- a/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/jndi/SimpleNamingContextBuilder.java +++ b/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/jndi/SimpleNamingContextBuilder.java @@ -4,12 +4,10 @@ */ package org.geoserver.cloud.jndi; -import org.springframework.lang.Nullable; - import java.util.Hashtable; - import javax.naming.spi.InitialContextFactory; import javax.naming.spi.InitialContextFactoryBuilder; +import org.springframework.lang.Nullable; /** * Simple implementation of a JNDI naming context builder. @@ -32,8 +30,7 @@ public class SimpleNamingContextBuilder implements InitialContextFactoryBuilder private final SimpleNamingContextFactory factory = new SimpleNamingContextFactory(); @Override - public InitialContextFactory createInitialContextFactory( - @Nullable Hashtable environment) { + public InitialContextFactory createInitialContextFactory(@Nullable Hashtable environment) { return factory; } } diff --git a/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/jndi/SimpleNamingContextFactory.java b/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/jndi/SimpleNamingContextFactory.java index 8c43b6b8c..fbfad0df0 100644 --- a/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/jndi/SimpleNamingContextFactory.java +++ b/src/library/spring-boot-simplejndi/src/main/java/org/geoserver/cloud/jndi/SimpleNamingContextFactory.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.jndi; import java.util.Hashtable; - import javax.naming.Context; import javax.naming.NamingException; import javax.naming.spi.InitialContextFactory; diff --git a/src/library/spring-boot-simplejndi/src/test/java/org/geoserver/cloud/autoconfigure/jndi/JNDIDataSourceAutoConfigurationTest.java b/src/library/spring-boot-simplejndi/src/test/java/org/geoserver/cloud/autoconfigure/jndi/JNDIDataSourceAutoConfigurationTest.java index 9d73daf76..a77b01034 100644 --- a/src/library/spring-boot-simplejndi/src/test/java/org/geoserver/cloud/autoconfigure/jndi/JNDIDataSourceAutoConfigurationTest.java +++ b/src/library/spring-boot-simplejndi/src/test/java/org/geoserver/cloud/autoconfigure/jndi/JNDIDataSourceAutoConfigurationTest.java @@ -7,24 +7,21 @@ import static org.assertj.core.api.Assertions.assertThat; import com.zaxxer.hikari.HikariDataSource; - +import javax.naming.Context; +import javax.naming.spi.NamingManager; import org.geoserver.cloud.config.jndi.JNDIDataSourceConfiguration; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.runner.ApplicationContextRunner; -import javax.naming.Context; -import javax.naming.spi.NamingManager; - /** * @since 1.0 */ class JNDIDataSourceAutoConfigurationTest { - private ApplicationContextRunner runner = - new ApplicationContextRunner() - .withInitializer(new SimpleJNDIStaticContextInitializer()) - .withConfiguration(AutoConfigurations.of(JNDIDataSourceConfiguration.class)); + private ApplicationContextRunner runner = new ApplicationContextRunner() + .withInitializer(new SimpleJNDIStaticContextInitializer()) + .withConfiguration(AutoConfigurations.of(JNDIDataSourceConfiguration.class)); @Test void testInitialContextLookup() { @@ -36,11 +33,10 @@ void testInitialContextLookup() { "jndi.datasources.ds1.connection-timeout: 250", // "jndi.datasources.ds1.idle-timeout: 60000" // ) - .run( - context -> { - Context initialContext = NamingManager.getInitialContext(null); - Object object = initialContext.lookup("java:comp/env/jdbc/ds1"); - assertThat(object).isInstanceOf(HikariDataSource.class); - }); + .run(context -> { + Context initialContext = NamingManager.getInitialContext(null); + Object object = initialContext.lookup("java:comp/env/jdbc/ds1"); + assertThat(object).isInstanceOf(HikariDataSource.class); + }); } } diff --git a/src/library/spring-boot-simplejndi/src/test/java/org/geoserver/cloud/config/jndi/SimpleJNDIStaticContextInitializerTest.java b/src/library/spring-boot-simplejndi/src/test/java/org/geoserver/cloud/config/jndi/SimpleJNDIStaticContextInitializerTest.java index be57f5eb6..9033ac185 100644 --- a/src/library/spring-boot-simplejndi/src/test/java/org/geoserver/cloud/config/jndi/SimpleJNDIStaticContextInitializerTest.java +++ b/src/library/spring-boot-simplejndi/src/test/java/org/geoserver/cloud/config/jndi/SimpleJNDIStaticContextInitializerTest.java @@ -6,16 +6,14 @@ import static org.assertj.core.api.Assertions.assertThat; -import org.geoserver.cloud.autoconfigure.jndi.SimpleJNDIStaticContextInitializer; -import org.geoserver.cloud.jndi.SimpleNamingContext; -import org.junit.jupiter.api.Test; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - import java.util.Hashtable; - import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.spi.NamingManager; +import org.geoserver.cloud.autoconfigure.jndi.SimpleJNDIStaticContextInitializer; +import org.geoserver.cloud.jndi.SimpleNamingContext; +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; /** * @since 1.0 @@ -23,29 +21,27 @@ class SimpleJNDIStaticContextInitializerTest { private ApplicationContextRunner runner = - new ApplicationContextRunner() - .withInitializer(new SimpleJNDIStaticContextInitializer()); + new ApplicationContextRunner().withInitializer(new SimpleJNDIStaticContextInitializer()); @Test void test() { - runner.run( - context -> { - InitialContext initialContext = new InitialContext(); - Context ctx = NamingManager.getInitialContext(new Hashtable<>()); - assertThat(ctx).isInstanceOf(SimpleNamingContext.class); + runner.run(context -> { + InitialContext initialContext = new InitialContext(); + Context ctx = NamingManager.getInitialContext(new Hashtable<>()); + assertThat(ctx).isInstanceOf(SimpleNamingContext.class); - Object value = new Object(); - initialContext.bind("java:comp/env/test", value); + Object value = new Object(); + initialContext.bind("java:comp/env/test", value); - initialContext.close(); + initialContext.close(); - assertThat(ctx.lookup("java:comp/env/test")).isSameAs(value); + assertThat(ctx.lookup("java:comp/env/test")).isSameAs(value); - initialContext = new InitialContext(); - ctx = NamingManager.getInitialContext(new Hashtable<>()); - assertThat(ctx).isInstanceOf(SimpleNamingContext.class); + initialContext = new InitialContext(); + ctx = NamingManager.getInitialContext(new Hashtable<>()); + assertThat(ctx).isInstanceOf(SimpleNamingContext.class); - assertThat(initialContext.lookup("java:comp/env/test")).isSameAs(value); - }); + assertThat(initialContext.lookup("java:comp/env/test")).isSameAs(value); + }); } } diff --git a/src/library/spring-boot-simplejndi/src/test/java/org/geoserver/cloud/jndi/SimpleNamingContextBuilderTest.java b/src/library/spring-boot-simplejndi/src/test/java/org/geoserver/cloud/jndi/SimpleNamingContextBuilderTest.java index cca723b1d..9567c55ad 100644 --- a/src/library/spring-boot-simplejndi/src/test/java/org/geoserver/cloud/jndi/SimpleNamingContextBuilderTest.java +++ b/src/library/spring-boot-simplejndi/src/test/java/org/geoserver/cloud/jndi/SimpleNamingContextBuilderTest.java @@ -9,15 +9,13 @@ import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import org.junit.jupiter.api.Test; - import java.util.Hashtable; - import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.naming.NoInitialContextException; import javax.naming.spi.NamingManager; +import org.junit.jupiter.api.Test; /** * Test suite for {@link SimpleNamingContextBuilder} @@ -29,9 +27,7 @@ class SimpleNamingContextBuilderTest { @Test void testInitialContext() throws NamingException { assertFalse(NamingManager.hasInitialContextFactoryBuilder()); - assertThrows( - NoInitialContextException.class, - () -> NamingManager.getInitialContext(new Hashtable<>())); + assertThrows(NoInitialContextException.class, () -> NamingManager.getInitialContext(new Hashtable<>())); SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder(); NamingManager.setInitialContextFactoryBuilder(builder); @@ -42,8 +38,7 @@ void testInitialContext() throws NamingException { @Test void testNewInitialContext() throws NamingException { - System.setProperty( - Context.INITIAL_CONTEXT_FACTORY, SimpleNamingContextFactory.class.getName()); + System.setProperty(Context.INITIAL_CONTEXT_FACTORY, SimpleNamingContextFactory.class.getName()); InitialContext ctx = new InitialContext(); Context subcontext = ctx.createSubcontext("java:comp"); assertThat(subcontext).isInstanceOf(SimpleNamingContext.class); diff --git a/src/library/spring-boot-simplejndi/src/test/java/org/geoserver/cloud/jndi/SimpleNamingContextTest.java b/src/library/spring-boot-simplejndi/src/test/java/org/geoserver/cloud/jndi/SimpleNamingContextTest.java index 1ea501d48..3d3365b21 100644 --- a/src/library/spring-boot-simplejndi/src/test/java/org/geoserver/cloud/jndi/SimpleNamingContextTest.java +++ b/src/library/spring-boot-simplejndi/src/test/java/org/geoserver/cloud/jndi/SimpleNamingContextTest.java @@ -9,19 +9,17 @@ import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.springframework.jdbc.datasource.DriverManagerDataSource; - import java.util.Collections; import java.util.Set; - import javax.naming.Context; import javax.naming.NameClassPair; import javax.naming.NameNotFoundException; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.sql.DataSource; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.jdbc.datasource.DriverManagerDataSource; /** * Test suite for {@link SimpleNamingContext} @@ -35,9 +33,7 @@ class SimpleNamingContextTest { @BeforeEach void setup() throws NamingException { SimpleNamingContextBuilder builder = new SimpleNamingContextBuilder(); - root = - (SimpleNamingContext) - builder.createInitialContextFactory(null).getInitialContext(null); + root = (SimpleNamingContext) builder.createInitialContextFactory(null).getInitialContext(null); assertNotNull(root); } @@ -81,10 +77,7 @@ void testList() throws NamingException { assertEquals(expected, list); list = Set.copyOf(Collections.list(root.list("java:comp"))); - expected = - Set.of( - ncp("test", SimpleNamingContext.class), - ncp("env", SimpleNamingContext.class)); + expected = Set.of(ncp("test", SimpleNamingContext.class), ncp("env", SimpleNamingContext.class)); assertEquals(expected, list); list = Set.copyOf(Collections.list(root.list("java:comp/test"))); diff --git a/src/library/spring-factory/src/main/java/org/geoserver/cloud/config/factory/FilteringXmlBeanDefinitionReader.java b/src/library/spring-factory/src/main/java/org/geoserver/cloud/config/factory/FilteringXmlBeanDefinitionReader.java index f37bdd035..2cacc682e 100644 --- a/src/library/spring-factory/src/main/java/org/geoserver/cloud/config/factory/FilteringXmlBeanDefinitionReader.java +++ b/src/library/spring-factory/src/main/java/org/geoserver/cloud/config/factory/FilteringXmlBeanDefinitionReader.java @@ -7,8 +7,18 @@ import static org.springframework.util.StringUtils.hasText; import static org.springframework.util.StringUtils.tokenizeToStringArray; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Set; +import java.util.function.Predicate; +import java.util.regex.Pattern; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.autoconfigure.factory.FilteringXmlBeanDefinitionReaderAutoConfiguration; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.support.BeanDefinitionRegistry; @@ -26,18 +36,6 @@ import org.w3c.dom.Element; import org.xml.sax.InputSource; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; -import java.util.function.Predicate; -import java.util.regex.Pattern; - /** * Spring xml bean definition reader that uses a regular expression to include or exclude beans by * name and alias using a regular expression. @@ -120,20 +118,16 @@ public static synchronized void clearCaches() { } } - protected @Override Document doLoadDocument(InputSource inputSource, Resource resource) - throws Exception { - return classpathDocuments.computeIfAbsent( - resource.getURI().toString(), - r -> { - try { - log.trace("Loading document {}", r); - return super.doLoadDocument(inputSource, resource); - } catch (Exception e) { - if (e instanceof RuntimeException rte) throw rte; - throw (RuntimeException) - new BeanDefinitionStoreException(e.getMessage()).initCause(e); - } - }); + protected @Override Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception { + return classpathDocuments.computeIfAbsent(resource.getURI().toString(), r -> { + try { + log.trace("Loading document {}", r); + return super.doLoadDocument(inputSource, resource); + } catch (Exception e) { + if (e instanceof RuntimeException rte) throw rte; + throw (RuntimeException) new BeanDefinitionStoreException(e.getMessage()).initCause(e); + } + }); } @Override @@ -152,9 +146,8 @@ public int loadBeanDefinitions(String location, @Nullable Set actualRe private int loadBeanDefinitionsApplyingFilters(String location, Set actualResources) { final ResourceLoader resourceLoader = getResourceLoader(); - final boolean filterByResourceLocation = - (resourceLoader instanceof ResourcePatternResolver) - && (location.startsWith("jar:") || location.startsWith("!jar:")); + final boolean filterByResourceLocation = (resourceLoader instanceof ResourcePatternResolver) + && (location.startsWith("jar:") || location.startsWith("!jar:")); if (!filterByResourceLocation) { return super.loadBeanDefinitions(location, actualResources); } @@ -182,19 +175,12 @@ private int loadBeanDefinitionsApplyingFilters(String location, Set ac int count = 0; for (Resource root : allClasspathBaseResources) { - count += - loadBeanDefinitions( - actualResources, - jarNameExpression, - jarNamePattern, - resourcePattern, - root); + count += loadBeanDefinitions(actualResources, jarNameExpression, jarNamePattern, resourcePattern, root); } return count; } catch (IOException ex) { throw new BeanDefinitionStoreException( - "Could not resolve bean definition resource pattern [%s]".formatted(location), - ex); + "Could not resolve bean definition resource pattern [%s]".formatted(location), ex); } } @@ -209,10 +195,7 @@ private int loadBeanDefinitions( int count = 0; if (jarNamePattern.matcher(uri).matches()) { String resourceURI = root.getURI().toString() + resourcePattern; - log.debug( - "Loading bean definitions from {}, matches pattern {}", - resourceURI, - jarNameExpression); + log.debug("Loading bean definitions from {}, matches pattern {}", resourceURI, jarNameExpression); try { count = super.loadBeanDefinitions(resourceURI, actualResources); log.debug("Loaded {} bean definitions from {}", count, uri); @@ -235,17 +218,16 @@ private int loadBeanDefinitions( * @return * @throws IOException */ - private static synchronized Resource[] getAllClasspathResources( - ResourcePatternResolver patternResolver) throws IOException { + private static synchronized Resource[] getAllClasspathResources(ResourcePatternResolver patternResolver) + throws IOException { if (null == classpathBaseResources) { StopWatch sw = new StopWatch(); sw.start(); classpathBaseResources = patternResolver.getResources("classpath*:"); sw.stop(); if (log.isTraceEnabled()) { - log.trace( - "Loaded %,d classpath resources in %,dms" - .formatted(classpathBaseResources.length, sw.getTotalTimeMillis())); + log.trace("Loaded %,d classpath resources in %,dms" + .formatted(classpathBaseResources.length, sw.getTotalTimeMillis())); } } return classpathBaseResources; @@ -253,9 +235,7 @@ private static synchronized Resource[] getAllClasspathResources( private String removeBeanFilterExpressions(String location) { if (location.contains(XML_SPLIT_TOKEN)) { - location = - location.substring( - 0, location.indexOf(XML_SPLIT_TOKEN) + XML_SPLIT_TOKEN.length() - 1); + location = location.substring(0, location.indexOf(XML_SPLIT_TOKEN) + XML_SPLIT_TOKEN.length() - 1); } return location; } @@ -263,8 +243,7 @@ private String removeBeanFilterExpressions(String location) { private void parseAndSetBeanInclusionFilters(String location) { if (location.contains(XML_SPLIT_TOKEN)) { String filterTypeAndRegularExpression = - location.substring( - XML_SPLIT_TOKEN.length() + location.indexOf(XML_SPLIT_TOKEN)); + location.substring(XML_SPLIT_TOKEN.length() + location.indexOf(XML_SPLIT_TOKEN)); if (hasText(filterTypeAndRegularExpression)) { String[] split = filterTypeAndRegularExpression.split("="); if (split.length != 2) { @@ -291,17 +270,14 @@ private void addBeanNameIncludeFilter(final String regex, final String resourceL private IllegalArgumentException throwInvalidExpression( final String resourceLocation, String regex, Throwable cause) { - String msg = - "Invalid bean filter expression (%s), expected name=>, resource: %s" - .formatted(regex, resourceLocation); + String msg = "Invalid bean filter expression (%s), expected name=>, resource: %s" + .formatted(regex, resourceLocation); throw new IllegalArgumentException(msg, cause); } - public static class FilteringBeanDefinitionDocumentReader - extends DefaultBeanDefinitionDocumentReader { + public static class FilteringBeanDefinitionDocumentReader extends DefaultBeanDefinitionDocumentReader { - private static final ThreadLocal>> MATCHERS = - ThreadLocal.withInitial(ArrayList::new); + private static final ThreadLocal>> MATCHERS = ThreadLocal.withInitial(ArrayList::new); public static void addMatcher(Predicate beanDefFilter) { MATCHERS.get().add(beanDefFilter); @@ -350,8 +326,7 @@ private void registerDeferredAlias(String name, String alias) { } catch (Exception ex) { getReaderContext() .error( - "Failed to register alias '%s' for bean with name '%s'" - .formatted(alias, name), + "Failed to register alias '%s' for bean with name '%s'".formatted(alias, name), null, ex); } @@ -376,8 +351,7 @@ private void registerDeferredAlias(String name, String alias) { deferredNameToAlias.put(name, alias); } - protected @Override void processBeanDefinition( - Element ele, BeanDefinitionParserDelegate delegate) { + protected @Override void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) { final String beanNameOrId = getBeanNameOrId(ele); if (isFiltering()) { if (shallInclude(beanNameOrId)) { @@ -399,8 +373,7 @@ private boolean shallInclude(String nameAtt) { } String[] aliases = - tokenizeToStringArray( - nameAtt, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS); + tokenizeToStringArray(nameAtt, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS); for (String alias : aliases) { if (include(alias)) { return true; diff --git a/src/library/spring-factory/src/test/java/org/geoserver/cloud/config/factory/FilteringXmlBeanDefinitionReaderTest.java b/src/library/spring-factory/src/test/java/org/geoserver/cloud/config/factory/FilteringXmlBeanDefinitionReaderTest.java index 6add36b8d..1037efbab 100644 --- a/src/library/spring-factory/src/test/java/org/geoserver/cloud/config/factory/FilteringXmlBeanDefinitionReaderTest.java +++ b/src/library/spring-factory/src/test/java/org/geoserver/cloud/config/factory/FilteringXmlBeanDefinitionReaderTest.java @@ -4,17 +4,16 @@ */ package org.geoserver.cloud.config.factory; -import org.junit.jupiter.api.Assertions; -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Test; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; - import java.util.Arrays; import java.util.Collections; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.stream.Collectors; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; class FilteringXmlBeanDefinitionReaderTest { @@ -47,12 +46,7 @@ class FilteringXmlBeanDefinitionReaderTest { @Test void noFilterIncludesdAll() { - verify( - baseResource, - "filterFactory", - "geoServer", - "memoryLockProvider", - "nullLockProvider"); + verify(baseResource, "filterFactory", "geoServer", "memoryLockProvider", "nullLockProvider"); } @Test @@ -69,24 +63,21 @@ void excludeAll_AnyWord() { @Test void excludeByName() { - String location = - "%s#name=^(?!nullLockProvider|memoryLockProvider).*$".formatted(baseResource); + String location = "%s#name=^(?!nullLockProvider|memoryLockProvider).*$".formatted(baseResource); verify(location, "filterFactory", "geoServer"); } @Test void excludeAllExplicitlyByName() { String location = - "%s#name=^(?!nullLockProvider|memoryLockProvider|filterFactory|geoServer)$" - .formatted(baseResource); + "%s#name=^(?!nullLockProvider|memoryLockProvider|filterFactory|geoServer)$".formatted(baseResource); verify(location); } @Test void includeAllExplicitly() { String location = - "%s#name=^(nullLockProvider|memoryLockProvider|filterFactory|geoServer)$" - .formatted(baseResource); + "%s#name=^(nullLockProvider|memoryLockProvider|filterFactory|geoServer)$".formatted(baseResource); verify(location, "filterFactory", "geoServer", "memoryLockProvider", "nullLockProvider"); } @@ -109,18 +100,15 @@ void includeByNameAttribute() { } private void verify(String location, String... expectedBeanNames) { - Set expected = - expectedBeanNames == null - ? Collections.emptySet() - : Arrays.stream(expectedBeanNames) - .collect(Collectors.toCollection(TreeSet::new)); + Set expected = expectedBeanNames == null + ? Collections.emptySet() + : Arrays.stream(expectedBeanNames).collect(Collectors.toCollection(TreeSet::new)); Set loadedNames = loadBeanDefinitionsAndReturnNames(location); Assertions.assertEquals(expected, loadedNames, "loaded beans don't match expected"); } private SortedSet loadBeanDefinitionsAndReturnNames(String location) { reader.loadBeanDefinitions(location); - return Arrays.stream(registry.getBeanDefinitionNames()) - .collect(Collectors.toCollection(TreeSet::new)); + return Arrays.stream(registry.getBeanDefinitionNames()).collect(Collectors.toCollection(TreeSet::new)); } } diff --git a/src/starters/geonode/src/main/java/org/geoserver/cloud/autoconfigure/geonode/GeoNodeOAuth2AutoConfiguration.java b/src/starters/geonode/src/main/java/org/geoserver/cloud/autoconfigure/geonode/GeoNodeOAuth2AutoConfiguration.java index 069631aa7..c2cb04b6c 100644 --- a/src/starters/geonode/src/main/java/org/geoserver/cloud/autoconfigure/geonode/GeoNodeOAuth2AutoConfiguration.java +++ b/src/starters/geonode/src/main/java/org/geoserver/cloud/autoconfigure/geonode/GeoNodeOAuth2AutoConfiguration.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.autoconfigure.geonode; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.config.factory.FilteringXmlBeanDefinitionReader; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.context.annotation.ComponentScan; diff --git a/src/starters/observability/src/main/java/org/geoserver/cloud/autoconfigure/observability/LoggingMDCAutoConfiguration.java b/src/starters/observability/src/main/java/org/geoserver/cloud/autoconfigure/observability/LoggingMDCAutoConfiguration.java index a3eeef447..26c717a21 100644 --- a/src/starters/observability/src/main/java/org/geoserver/cloud/autoconfigure/observability/LoggingMDCAutoConfiguration.java +++ b/src/starters/observability/src/main/java/org/geoserver/cloud/autoconfigure/observability/LoggingMDCAutoConfiguration.java @@ -4,6 +4,7 @@ */ package org.geoserver.cloud.autoconfigure.observability; +import java.util.Optional; import org.geoserver.cloud.observability.logging.config.MDCConfigProperties; import org.geoserver.cloud.observability.logging.servlet.HttpRequestMdcConfigProperties; import org.geoserver.cloud.observability.logging.servlet.HttpRequestMdcFilter; @@ -28,8 +29,6 @@ import org.springframework.security.core.Authentication; import org.springframework.security.core.context.SecurityContext; -import java.util.Optional; - /** * {@link AutoConfiguration @AutoConfiguration} to enable logging MDC (Mapped Diagnostic Context) * contributions during the request life cycle @@ -65,9 +64,7 @@ MDCCleaningFilter mdcCleaningServletFilter() { @Bean @Order(Ordered.HIGHEST_PRECEDENCE) SpringEnvironmentMdcFilter springEnvironmentMdcFilter( - Environment env, - SpringEnvironmentMdcConfigProperties config, - Optional buildProperties) { + Environment env, SpringEnvironmentMdcConfigProperties config, Optional buildProperties) { return new SpringEnvironmentMdcFilter(env, buildProperties, config); } @@ -81,8 +78,7 @@ SpringEnvironmentMdcFilter springEnvironmentMdcFilter( @ConditionalOnClass(name = "org.springframework.security.core.Authentication") FilterRegistrationBean mdcAuthenticationPropertiesServletFilter( MDCConfigProperties config) { - FilterRegistrationBean registration = - new FilterRegistrationBean<>(); + FilterRegistrationBean registration = new FilterRegistrationBean<>(); var filter = new MDCAuthenticationFilter(config); registration.setMatchAfter(true); diff --git a/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/config/MDCConfigProperties.java b/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/config/MDCConfigProperties.java index 7a429f9b0..aa37b9e20 100644 --- a/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/config/MDCConfigProperties.java +++ b/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/config/MDCConfigProperties.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.observability.logging.config; import lombok.Data; - import org.springframework.boot.context.properties.ConfigurationProperties; @Data diff --git a/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/ows/MDCDispatcherCallback.java b/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/ows/MDCDispatcherCallback.java index b46ce7327..182c75f89 100644 --- a/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/ows/MDCDispatcherCallback.java +++ b/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/ows/MDCDispatcherCallback.java @@ -6,7 +6,6 @@ import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.cloud.observability.logging.config.MDCConfigProperties; import org.geoserver.ows.AbstractDispatcherCallback; import org.geoserver.ows.DispatcherCallback; @@ -16,8 +15,7 @@ import org.slf4j.MDC; @RequiredArgsConstructor -public class MDCDispatcherCallback extends AbstractDispatcherCallback - implements DispatcherCallback { +public class MDCDispatcherCallback extends AbstractDispatcherCallback implements DispatcherCallback { private final @NonNull MDCConfigProperties config; diff --git a/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/HttpRequestMdcConfigProperties.java b/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/HttpRequestMdcConfigProperties.java index 021018235..273c9b22a 100644 --- a/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/HttpRequestMdcConfigProperties.java +++ b/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/HttpRequestMdcConfigProperties.java @@ -4,12 +4,10 @@ */ package org.geoserver.cloud.observability.logging.servlet; +import java.util.regex.Pattern; import lombok.Data; - import org.springframework.boot.context.properties.ConfigurationProperties; -import java.util.regex.Pattern; - @Data @ConfigurationProperties(prefix = "logging.mdc.include.http") public class HttpRequestMdcConfigProperties { diff --git a/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/HttpRequestMdcFilter.java b/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/HttpRequestMdcFilter.java index 0462777d1..cf912efe3 100644 --- a/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/HttpRequestMdcFilter.java +++ b/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/HttpRequestMdcFilter.java @@ -6,26 +6,22 @@ import com.github.f4b6a3.ulid.UlidCreator; import com.google.common.collect.Streams; - -import lombok.NonNull; -import lombok.RequiredArgsConstructor; - -import org.slf4j.MDC; -import org.springframework.web.filter.OncePerRequestFilter; - import java.io.IOException; import java.util.Optional; import java.util.function.BooleanSupplier; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; - import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import org.slf4j.MDC; +import org.springframework.web.filter.OncePerRequestFilter; @RequiredArgsConstructor public class HttpRequestMdcFilter extends OncePerRequestFilter { @@ -33,8 +29,7 @@ public class HttpRequestMdcFilter extends OncePerRequestFilter { private final @NonNull HttpRequestMdcConfigProperties config; @Override - protected void doFilterInternal( - HttpServletRequest request, HttpServletResponse response, FilterChain chain) + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { try { if (request instanceof HttpServletRequest req) addRequestMdcProperties(req); @@ -54,14 +49,8 @@ private void addRequestMdcProperties(HttpServletRequest req) { put("http.request.url", config::isUrl, req::getRequestURL); putRequestParams(req); put("http.request.query-string", config::isQueryString, req::getQueryString); - put( - "http.request.session.id", - config::isSessionId, - () -> session == null ? null : session.getId()); - put( - "http.request.session.started", - config::isSessionId, - () -> session == null ? null : !session.isNew()); + put("http.request.session.id", config::isSessionId, () -> session == null ? null : session.getId()); + put("http.request.session.started", config::isSessionId, () -> session == null ? null : !session.isNew()); addHeaders(req); addCookies(req); } @@ -69,11 +58,7 @@ private void addRequestMdcProperties(HttpServletRequest req) { private void putRequestParams(HttpServletRequest req) { if (config.isParameters()) { Streams.stream(req.getParameterNames().asIterator()) - .forEach( - name -> - put( - "http.request.parameter.%s".formatted(name), - requestParam(name, req))); + .forEach(name -> put("http.request.parameter.%s".formatted(name), requestParam(name, req))); } } diff --git a/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/MDCAuthenticationFilter.java b/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/MDCAuthenticationFilter.java index 8d592c38c..a71b589dc 100644 --- a/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/MDCAuthenticationFilter.java +++ b/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/MDCAuthenticationFilter.java @@ -4,23 +4,20 @@ */ package org.geoserver.cloud.observability.logging.servlet; -import lombok.NonNull; -import lombok.RequiredArgsConstructor; - -import org.geoserver.cloud.observability.logging.config.MDCConfigProperties; -import org.slf4j.MDC; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.GrantedAuthority; -import org.springframework.security.core.context.SecurityContextHolder; - import java.io.IOException; import java.util.stream.Collectors; - import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import org.geoserver.cloud.observability.logging.config.MDCConfigProperties; +import org.slf4j.MDC; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.GrantedAuthority; +import org.springframework.security.core.context.SecurityContextHolder; /** * Appends the {@code enduser.id} and {@code enduser.role} MDC properties depending on whether diff --git a/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/MDCCleaningFilter.java b/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/MDCCleaningFilter.java index bf159e1f4..08799717b 100644 --- a/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/MDCCleaningFilter.java +++ b/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/MDCCleaningFilter.java @@ -4,21 +4,18 @@ */ package org.geoserver.cloud.observability.logging.servlet; -import org.slf4j.MDC; -import org.springframework.web.filter.OncePerRequestFilter; - import java.io.IOException; - import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import org.slf4j.MDC; +import org.springframework.web.filter.OncePerRequestFilter; public class MDCCleaningFilter extends OncePerRequestFilter { @Override - protected void doFilterInternal( - HttpServletRequest request, HttpServletResponse response, FilterChain chain) + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { try { chain.doFilter(request, response); diff --git a/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/SpringEnvironmentMdcConfigProperties.java b/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/SpringEnvironmentMdcConfigProperties.java index 99c5396d0..24168322c 100644 --- a/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/SpringEnvironmentMdcConfigProperties.java +++ b/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/SpringEnvironmentMdcConfigProperties.java @@ -1,11 +1,9 @@ package org.geoserver.cloud.observability.logging.servlet; +import java.util.List; import lombok.Data; - import org.springframework.boot.context.properties.ConfigurationProperties; -import java.util.List; - @Data @ConfigurationProperties(prefix = "logging.mdc.include.application") public class SpringEnvironmentMdcConfigProperties { @@ -13,7 +11,6 @@ public class SpringEnvironmentMdcConfigProperties { private boolean name = true; private boolean version = true; private boolean instanceId = true; - private List instanceIdProperties = - List.of("info.instance-id", "spring.application.instance_id"); + private List instanceIdProperties = List.of("info.instance-id", "spring.application.instance_id"); private boolean activeProfiles = true; } diff --git a/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/SpringEnvironmentMdcFilter.java b/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/SpringEnvironmentMdcFilter.java index 09673fb36..f64d01e34 100644 --- a/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/SpringEnvironmentMdcFilter.java +++ b/src/starters/observability/src/main/java/org/geoserver/cloud/observability/logging/servlet/SpringEnvironmentMdcFilter.java @@ -4,24 +4,21 @@ */ package org.geoserver.cloud.observability.logging.servlet; -import lombok.NonNull; -import lombok.RequiredArgsConstructor; - -import org.slf4j.MDC; -import org.springframework.boot.info.BuildProperties; -import org.springframework.core.env.Environment; -import org.springframework.util.StringUtils; -import org.springframework.web.filter.OncePerRequestFilter; - import java.io.IOException; import java.util.Optional; import java.util.stream.Collectors; import java.util.stream.Stream; - import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import lombok.NonNull; +import lombok.RequiredArgsConstructor; +import org.slf4j.MDC; +import org.springframework.boot.info.BuildProperties; +import org.springframework.core.env.Environment; +import org.springframework.util.StringUtils; +import org.springframework.web.filter.OncePerRequestFilter; @RequiredArgsConstructor public class SpringEnvironmentMdcFilter extends OncePerRequestFilter { @@ -31,8 +28,7 @@ public class SpringEnvironmentMdcFilter extends OncePerRequestFilter { private final @NonNull SpringEnvironmentMdcConfigProperties config; @Override - protected void doFilterInternal( - HttpServletRequest request, HttpServletResponse response, FilterChain chain) + protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException { try { addEnvironmentProperties(); @@ -42,23 +38,18 @@ protected void doFilterInternal( } private void addEnvironmentProperties() { - if (config.isName()) - MDC.put("application.name", env.getProperty("spring.application.name")); + if (config.isName()) MDC.put("application.name", env.getProperty("spring.application.name")); putVersion(); putInstanceId(); if (config.isActiveProfiles()) - MDC.put( - "spring.profiles.active", - Stream.of(env.getActiveProfiles()).collect(Collectors.joining(","))); + MDC.put("spring.profiles.active", Stream.of(env.getActiveProfiles()).collect(Collectors.joining(","))); } private void putVersion() { if (config.isVersion()) { - buildProperties - .map(BuildProperties::getVersion) - .ifPresent(v -> MDC.put("application.version", v)); + buildProperties.map(BuildProperties::getVersion).ifPresent(v -> MDC.put("application.version", v)); } } diff --git a/src/starters/observability/src/test/java/org/geoserver/cloud/autoconfigure/observability/LoggingMDCAutoConfigurationTest.java b/src/starters/observability/src/test/java/org/geoserver/cloud/autoconfigure/observability/LoggingMDCAutoConfigurationTest.java index 2329745c1..0aa595fed 100644 --- a/src/starters/observability/src/test/java/org/geoserver/cloud/autoconfigure/observability/LoggingMDCAutoConfigurationTest.java +++ b/src/starters/observability/src/test/java/org/geoserver/cloud/autoconfigure/observability/LoggingMDCAutoConfigurationTest.java @@ -20,22 +20,19 @@ class LoggingMDCAutoConfigurationTest { - private WebApplicationContextRunner runner = - new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(LoggingMDCAutoConfiguration.class)); + private WebApplicationContextRunner runner = new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(LoggingMDCAutoConfiguration.class)); @Test void testDefaultBeans() { - runner.run( - context -> - assertThat(context) - .hasNotFailed() - .hasSingleBean(MDCConfigProperties.class) - .hasSingleBean(MDCDispatcherCallback.class) - .hasSingleBean(MDCCleaningFilter.class) - .hasSingleBean(HttpRequestMdcFilter.class) - .hasSingleBean(SpringEnvironmentMdcFilter.class) - .hasBean("mdcAuthenticationPropertiesServletFilter")); + runner.run(context -> assertThat(context) + .hasNotFailed() + .hasSingleBean(MDCConfigProperties.class) + .hasSingleBean(MDCDispatcherCallback.class) + .hasSingleBean(MDCCleaningFilter.class) + .hasSingleBean(HttpRequestMdcFilter.class) + .hasSingleBean(SpringEnvironmentMdcFilter.class) + .hasBean("mdcAuthenticationPropertiesServletFilter")); } @Test @@ -46,48 +43,34 @@ void testMDCConfigProperties() { "logging.mdc.include.user=%s".formatted(!defaults.isUser()), "logging.mdc.include.roles=%s".formatted(!defaults.isRoles()), "logging.mdc.include.ows=%s".formatted(!defaults.isOws())) - .run( - context -> - assertThat(context) - .getBean(MDCConfigProperties.class) - .hasFieldOrPropertyWithValue("user", !defaults.isUser()) - .hasFieldOrPropertyWithValue("roles", !defaults.isRoles()) - .hasFieldOrPropertyWithValue("ows", !defaults.isOws())); + .run(context -> assertThat(context) + .getBean(MDCConfigProperties.class) + .hasFieldOrPropertyWithValue("user", !defaults.isUser()) + .hasFieldOrPropertyWithValue("roles", !defaults.isRoles()) + .hasFieldOrPropertyWithValue("ows", !defaults.isOws())); } @Test void conditionalOnGeoServerDispatcher() { runner.withClassLoader(new FilteredClassLoader(org.geoserver.ows.Dispatcher.class)) - .run( - context -> - assertThat(context) - .hasNotFailed() - .doesNotHaveBean(MDCDispatcherCallback.class)); + .run(context -> assertThat(context).hasNotFailed().doesNotHaveBean(MDCDispatcherCallback.class)); } @Test void conditionalOnServletWebApplication() { - ReactiveWebApplicationContextRunner reactiveAppRunner = - new ReactiveWebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(LoggingMDCAutoConfiguration.class)); - reactiveAppRunner.run( - context -> - assertThat(context) - .hasNotFailed() - .doesNotHaveBean(MDCConfigProperties.class) - .doesNotHaveBean(MDCDispatcherCallback.class) - .doesNotHaveBean("mdcCleaningServletFilter")); + ReactiveWebApplicationContextRunner reactiveAppRunner = new ReactiveWebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(LoggingMDCAutoConfiguration.class)); + reactiveAppRunner.run(context -> assertThat(context) + .hasNotFailed() + .doesNotHaveBean(MDCConfigProperties.class) + .doesNotHaveBean(MDCDispatcherCallback.class) + .doesNotHaveBean("mdcCleaningServletFilter")); } @Test void authenticationFilterConditionalOnAuthenticationClass() { runner.withClassLoader(new FilteredClassLoader(Authentication.class)) - .run( - context -> - assertThat(context) - .hasNotFailed() - .doesNotHaveBean( - "mdcAuthenticationPropertiesServletFilter")); + .run(context -> + assertThat(context).hasNotFailed().doesNotHaveBean("mdcAuthenticationPropertiesServletFilter")); } } diff --git a/src/starters/raster-formats/src/main/java/org/geoserver/cloud/autoconfigure/cog/COGAutoConfiguration.java b/src/starters/raster-formats/src/main/java/org/geoserver/cloud/autoconfigure/cog/COGAutoConfiguration.java index ded66e52a..cc8c29e69 100644 --- a/src/starters/raster-formats/src/main/java/org/geoserver/cloud/autoconfigure/cog/COGAutoConfiguration.java +++ b/src/starters/raster-formats/src/main/java/org/geoserver/cloud/autoconfigure/cog/COGAutoConfiguration.java @@ -15,11 +15,8 @@ @ConditionalOnClass({CogSettings.class}) @ImportResource( reader = FilteringXmlBeanDefinitionReader.class, // - locations = { - "jar:gs-cog-.*!/applicationContext.xml#name=" + COGAutoConfiguration.EXCLUDE_WEBUI_BEANS - }) + locations = {"jar:gs-cog-.*!/applicationContext.xml#name=" + COGAutoConfiguration.EXCLUDE_WEBUI_BEANS}) public class COGAutoConfiguration { - static final String EXCLUDE_WEBUI_BEANS = - "^(?!" + COGWebUIAutoConfiguration.WEBUI_BEAN_NAMES + ").*$"; + static final String EXCLUDE_WEBUI_BEANS = "^(?!" + COGWebUIAutoConfiguration.WEBUI_BEAN_NAMES + ").*$"; } diff --git a/src/starters/raster-formats/src/main/java/org/geoserver/cloud/autoconfigure/cog/COGWebUIAutoConfiguration.java b/src/starters/raster-formats/src/main/java/org/geoserver/cloud/autoconfigure/cog/COGWebUIAutoConfiguration.java index b109359fe..a1bb2d190 100644 --- a/src/starters/raster-formats/src/main/java/org/geoserver/cloud/autoconfigure/cog/COGWebUIAutoConfiguration.java +++ b/src/starters/raster-formats/src/main/java/org/geoserver/cloud/autoconfigure/cog/COGWebUIAutoConfiguration.java @@ -16,14 +16,10 @@ @ConditionalOnClass({GeoServerApplication.class, CogRasterEditPanel.class}) @ImportResource( reader = FilteringXmlBeanDefinitionReader.class, // - locations = { - "jar:gs-cog-.*!/applicationContext.xml#name=" - + COGWebUIAutoConfiguration.INCLUDE_WEBUI_BEANS - }) + locations = {"jar:gs-cog-.*!/applicationContext.xml#name=" + COGWebUIAutoConfiguration.INCLUDE_WEBUI_BEANS}) public class COGWebUIAutoConfiguration { - static final String WEBUI_BEAN_NAMES = - "COGGeoTIFFExclusionFilter|CogGeotiffStorePanel|CogSettingsPanel"; + static final String WEBUI_BEAN_NAMES = "COGGeoTIFFExclusionFilter|CogGeotiffStorePanel|CogSettingsPanel"; static final String INCLUDE_WEBUI_BEANS = "^(" + WEBUI_BEAN_NAMES + ").*$"; } diff --git a/src/starters/raster-formats/src/main/java/org/geoserver/cloud/autoconfigure/pgraster/PostgisRasterWebUIAutoConfiguration.java b/src/starters/raster-formats/src/main/java/org/geoserver/cloud/autoconfigure/pgraster/PostgisRasterWebUIAutoConfiguration.java index 4f541776d..56e982867 100644 --- a/src/starters/raster-formats/src/main/java/org/geoserver/cloud/autoconfigure/pgraster/PostgisRasterWebUIAutoConfiguration.java +++ b/src/starters/raster-formats/src/main/java/org/geoserver/cloud/autoconfigure/pgraster/PostgisRasterWebUIAutoConfiguration.java @@ -19,10 +19,6 @@ * org.geoserver.web.data.resource.DataStorePanelInfo#setComponentClass(Class)} */ @AutoConfiguration -@ConditionalOnClass({ - GeoServerApplication.class, - DataStorePanelInfo.class, - PGRasterCoverageStoreEditPanel.class -}) +@ConditionalOnClass({GeoServerApplication.class, DataStorePanelInfo.class, PGRasterCoverageStoreEditPanel.class}) @ImportResource(locations = "classpath:pgrasterApplicationContext.xml") public class PostgisRasterWebUIAutoConfiguration {} diff --git a/src/starters/raster-formats/src/test/java/org/geoserver/cloud/autoconfigure/cog/COGAutoConfigurationTest.java b/src/starters/raster-formats/src/test/java/org/geoserver/cloud/autoconfigure/cog/COGAutoConfigurationTest.java index 8d1ebe9ee..6f7428f91 100644 --- a/src/starters/raster-formats/src/test/java/org/geoserver/cloud/autoconfigure/cog/COGAutoConfigurationTest.java +++ b/src/starters/raster-formats/src/test/java/org/geoserver/cloud/autoconfigure/cog/COGAutoConfigurationTest.java @@ -22,47 +22,40 @@ class COGAutoConfigurationTest { private final Catalog mockCatalog = mock(Catalog.class); - private final ApplicationContextRunner contextRunner = - new ApplicationContextRunner() - .withBean("catalog", Catalog.class, () -> mockCatalog) - .withConfiguration( - AutoConfigurations.of( - COGAutoConfiguration.class, COGWebUIAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withBean("catalog", Catalog.class, () -> mockCatalog) + .withConfiguration(AutoConfigurations.of(COGAutoConfiguration.class, COGWebUIAutoConfiguration.class)); @Test void testWebUIUnavailable() { FilteredClassLoader hiddenClasses = new FilteredClassLoader(GeoServerApplication.class, CogRasterEditPanel.class); - contextRunner - .withClassLoader(hiddenClasses) - .run( - context -> { - assertThat(context).hasNotFailed(); + contextRunner.withClassLoader(hiddenClasses).run(context -> { + assertThat(context).hasNotFailed(); - for (String beanName : nonWebuiBeanNames()) { - assertThat(context).hasBean(beanName); - } + for (String beanName : nonWebuiBeanNames()) { + assertThat(context).hasBean(beanName); + } - for (String webuiBeanName : webuiBeanNames()) { - assertThat(context).doesNotHaveBean(webuiBeanName); - } - }); + for (String webuiBeanName : webuiBeanNames()) { + assertThat(context).doesNotHaveBean(webuiBeanName); + } + }); } @Test void testWebUIAvailable() { - contextRunner.run( - context -> { - assertThat(context).hasNotFailed(); + contextRunner.run(context -> { + assertThat(context).hasNotFailed(); - for (String beanName : nonWebuiBeanNames()) { - assertThat(context).hasBean(beanName); - } - for (String webuiBeanName : webuiBeanNames()) { - assertThat(context).hasBean(webuiBeanName); - } - }); + for (String beanName : nonWebuiBeanNames()) { + assertThat(context).hasBean(beanName); + } + for (String webuiBeanName : webuiBeanNames()) { + assertThat(context).hasBean(webuiBeanName); + } + }); } private String[] nonWebuiBeanNames() { diff --git a/src/starters/raster-formats/src/test/java/org/geoserver/cloud/autoconfigure/pgraster/PostgisRasterWebUIAutoConfigurationTest.java b/src/starters/raster-formats/src/test/java/org/geoserver/cloud/autoconfigure/pgraster/PostgisRasterWebUIAutoConfigurationTest.java index 42b12983c..89ef50d06 100644 --- a/src/starters/raster-formats/src/test/java/org/geoserver/cloud/autoconfigure/pgraster/PostgisRasterWebUIAutoConfigurationTest.java +++ b/src/starters/raster-formats/src/test/java/org/geoserver/cloud/autoconfigure/pgraster/PostgisRasterWebUIAutoConfigurationTest.java @@ -17,32 +17,24 @@ class PostgisRasterWebUIAutoConfigurationTest { - private final ApplicationContextRunner contextRunner = - new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(PostgisRasterWebUIAutoConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(PostgisRasterWebUIAutoConfiguration.class)); @Test void testConditionalOnPostgisRasterWebUI_enabled() { - contextRunner.run( - context -> { - assertThat(context) - .hasBean("pgrasterCoverageStorePanel") - .getBean("pgrasterCoverageStorePanel") - .isInstanceOf(DataStorePanelInfo.class); - - assertThat( - context.getBean( - "pgrasterCoverageStorePanel", DataStorePanelInfo.class)) - .hasFieldOrPropertyWithValue("factoryClass", PostgisRasterFormat.class); - - assertThat( - context.getBean( - "pgrasterCoverageStorePanel", DataStorePanelInfo.class)) - .hasFieldOrPropertyWithValue( - "componentClass", PGRasterCoverageStoreEditPanel.class); - }); + contextRunner.run(context -> { + assertThat(context) + .hasBean("pgrasterCoverageStorePanel") + .getBean("pgrasterCoverageStorePanel") + .isInstanceOf(DataStorePanelInfo.class); + + assertThat(context.getBean("pgrasterCoverageStorePanel", DataStorePanelInfo.class)) + .hasFieldOrPropertyWithValue("factoryClass", PostgisRasterFormat.class); + + assertThat(context.getBean("pgrasterCoverageStorePanel", DataStorePanelInfo.class)) + .hasFieldOrPropertyWithValue("componentClass", PGRasterCoverageStoreEditPanel.class); + }); } @Test @@ -50,9 +42,8 @@ void testConditionalOnPostgisRasterWebUI_disabled() { contextRunner .withClassLoader(new FilteredClassLoader(GeoServerApplication.class)) - .run( - context -> { - assertThat(context).doesNotHaveBean("pgrasterCoverageStorePanel"); - }); + .run(context -> { + assertThat(context).doesNotHaveBean("pgrasterCoverageStorePanel"); + }); } } diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/AuthKeyAutoConfiguration.java b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/AuthKeyAutoConfiguration.java index 71b9bdad4..c90e5f53c 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/AuthKeyAutoConfiguration.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/AuthKeyAutoConfiguration.java @@ -4,8 +4,8 @@ */ package org.geoserver.cloud.autoconfigure.authzn; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.config.factory.FilteringXmlBeanDefinitionReader; import org.geoserver.platform.ModuleStatus; import org.geoserver.platform.ModuleStatusImpl; @@ -18,8 +18,6 @@ import org.springframework.context.annotation.Import; import org.springframework.context.annotation.ImportResource; -import javax.annotation.PostConstruct; - /** * @since 1.0 */ @@ -35,12 +33,7 @@ public class AuthKeyAutoConfiguration { @Bean(name = "authKeyExtension") ModuleStatus authKeyExtension( - @Value( - "${" - + GEOSERVER_SECURITY_AUTHKEY - + ":" - + ConditionalOnAuthKeyEnabled.ENABLED_BY_DEFAULT - + "}") + @Value("${" + GEOSERVER_SECURITY_AUTHKEY + ":" + ConditionalOnAuthKeyEnabled.ENABLED_BY_DEFAULT + "}") boolean enabled) { ModuleStatusImpl module = new ModuleStatusImpl(); @@ -50,8 +43,7 @@ ModuleStatus authKeyExtension( module.setAvailable(true); module.setEnabled(enabled); if (!enabled) { - module.setMessage( - "Authkey Extension disabled. " + GEOSERVER_SECURITY_AUTHKEY + "=false"); + module.setMessage("Authkey Extension disabled. " + GEOSERVER_SECURITY_AUTHKEY + "=false"); } return module; } @@ -62,8 +54,7 @@ ModuleStatus authKeyExtension( locations = {Enabled.INCLUDE}) static @Configuration class Enabled { static final String EXCLUDE = "authKeyExtension|" + WEB_UI_BEANS; - static final String INCLUDE = - "jar:gs-authkey-.*!/applicationContext.xml#name=^(?!" + EXCLUDE + ").*$"; + static final String INCLUDE = "jar:gs-authkey-.*!/applicationContext.xml#name=^(?!" + EXCLUDE + ").*$"; public @PostConstruct void log() { log.info("{} enabled", GEOSERVER_SECURITY_AUTHKEY); @@ -76,7 +67,6 @@ ModuleStatus authKeyExtension( reader = FilteringXmlBeanDefinitionReader.class, locations = {WebUI.INCLUDE}) static @Configuration class WebUI { - static final String INCLUDE = - "jar:gs-authkey-.*!/applicationContext.xml#name=^(" + WEB_UI_BEANS + ").*$"; + static final String INCLUDE = "jar:gs-authkey-.*!/applicationContext.xml#name=^(" + WEB_UI_BEANS + ").*$"; } } diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/ConditionalOnAuthKeyEnabled.java b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/ConditionalOnAuthKeyEnabled.java index b191ae359..b97c29015 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/ConditionalOnAuthKeyEnabled.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/ConditionalOnAuthKeyEnabled.java @@ -4,17 +4,16 @@ */ package org.geoserver.cloud.autoconfigure.authzn; -import org.geoserver.security.GeoServerAuthenticationKeyProvider; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.geoserver.security.GeoServerAuthenticationKeyProvider; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type; /** * Conditionals: diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/ConditionalOnGatewaySharedAuthDisabled.java b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/ConditionalOnGatewaySharedAuthDisabled.java index 3930b9494..5a14f8ad8 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/ConditionalOnGatewaySharedAuthDisabled.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/ConditionalOnGatewaySharedAuthDisabled.java @@ -4,14 +4,13 @@ */ package org.geoserver.cloud.autoconfigure.authzn; -import org.geoserver.cloud.autoconfigure.security.ConditionalOnGeoServerSecurityEnabled; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.geoserver.cloud.autoconfigure.security.ConditionalOnGeoServerSecurityEnabled; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; /** Conditional to check if gateway/webui shared authentication is disabled. */ @Retention(RetentionPolicy.RUNTIME) diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/ConditionalOnGatewaySharedAuthEnabled.java b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/ConditionalOnGatewaySharedAuthEnabled.java index 1c46844e4..cc62c1269 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/ConditionalOnGatewaySharedAuthEnabled.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/ConditionalOnGatewaySharedAuthEnabled.java @@ -4,14 +4,13 @@ */ package org.geoserver.cloud.autoconfigure.authzn; -import org.geoserver.cloud.autoconfigure.security.ConditionalOnGeoServerSecurityEnabled; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; +import org.geoserver.cloud.autoconfigure.security.ConditionalOnGeoServerSecurityEnabled; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; /** * Conditional to enable gateway/webui shared authentication mechanism. It must also be enabled in diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/GatewayPreAuthenticationAutoConfiguration.java b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/GatewayPreAuthenticationAutoConfiguration.java index ec1f20e24..679d6dca0 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/GatewayPreAuthenticationAutoConfiguration.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/GatewayPreAuthenticationAutoConfiguration.java @@ -17,10 +17,7 @@ // run before GeoServerSecurityAutoConfiguration so the provider is available when // GeoServerSecurityManager calls GeoServerExtensions.extensions(GeoServerSecurityProvider.class) @AutoConfiguration(before = GeoServerSecurityAutoConfiguration.class) -@Import({ - GatewayPreAuthenticationConfiguration.class, - GatewayPreAuthenticationAutoConfiguration.WebUi.class -}) +@Import({GatewayPreAuthenticationConfiguration.class, GatewayPreAuthenticationAutoConfiguration.WebUi.class}) @ConditionalOnGeoServerSecurityEnabled @SuppressWarnings("java:S1118") public class GatewayPreAuthenticationAutoConfiguration { diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/GatewaySharedAuthConfigProperties.java b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/GatewaySharedAuthConfigProperties.java index 1791d9919..ce9be38ac 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/GatewaySharedAuthConfigProperties.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/GatewaySharedAuthConfigProperties.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.autoconfigure.authzn; import lombok.Data; - import org.springframework.boot.context.properties.ConfigurationProperties; /** diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/GatewaySharedAuthenticationAutoConfiguration.java b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/GatewaySharedAuthenticationAutoConfiguration.java index d7574bf82..351f2e75c 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/GatewaySharedAuthenticationAutoConfiguration.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/GatewaySharedAuthenticationAutoConfiguration.java @@ -4,8 +4,9 @@ */ package org.geoserver.cloud.autoconfigure.authzn; +import java.util.Optional; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.autoconfigure.security.GeoServerSecurityAutoConfiguration; import org.geoserver.cloud.security.gateway.sharedauth.ClientConfiguration; import org.geoserver.cloud.security.gateway.sharedauth.DisabledConfiguration; @@ -24,10 +25,6 @@ import org.springframework.security.core.Authentication; import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; -import java.util.Optional; - -import javax.annotation.PostConstruct; - /** * {@link AutoConfiguration @AutoConfiguration} to enable sharing the webui form-based * authentication object with the other services. @@ -98,8 +95,7 @@ logged in through the WebUI, calls to other services (for example, in name = GatewaySharedAuthConfigProperties.AUTO_PROP, havingValue = "true", matchIfMissing = false) - GatewaySharedAuthenticationInitializer gatewaySharedAuthenticationInitializer( - GeoServerSecurityManager secManager) { + GatewaySharedAuthenticationInitializer gatewaySharedAuthenticationInitializer(GeoServerSecurityManager secManager) { return new GatewaySharedAuthenticationInitializer(secManager); } diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/PrioritizableLoginFormInfo.java b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/PrioritizableLoginFormInfo.java index 667ca1da8..e412ba555 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/PrioritizableLoginFormInfo.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/authzn/PrioritizableLoginFormInfo.java @@ -6,7 +6,6 @@ import lombok.Getter; import lombok.Setter; - import org.geoserver.platform.ExtensionPriority; import org.geoserver.web.LoginFormInfo; diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityAutoConfiguration.java b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityAutoConfiguration.java index 9a0fed637..9721a90b3 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityAutoConfiguration.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityAutoConfiguration.java @@ -18,10 +18,7 @@ @AutoConfiguration(before = GeoServerSecurityAutoConfiguration.class) @EnableConfigurationProperties(JDBCSecurityConfigProperties.class) @ConditionalOnGeoServerSecurityEnabled -@ConditionalOnProperty( - name = "geoserver.security.jdbc", - havingValue = "true", - matchIfMissing = true) +@ConditionalOnProperty(name = "geoserver.security.jdbc", havingValue = "true", matchIfMissing = true) @ImportResource( reader = FilteringXmlBeanDefinitionReader.class, // locations = "jar:gs-sec-jdbc-.*!/applicationContext.xml") diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityConfigProperties.java b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityConfigProperties.java index 399e03f28..bc54909c9 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityConfigProperties.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityConfigProperties.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.autoconfigure.security.jdbc; import lombok.Data; - import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties("geoserver.security") diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityWebUIAutoConfiguration.java b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityWebUIAutoConfiguration.java index 34d089737..40863fbae 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityWebUIAutoConfiguration.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityWebUIAutoConfiguration.java @@ -24,10 +24,7 @@ @EnableConfigurationProperties(JDBCSecurityConfigProperties.class) @ConditionalOnClass(AuthenticationFilterPanelInfo.class) @ConditionalOnGeoServerSecurityEnabled -@ConditionalOnProperty( - name = "geoserver.security.jdbc", - havingValue = "true", - matchIfMissing = true) +@ConditionalOnProperty(name = "geoserver.security.jdbc", havingValue = "true", matchIfMissing = true) @ImportResource( reader = FilteringXmlBeanDefinitionReader.class, // locations = "jar:gs-web-sec-jdbc-.*!/applicationContext.xml") diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityAutoConfiguration.java b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityAutoConfiguration.java index b9dbf9606..f444f2baf 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityAutoConfiguration.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityAutoConfiguration.java @@ -18,10 +18,7 @@ @AutoConfiguration(before = GeoServerSecurityAutoConfiguration.class) @EnableConfigurationProperties(LDAPSecurityConfigProperties.class) @ConditionalOnGeoServerSecurityEnabled -@ConditionalOnProperty( - name = "geoserver.security.ldap", - havingValue = "true", - matchIfMissing = true) +@ConditionalOnProperty(name = "geoserver.security.ldap", havingValue = "true", matchIfMissing = true) @ImportResource( reader = FilteringXmlBeanDefinitionReader.class, // locations = "jar:gs-sec-ldap-.*!/applicationContext.xml") diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityConfigProperties.java b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityConfigProperties.java index 2f3a5a69b..3c6a6178d 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityConfigProperties.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityConfigProperties.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.autoconfigure.security.ldap; import lombok.Data; - import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties("geoserver.security") diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityWebUIAutoConfiguration.java b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityWebUIAutoConfiguration.java index 7d44f50ac..4961c633f 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityWebUIAutoConfiguration.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityWebUIAutoConfiguration.java @@ -24,10 +24,7 @@ @EnableConfigurationProperties(LDAPSecurityConfigProperties.class) @ConditionalOnClass(AuthenticationFilterPanelInfo.class) @ConditionalOnGeoServerSecurityEnabled -@ConditionalOnProperty( - name = "geoserver.security.ldap", - havingValue = "true", - matchIfMissing = true) +@ConditionalOnProperty(name = "geoserver.security.ldap", havingValue = "true", matchIfMissing = true) @ImportResource( reader = FilteringXmlBeanDefinitionReader.class, // locations = "jar:gs-web-sec-ldap-.*!/applicationContext.xml") diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/GatewayPreAuthenticationFilter.java b/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/GatewayPreAuthenticationFilter.java index f9b7c048f..5e5652ea8 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/GatewayPreAuthenticationFilter.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/GatewayPreAuthenticationFilter.java @@ -4,22 +4,19 @@ */ package org.geoserver.cloud.security.gateway; -import lombok.extern.slf4j.Slf4j; - -import org.geoserver.security.filter.GeoServerRequestHeaderAuthenticationFilter; -import org.geoserver.security.filter.GeoServerSecurityFilter; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; - import java.io.IOException; - import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import lombok.extern.slf4j.Slf4j; +import org.geoserver.security.filter.GeoServerRequestHeaderAuthenticationFilter; +import org.geoserver.security.filter.GeoServerSecurityFilter; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.security.web.authentication.preauth.PreAuthenticatedAuthenticationToken; /** * @since 1.2 @@ -57,9 +54,7 @@ public void doFilter(final ServletRequest request, ServletResponse response, Fil boolean cached = cacheKey != null; boolean sessionAvailable = cacheAuthentication(postAuthentication, httpRequest); if (authenticated && cached && sessionAvailable) { - getSecurityManager() - .getAuthenticationCache() - .put(getName(), cacheKey, postAuthentication); + getSecurityManager().getAuthenticationCache().put(getName(), cacheKey, postAuthentication); } } diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/GatewayPreAuthenticationProvider.java b/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/GatewayPreAuthenticationProvider.java index 54e68d8c9..1d263990f 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/GatewayPreAuthenticationProvider.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/GatewayPreAuthenticationProvider.java @@ -14,8 +14,7 @@ public class GatewayPreAuthenticationProvider extends AbstractFilterProvider { @Override public void configure(XStreamPersister xp) { super.configure(xp); - xp.getXStream() - .alias("gatewayPreAuthentication", GatewayPreAuthenticationFilterConfig.class); + xp.getXStream().alias("gatewayPreAuthentication", GatewayPreAuthenticationFilterConfig.class); } @Override diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationFilter.java b/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationFilter.java index 4011e11ba..4c37cc0f3 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationFilter.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationFilter.java @@ -7,13 +7,22 @@ import static com.google.common.collect.Streams.stream; import com.google.common.collect.Streams; - +import java.io.IOException; +import java.util.Collection; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.Cookie; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import lombok.AccessLevel; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; import lombok.extern.slf4j.Slf4j; - import org.geoserver.security.GeoServerRoleConverter; import org.geoserver.security.config.PreAuthenticatedUserNameFilterConfig.PreAuthenticatedUserNameRoleSource; import org.geoserver.security.config.SecurityAuthFilterConfig; @@ -28,26 +37,12 @@ import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.util.StringUtils; -import java.io.IOException; -import java.util.Collection; -import java.util.stream.Collectors; -import java.util.stream.Stream; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.Cookie; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - /** * @since 1.9 */ @RequiredArgsConstructor(access = AccessLevel.PRIVATE) @Slf4j(topic = "org.geoserver.cloud.security.gateway.sharedauth") -class GatewaySharedAuthenticationFilter extends GeoServerSecurityFilter - implements GeoServerAuthenticationFilter { +class GatewaySharedAuthenticationFilter extends GeoServerSecurityFilter implements GeoServerAuthenticationFilter { static final String X_GSCLOUD_USERNAME = "x-gsc-username"; static final String X_GSCLOUD_ROLES = "x-gsc-roles"; @@ -155,8 +150,7 @@ private String getHeaders(HttpServletRequest req) { * header with a delimiter to handle mutliple values */ @Override - protected Collection getRolesFromHttpAttribute( - HttpServletRequest request, String principal) { + protected Collection getRolesFromHttpAttribute(HttpServletRequest request, String principal) { GeoServerRoleConverter roleConverter = super.getConverter(); @@ -182,9 +176,7 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha HttpServletResponse resp = (HttpServletResponse) response; HttpServletRequest req = (HttpServletRequest) request; - if (auth != null - && !(auth instanceof AnonymousAuthenticationToken) - && auth.isAuthenticated()) { + if (auth != null && !(auth instanceof AnonymousAuthenticationToken) && auth.isAuthenticated()) { setGatewayResponseHeaders(auth, req, resp); } else if (auth == null || auth instanceof AnonymousAuthenticationToken) { setEmptyUserResponseHeader(req, resp); @@ -198,8 +190,7 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha * requires for it to be explicitly set to clear it out from its session, just removing the * header wouldn't work. */ - private void setEmptyUserResponseHeader( - HttpServletRequest req, HttpServletResponse response) { + private void setEmptyUserResponseHeader(HttpServletRequest req, HttpServletResponse response) { response.setHeader(X_GSCLOUD_USERNAME, ""); if (log.isDebugEnabled()) { String gatewaySessionId = getGatewaySessionId(req); @@ -218,10 +209,7 @@ private void setGatewayResponseHeaders( if (null != username) { response.setHeader(X_GSCLOUD_USERNAME, username); preAuth.getAuthorities() - .forEach( - authority -> - response.addHeader( - X_GSCLOUD_ROLES, authority.getAuthority())); + .forEach(authority -> response.addHeader(X_GSCLOUD_ROLES, authority.getAuthority())); if (log.isDebugEnabled()) { String gatewaySessionId = getGatewaySessionId(req); log.debug( diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationInitializer.java b/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationInitializer.java index e8519683f..119984f2c 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationInitializer.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationInitializer.java @@ -4,10 +4,15 @@ */ package org.geoserver.cloud.security.gateway.sharedauth; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; import lombok.NonNull; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.security.gateway.sharedauth.GatewaySharedAuthenticationFilter.Config; import org.geoserver.platform.ContextLoadedEvent; import org.geoserver.platform.resource.Resource; @@ -20,13 +25,6 @@ import org.springframework.context.ApplicationListener; import org.springframework.core.Ordered; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - /** * Upon a GeoServer {@link ContextLoadedEvent}, creates the {@link * GatewaySharedAuthenticationFilter} filter in the {@link GeoServerSecurityManager} configuration, @@ -36,17 +34,15 @@ */ @Slf4j(topic = "org.geoserver.cloud.security.gateway.sharedauth") @RequiredArgsConstructor -public class GatewaySharedAuthenticationInitializer - implements ApplicationListener, Ordered { +public class GatewaySharedAuthenticationInitializer implements ApplicationListener, Ordered { - @NonNull private final GeoServerSecurityManager securityManager; + @NonNull + private final GeoServerSecurityManager securityManager; @Override public void onApplicationEvent(ContextLoadedEvent event) { if (!filterIsMissing()) { - log.info( - "{} config is present.", - GatewaySharedAuthenticationFilter.class.getSimpleName()); + log.info("{} config is present.", GatewaySharedAuthenticationFilter.class.getSimpleName()); return; } log.info( @@ -79,15 +75,12 @@ private void addToFilterChains(Config filterConfig) throws Exception { final Set applyTo = Set.of("web", "rest", "gwc", "default"); - filterChain - .getRequestChains() - .forEach( - requestFiltersChain -> { - String chainName = requestFiltersChain.getName(); - if (applyTo.contains(chainName)) { - addToFilterChain(requestFiltersChain, filterName); - } - }); + filterChain.getRequestChains().forEach(requestFiltersChain -> { + String chainName = requestFiltersChain.getName(); + if (applyTo.contains(chainName)) { + addToFilterChain(requestFiltersChain, filterName); + } + }); securityManager.saveSecurityConfig(config); log.info("SecurityManagerConfig saved"); @@ -100,8 +93,7 @@ private void addToFilterChain(RequestFilterChain requestFiltersChain, String fil "Filter chain {} already contains {} -> {}", requestFiltersChain.getName(), filterName, - requestFiltersChain.getFilterNames().stream() - .collect(Collectors.joining(", "))); + requestFiltersChain.getFilterNames().stream().collect(Collectors.joining(", "))); } else { if (filterNames.contains("anonymous")) { // anonymous must always be the last one if present @@ -116,14 +108,15 @@ private void addToFilterChain(RequestFilterChain requestFiltersChain, String fil "Applied filter {} to filter chain {} -> {}", filterName, requestFiltersChain.getName(), - requestFiltersChain.getFilterNames().stream() - .collect(Collectors.joining(", "))); + requestFiltersChain.getFilterNames().stream().collect(Collectors.joining(", "))); } } private boolean filterIsMissing() { try { - return securityManager.listFilters(GatewaySharedAuthenticationFilter.class).isEmpty(); + return securityManager + .listFilters(GatewaySharedAuthenticationFilter.class) + .isEmpty(); } catch (IOException e) { throw new UncheckedIOException(e); } diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationProvider.java b/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationProvider.java index 2674eeb21..d0d09bcfe 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationProvider.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/GatewaySharedAuthenticationProvider.java @@ -5,10 +5,8 @@ package org.geoserver.cloud.security.gateway.sharedauth; import com.thoughtworks.xstream.XStream; - import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.config.util.XStreamPersister; import org.geoserver.security.config.SecurityNamedServiceConfig; import org.geoserver.security.filter.AbstractFilterProvider; @@ -40,9 +38,7 @@ public void configure(XStreamPersister xp) { XStream xStream = xp.getXStream(); xStream.allowTypes(new Class[] {GatewaySharedAuthenticationFilter.Config.class}); xStream.alias("gatewaySharedAuthentication", GatewaySharedAuthenticationProvider.class); - xStream.alias( - "gatewaySharedAuthenticationFilter", - GatewaySharedAuthenticationFilter.Config.class); + xStream.alias("gatewaySharedAuthenticationFilter", GatewaySharedAuthenticationFilter.Config.class); } @Override diff --git a/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/ServerConfiguration.java b/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/ServerConfiguration.java index 251ab733d..2930d2a47 100644 --- a/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/ServerConfiguration.java +++ b/src/starters/security/src/main/java/org/geoserver/cloud/security/gateway/sharedauth/ServerConfiguration.java @@ -58,8 +58,7 @@ public GatewaySharedAuthFilterPanelInfo() { public static class GatewaySharedAuthAuthFilterPanel extends AuthenticationFilterPanel { - public GatewaySharedAuthAuthFilterPanel( - String id, IModel model) { + public GatewaySharedAuthAuthFilterPanel(String id, IModel model) { super(id, model); } } diff --git a/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/authzn/AuthKeyAutoConfigurationTest.java b/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/authzn/AuthKeyAutoConfigurationTest.java index 160d9e319..7402ce634 100644 --- a/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/authzn/AuthKeyAutoConfigurationTest.java +++ b/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/authzn/AuthKeyAutoConfigurationTest.java @@ -33,8 +33,7 @@ class AuthKeyAutoConfigurationTest { private WebApplicationContextRunner contextRunner = - new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AuthKeyAutoConfiguration.class)); + new WebApplicationContextRunner().withConfiguration(AutoConfigurations.of(AuthKeyAutoConfiguration.class)); @BeforeEach void mockBeanDependencies() { @@ -46,11 +45,9 @@ void mockBeanDependencies() { void testModuleStatus_disabled_by_default() { contextRunner .run(context -> assertThat(context).hasBean("authKeyExtension")) - .run( - context -> - assertThat(context) - .getBean("authKeyExtension", ModuleStatus.class) - .hasFieldOrPropertyWithValue("enabled", false)); + .run(context -> assertThat(context) + .getBean("authKeyExtension", ModuleStatus.class) + .hasFieldOrPropertyWithValue("enabled", false)); } @Test @@ -58,11 +55,9 @@ void testModuleStatus_enabled() { contextRunner .withPropertyValues("geoserver.security.authkey=true") .run(context -> assertThat(context).hasBean("authKeyExtension")) - .run( - context -> - assertThat(context) - .getBean("authKeyExtension", ModuleStatus.class) - .hasFieldOrPropertyWithValue("enabled", true)); + .run(context -> assertThat(context) + .getBean("authKeyExtension", ModuleStatus.class) + .hasFieldOrPropertyWithValue("enabled", true)); } @Test @@ -70,11 +65,9 @@ void testModuleStatus_disabled() { contextRunner .withPropertyValues("geoserver.security.authkey=false") .run(context -> assertThat(context).hasBean("authKeyExtension")) - .run( - context -> - assertThat(context) - .getBean("authKeyExtension", ModuleStatus.class) - .hasFieldOrPropertyWithValue("enabled", false)); + .run(context -> assertThat(context) + .getBean("authKeyExtension", ModuleStatus.class) + .hasFieldOrPropertyWithValue("enabled", false)); } @Test @@ -84,38 +77,27 @@ void testGeoServerAuthenticationKeyProvider_enabled_no_GsWebSecCore_InClasspath( // AuthenticationFilterPanel is from gs-web-sec-core, used as @ConditionalOnClass to // enabled the web-ui components .withClassLoader(new FilteredClassLoader(AuthenticationFilterPanel.class)) - .run( - ctx -> { - assertThat(ctx).doesNotHaveBean(AuthenticationKeyFilterPanelInfo.class); - assertThat(ctx) - .doesNotHaveBean(GeoServerRestRoleServicePanelInfo.class); - assertThat(ctx) - .doesNotHaveBean( - WebServiceBodyResponseUserGroupServicePanelInfo.class); - }); + .run(ctx -> { + assertThat(ctx).doesNotHaveBean(AuthenticationKeyFilterPanelInfo.class); + assertThat(ctx).doesNotHaveBean(GeoServerRestRoleServicePanelInfo.class); + assertThat(ctx).doesNotHaveBean(WebServiceBodyResponseUserGroupServicePanelInfo.class); + }); } @Test void testGeoServerAuthenticationKeyProvider_enabled() { - contextRunner - .withPropertyValues("geoserver.security.authkey=true") - .run( - ctx -> { - assertThat(ctx).hasSingleBean(GeoServerAuthenticationKeyProvider.class); - assertThat(ctx).hasSingleBean(AuthenticationKeyMangler.class); - assertThat(ctx).hasSingleBean(PropertyAuthenticationKeyMapper.class); - assertThat(ctx) - .hasSingleBean(UserPropertyAuthenticationKeyMapper.class); - assertThat(ctx).hasSingleBean(WebServiceAuthenticationKeyMapper.class); - assertThat(ctx).hasSingleBean(GeoServerAuthenticationKeyProvider.class); - assertThat(ctx) - .hasSingleBean(WebServiceBodyResponseSecurityProvider.class); + contextRunner.withPropertyValues("geoserver.security.authkey=true").run(ctx -> { + assertThat(ctx).hasSingleBean(GeoServerAuthenticationKeyProvider.class); + assertThat(ctx).hasSingleBean(AuthenticationKeyMangler.class); + assertThat(ctx).hasSingleBean(PropertyAuthenticationKeyMapper.class); + assertThat(ctx).hasSingleBean(UserPropertyAuthenticationKeyMapper.class); + assertThat(ctx).hasSingleBean(WebServiceAuthenticationKeyMapper.class); + assertThat(ctx).hasSingleBean(GeoServerAuthenticationKeyProvider.class); + assertThat(ctx).hasSingleBean(WebServiceBodyResponseSecurityProvider.class); - assertThat(ctx).hasSingleBean(AuthenticationKeyFilterPanelInfo.class); - assertThat(ctx) - .hasSingleBean( - WebServiceBodyResponseUserGroupServicePanelInfo.class); - assertThat(ctx).hasSingleBean(GeoServerRestRoleServicePanelInfo.class); - }); + assertThat(ctx).hasSingleBean(AuthenticationKeyFilterPanelInfo.class); + assertThat(ctx).hasSingleBean(WebServiceBodyResponseUserGroupServicePanelInfo.class); + assertThat(ctx).hasSingleBean(GeoServerRestRoleServicePanelInfo.class); + }); } } diff --git a/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityAutoConfigurationTest.java b/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityAutoConfigurationTest.java index 15574c9e5..433038b81 100644 --- a/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityAutoConfigurationTest.java +++ b/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityAutoConfigurationTest.java @@ -15,32 +15,24 @@ class JDBCSecurityAutoConfigurationTest { - private WebApplicationContextRunner runner = - new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(JDBCSecurityAutoConfiguration.class)) - .withBean( - GeoServerSecurityManager.class, - () -> mock(GeoServerSecurityManager.class)); + private WebApplicationContextRunner runner = new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(JDBCSecurityAutoConfiguration.class)) + .withBean(GeoServerSecurityManager.class, () -> mock(GeoServerSecurityManager.class)); @Test void testExpectedBeans() { - runner.run( - context -> - assertThat(context) - .hasNotFailed() - .hasSingleBean(JDBCSecurityProvider.class) - .getBean(JDBCSecurityConfigProperties.class) - .hasFieldOrPropertyWithValue("jdbc", true)); + runner.run(context -> assertThat(context) + .hasNotFailed() + .hasSingleBean(JDBCSecurityProvider.class) + .getBean(JDBCSecurityConfigProperties.class) + .hasFieldOrPropertyWithValue("jdbc", true)); } @Test void testDisabled() { - runner.withPropertyValues("geoserver.security.jdbc=false") - .run( - context -> - assertThat(context) - .hasNotFailed() - .doesNotHaveBean(JDBCSecurityProvider.class) - .doesNotHaveBean(JDBCSecurityConfigProperties.class)); + runner.withPropertyValues("geoserver.security.jdbc=false").run(context -> assertThat(context) + .hasNotFailed() + .doesNotHaveBean(JDBCSecurityProvider.class) + .doesNotHaveBean(JDBCSecurityConfigProperties.class)); } } diff --git a/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityWebUIAutoConfigurationTest.java b/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityWebUIAutoConfigurationTest.java index 0177ef7a0..571f0476c 100644 --- a/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityWebUIAutoConfigurationTest.java +++ b/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/security/jdbc/JDBCSecurityWebUIAutoConfigurationTest.java @@ -20,53 +20,41 @@ class JDBCSecurityWebUIAutoConfigurationTest { - private WebApplicationContextRunner runner = - new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of( - JDBCSecurityAutoConfiguration.class, - JDBCSecurityWebUIAutoConfiguration.class)) - .withBean( - GeoServerSecurityManager.class, - () -> mock(GeoServerSecurityManager.class)); + private WebApplicationContextRunner runner = new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + JDBCSecurityAutoConfiguration.class, JDBCSecurityWebUIAutoConfiguration.class)) + .withBean(GeoServerSecurityManager.class, () -> mock(GeoServerSecurityManager.class)); @Test void testConditionalOnClassNoMatch() { runner.withClassLoader(new FilteredClassLoader(AuthenticationFilterPanelInfo.class)) - .run( - context -> - assertThat(context) - .hasNotFailed() - .doesNotHaveBean(JDBCUserGroupServicePanelInfo.class) - .doesNotHaveBean(JDBCRoleServicePanelInfo.class) - .doesNotHaveBean(JDBCAuthProviderPanelInfo.class) - .doesNotHaveBean("jdbcSecurityWebExtension")); + .run(context -> assertThat(context) + .hasNotFailed() + .doesNotHaveBean(JDBCUserGroupServicePanelInfo.class) + .doesNotHaveBean(JDBCRoleServicePanelInfo.class) + .doesNotHaveBean(JDBCAuthProviderPanelInfo.class) + .doesNotHaveBean("jdbcSecurityWebExtension")); } @Test void testConditionalOnClassMatch() { - runner.run( - context -> - assertThat(context) - .hasNotFailed() - .hasSingleBean(JDBCUserGroupServicePanelInfo.class) - .hasSingleBean(JDBCRoleServicePanelInfo.class) - .hasSingleBean(JDBCAuthProviderPanelInfo.class) - .hasBean("jdbcSecurityWebExtension") - .getBean("jdbcSecurityWebExtension") - .isInstanceOf(ModuleStatusImpl.class)); + runner.run(context -> assertThat(context) + .hasNotFailed() + .hasSingleBean(JDBCUserGroupServicePanelInfo.class) + .hasSingleBean(JDBCRoleServicePanelInfo.class) + .hasSingleBean(JDBCAuthProviderPanelInfo.class) + .hasBean("jdbcSecurityWebExtension") + .getBean("jdbcSecurityWebExtension") + .isInstanceOf(ModuleStatusImpl.class)); } @Test void testDisabled() { - runner.withPropertyValues("geoserver.security.jdbc=false") - .run( - context -> - assertThat(context) - .hasNotFailed() - .doesNotHaveBean(JDBCUserGroupServicePanelInfo.class) - .doesNotHaveBean(JDBCRoleServicePanelInfo.class) - .doesNotHaveBean(JDBCAuthProviderPanelInfo.class) - .doesNotHaveBean("jdbcSecurityWebExtension")); + runner.withPropertyValues("geoserver.security.jdbc=false").run(context -> assertThat(context) + .hasNotFailed() + .doesNotHaveBean(JDBCUserGroupServicePanelInfo.class) + .doesNotHaveBean(JDBCRoleServicePanelInfo.class) + .doesNotHaveBean(JDBCAuthProviderPanelInfo.class) + .doesNotHaveBean("jdbcSecurityWebExtension")); } } diff --git a/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityAutoConfigurationTest.java b/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityAutoConfigurationTest.java index b8eb8224b..69842177d 100644 --- a/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityAutoConfigurationTest.java +++ b/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityAutoConfigurationTest.java @@ -16,32 +16,24 @@ class LDAPSecurityAutoConfigurationTest { - private WebApplicationContextRunner runner = - new WebApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(LDAPSecurityAutoConfiguration.class)) - .withBean( - GeoServerSecurityManager.class, - () -> mock(GeoServerSecurityManager.class)); + private WebApplicationContextRunner runner = new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(LDAPSecurityAutoConfiguration.class)) + .withBean(GeoServerSecurityManager.class, () -> mock(GeoServerSecurityManager.class)); @Test void testExpectedBeans() { - runner.run( - context -> - assertThat(context) - .hasNotFailed() - .hasSingleBean(LDAPSecurityProvider.class) - .getBean(LDAPSecurityConfigProperties.class) - .hasFieldOrPropertyWithValue("ldap", true)); + runner.run(context -> assertThat(context) + .hasNotFailed() + .hasSingleBean(LDAPSecurityProvider.class) + .getBean(LDAPSecurityConfigProperties.class) + .hasFieldOrPropertyWithValue("ldap", true)); } @Test void testDisabled() { - runner.withPropertyValues("geoserver.security.ldap=false") - .run( - context -> - assertThat(context) - .hasNotFailed() - .doesNotHaveBean(LDAPSecurityProvider.class) - .doesNotHaveBean(JDBCSecurityConfigProperties.class)); + runner.withPropertyValues("geoserver.security.ldap=false").run(context -> assertThat(context) + .hasNotFailed() + .doesNotHaveBean(LDAPSecurityProvider.class) + .doesNotHaveBean(JDBCSecurityConfigProperties.class)); } } diff --git a/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityWebUIAutoConfigurationTest.java b/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityWebUIAutoConfigurationTest.java index 490e43a18..74733f38f 100644 --- a/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityWebUIAutoConfigurationTest.java +++ b/src/starters/security/src/test/java/org/geoserver/cloud/autoconfigure/security/ldap/LDAPSecurityWebUIAutoConfigurationTest.java @@ -20,53 +20,41 @@ class LDAPSecurityWebUIAutoConfigurationTest { - private WebApplicationContextRunner runner = - new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of( - LDAPSecurityAutoConfiguration.class, - LDAPSecurityWebUIAutoConfiguration.class)) - .withBean( - GeoServerSecurityManager.class, - () -> mock(GeoServerSecurityManager.class)); + private WebApplicationContextRunner runner = new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of( + LDAPSecurityAutoConfiguration.class, LDAPSecurityWebUIAutoConfiguration.class)) + .withBean(GeoServerSecurityManager.class, () -> mock(GeoServerSecurityManager.class)); @Test void testConditionalOnClassNoMatch() { runner.withClassLoader(new FilteredClassLoader(AuthenticationFilterPanelInfo.class)) - .run( - context -> - assertThat(context) - .hasNotFailed() - .doesNotHaveBean(LDAPUserGroupServicePanelInfo.class) - .doesNotHaveBean(LDAPRoleServicePanelInfo.class) - .doesNotHaveBean(LDAPAuthProviderPanelInfo.class) - .doesNotHaveBean("ldapSecurityWebExtension")); + .run(context -> assertThat(context) + .hasNotFailed() + .doesNotHaveBean(LDAPUserGroupServicePanelInfo.class) + .doesNotHaveBean(LDAPRoleServicePanelInfo.class) + .doesNotHaveBean(LDAPAuthProviderPanelInfo.class) + .doesNotHaveBean("ldapSecurityWebExtension")); } @Test void testConditionalOnClassMatch() { - runner.run( - context -> - assertThat(context) - .hasNotFailed() - .hasSingleBean(LDAPUserGroupServicePanelInfo.class) - .hasSingleBean(LDAPRoleServicePanelInfo.class) - .hasSingleBean(LDAPAuthProviderPanelInfo.class) - .hasBean("ldapSecurityWebExtension") - .getBean("ldapSecurityWebExtension") - .isInstanceOf(ModuleStatusImpl.class)); + runner.run(context -> assertThat(context) + .hasNotFailed() + .hasSingleBean(LDAPUserGroupServicePanelInfo.class) + .hasSingleBean(LDAPRoleServicePanelInfo.class) + .hasSingleBean(LDAPAuthProviderPanelInfo.class) + .hasBean("ldapSecurityWebExtension") + .getBean("ldapSecurityWebExtension") + .isInstanceOf(ModuleStatusImpl.class)); } @Test void testDisabled() { - runner.withPropertyValues("geoserver.security.ldap=false") - .run( - context -> - assertThat(context) - .hasNotFailed() - .doesNotHaveBean(LDAPUserGroupServicePanelInfo.class) - .doesNotHaveBean(LDAPRoleServicePanelInfo.class) - .doesNotHaveBean(LDAPAuthProviderPanelInfo.class) - .doesNotHaveBean("ldapSecurityWebExtension")); + runner.withPropertyValues("geoserver.security.ldap=false").run(context -> assertThat(context) + .hasNotFailed() + .doesNotHaveBean(LDAPUserGroupServicePanelInfo.class) + .doesNotHaveBean(LDAPRoleServicePanelInfo.class) + .doesNotHaveBean(LDAPAuthProviderPanelInfo.class) + .doesNotHaveBean("ldapSecurityWebExtension")); } } diff --git a/src/starters/spring-boot/src/main/java/org/geoserver/cloud/app/ExitOnApplicationEventAutoConfiguration.java b/src/starters/spring-boot/src/main/java/org/geoserver/cloud/app/ExitOnApplicationEventAutoConfiguration.java index 989882ea6..5f25efac4 100644 --- a/src/starters/spring-boot/src/main/java/org/geoserver/cloud/app/ExitOnApplicationEventAutoConfiguration.java +++ b/src/starters/spring-boot/src/main/java/org/geoserver/cloud/app/ExitOnApplicationEventAutoConfiguration.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.app; import lombok.extern.slf4j.Slf4j; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationRunner; @@ -84,7 +83,8 @@ public enum ExitOn { onReady } - @Autowired private ApplicationContext appContext; + @Autowired + private ApplicationContext appContext; @Value("${spring.context.exit}") ExitOn exitOn; diff --git a/src/starters/spring-boot/src/main/java/org/geoserver/cloud/app/ServiceIdFilterAutoConfiguration.java b/src/starters/spring-boot/src/main/java/org/geoserver/cloud/app/ServiceIdFilterAutoConfiguration.java index 5151fbb72..ee2222b86 100644 --- a/src/starters/spring-boot/src/main/java/org/geoserver/cloud/app/ServiceIdFilterAutoConfiguration.java +++ b/src/starters/spring-boot/src/main/java/org/geoserver/cloud/app/ServiceIdFilterAutoConfiguration.java @@ -4,6 +4,12 @@ */ package org.geoserver.cloud.app; +import java.io.IOException; +import javax.servlet.FilterChain; +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletResponse; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -13,14 +19,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; -import java.io.IOException; - -import javax.servlet.FilterChain; -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletResponse; - /** * Auto configuration to log basic application info at {@link ApplicationReadyEvent app startup} * @@ -32,10 +30,7 @@ @Configuration(proxyBeanMethods = false) @ConditionalOnWebApplication @ConditionalOnClass(javax.servlet.Filter.class) -@ConditionalOnProperty( - name = "geoserver.debug.instanceId", - havingValue = "true", - matchIfMissing = false) +@ConditionalOnProperty(name = "geoserver.debug.instanceId", havingValue = "true", matchIfMissing = false) public class ServiceIdFilterAutoConfiguration { static class ServiceIdFilter implements javax.servlet.Filter { diff --git a/src/starters/spring-boot/src/main/java/org/geoserver/cloud/app/StartupLogger.java b/src/starters/spring-boot/src/main/java/org/geoserver/cloud/app/StartupLogger.java index 8fcbd8964..dbac6dbf6 100644 --- a/src/starters/spring-boot/src/main/java/org/geoserver/cloud/app/StartupLogger.java +++ b/src/starters/spring-boot/src/main/java/org/geoserver/cloud/app/StartupLogger.java @@ -5,7 +5,6 @@ package org.geoserver.cloud.app; import lombok.extern.slf4j.Slf4j; - import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.event.EventListener; import org.springframework.core.env.ConfigurableEnvironment; diff --git a/src/starters/spring-boot/src/test/java/org/geoserver/cloud/app/ServiceIdFilterAutoConfigurationTest.java b/src/starters/spring-boot/src/test/java/org/geoserver/cloud/app/ServiceIdFilterAutoConfigurationTest.java index 41f51e7c4..7c89ce6f0 100644 --- a/src/starters/spring-boot/src/test/java/org/geoserver/cloud/app/ServiceIdFilterAutoConfigurationTest.java +++ b/src/starters/spring-boot/src/test/java/org/geoserver/cloud/app/ServiceIdFilterAutoConfigurationTest.java @@ -9,6 +9,9 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; +import javax.servlet.Filter; +import javax.servlet.FilterChain; +import javax.servlet.ServletRequest; import org.junit.jupiter.api.Test; import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.test.context.FilteredClassLoader; @@ -17,20 +20,14 @@ import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; -import javax.servlet.Filter; -import javax.servlet.FilterChain; -import javax.servlet.ServletRequest; - /** * @since 1.0 */ class ServiceIdFilterAutoConfigurationTest { - WebApplicationContextRunner webappRunner = - new WebApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(ServiceIdFilterAutoConfiguration.class)) - .withPropertyValues("info.instance-id=test-instance-id"); + WebApplicationContextRunner webappRunner = new WebApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(ServiceIdFilterAutoConfiguration.class)) + .withPropertyValues("info.instance-id=test-instance-id"); @Test void testDisabledByDefault() { @@ -47,11 +44,9 @@ void testConditionalOnClassServletFilterUnmet() { @Test void testOnWebApplicationConditionUnmet() { - ApplicationContextRunner notAWebAppRunner = - new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(ServiceIdFilterAutoConfiguration.class)) - .withPropertyValues("geoserver.debug.instanceId=true"); + ApplicationContextRunner notAWebAppRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(ServiceIdFilterAutoConfiguration.class)) + .withPropertyValues("geoserver.debug.instanceId=true"); notAWebAppRunner.run(context -> assertThat(context).doesNotHaveBean("serviceIdFilter")); } @@ -61,17 +56,15 @@ void testEnabledAndAllConditionalsMet() { webappRunner .withPropertyValues( // "geoserver.debug.instanceId=true") - .run( - context -> { - assertThat(context).hasBean("serviceIdFilter"); - Filter servletFilter = context.getBean("serviceIdFilter", Filter.class); - ServletRequest req = new MockHttpServletRequest(); - MockHttpServletResponse resp = new MockHttpServletResponse(); - FilterChain chain = mock(FilterChain.class); - servletFilter.doFilter(req, resp, chain); - assertEquals( - "test-instance-id", resp.getHeader("X-gs-cloud-service-id")); - verify(chain).doFilter(req, resp); - }); + .run(context -> { + assertThat(context).hasBean("serviceIdFilter"); + Filter servletFilter = context.getBean("serviceIdFilter", Filter.class); + ServletRequest req = new MockHttpServletRequest(); + MockHttpServletResponse resp = new MockHttpServletResponse(); + FilterChain chain = mock(FilterChain.class); + servletFilter.doFilter(req, resp, chain); + assertEquals("test-instance-id", resp.getHeader("X-gs-cloud-service-id")); + verify(chain).doFilter(req, resp); + }); } } diff --git a/src/starters/webmvc/src/main/java/org/geoserver/cloud/autoconfigure/context/GeoServerContextInitializer.java b/src/starters/webmvc/src/main/java/org/geoserver/cloud/autoconfigure/context/GeoServerContextInitializer.java index 0a8a5c499..4f64a2f21 100644 --- a/src/starters/webmvc/src/main/java/org/geoserver/cloud/autoconfigure/context/GeoServerContextInitializer.java +++ b/src/starters/webmvc/src/main/java/org/geoserver/cloud/autoconfigure/context/GeoServerContextInitializer.java @@ -4,17 +4,15 @@ */ package org.geoserver.cloud.autoconfigure.context; -import org.geoserver.GeoserverInitStartupListener; -import org.springframework.context.ApplicationContextInitializer; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.web.context.support.GenericWebApplicationContext; - import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; - import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; +import org.geoserver.GeoserverInitStartupListener; +import org.springframework.context.ApplicationContextInitializer; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.web.context.support.GenericWebApplicationContext; /** * {@link ApplicationContextInitializer} replacing upstream's {@link GeoserverInitStartupListener}, @@ -25,8 +23,7 @@ * * @since 1.0 */ -public class GeoServerContextInitializer - implements ApplicationContextInitializer { +public class GeoServerContextInitializer implements ApplicationContextInitializer { @Override public void initialize(ConfigurableApplicationContext applicationContext) { @@ -53,16 +50,13 @@ public void initialize(ConfigurableApplicationContext applicationContext) { } protected ServletContext mockServletContext() { - InvocationHandler handler = - new InvocationHandler() { - @Override - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { - return null; - } - }; + InvocationHandler handler = new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + return null; + } + }; return (ServletContext) - Proxy.newProxyInstance( - getClass().getClassLoader(), new Class[] {ServletContext.class}, handler); + Proxy.newProxyInstance(getClass().getClassLoader(), new Class[] {ServletContext.class}, handler); } } diff --git a/src/starters/webmvc/src/main/java/org/geoserver/cloud/autoconfigure/servlet/GeoServerServletContextAutoConfiguration.java b/src/starters/webmvc/src/main/java/org/geoserver/cloud/autoconfigure/servlet/GeoServerServletContextAutoConfiguration.java index 96a3bb186..96f6c5d4b 100644 --- a/src/starters/webmvc/src/main/java/org/geoserver/cloud/autoconfigure/servlet/GeoServerServletContextAutoConfiguration.java +++ b/src/starters/webmvc/src/main/java/org/geoserver/cloud/autoconfigure/servlet/GeoServerServletContextAutoConfiguration.java @@ -4,22 +4,16 @@ */ package org.geoserver.cloud.autoconfigure.servlet; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.geoserver.cloud.autoconfigure.core.GeoServerWebMvcMainAutoConfiguration; import org.geoserver.cloud.config.servlet.GeoServerServletContextConfiguration; import org.springframework.boot.autoconfigure.AutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.annotation.Import; -import javax.annotation.PostConstruct; - @AutoConfiguration(after = GeoServerWebMvcMainAutoConfiguration.class) -@ConditionalOnProperty( - prefix = "geoserver.servlet", - name = "enabled", - havingValue = "true", - matchIfMissing = true) +@ConditionalOnProperty(prefix = "geoserver.servlet", name = "enabled", havingValue = "true", matchIfMissing = true) @Import(GeoServerServletContextConfiguration.class) @Slf4j public class GeoServerServletContextAutoConfiguration { @@ -32,8 +26,7 @@ public class GeoServerServletContextAutoConfiguration { matchIfMissing = false) public static class Disabled { public @PostConstruct void log() { - log.info( - "GeoServer servlet-context auto-configuration disabled explicitly through config property"); + log.info("GeoServer servlet-context auto-configuration disabled explicitly through config property"); } } } diff --git a/src/starters/webmvc/src/main/java/org/geoserver/cloud/config/main/GeoServerMainModuleConfiguration.java b/src/starters/webmvc/src/main/java/org/geoserver/cloud/config/main/GeoServerMainModuleConfiguration.java index 90e6fdf3b..d368ddb6c 100644 --- a/src/starters/webmvc/src/main/java/org/geoserver/cloud/config/main/GeoServerMainModuleConfiguration.java +++ b/src/starters/webmvc/src/main/java/org/geoserver/cloud/config/main/GeoServerMainModuleConfiguration.java @@ -58,8 +58,7 @@ reader = FilteringXmlBeanDefinitionReader.class, // // exclude beans locations = - "jar:gs-main-.*!/applicationContext.xml#name=" - + GeoServerMainModuleConfiguration.EXCLUDE_BEANS_REGEX) + "jar:gs-main-.*!/applicationContext.xml#name=" + GeoServerMainModuleConfiguration.EXCLUDE_BEANS_REGEX) public class GeoServerMainModuleConfiguration { private static final String UNUSED_BEAN_NAMES = @@ -97,6 +96,5 @@ public class GeoServerMainModuleConfiguration { |layerGroupContainmentCache\ """; - static final String EXCLUDE_BEANS_REGEX = - "^(?!" + OVERRIDDEN_BEAN_NAMES + "|" + UNUSED_BEAN_NAMES + ").*$"; + static final String EXCLUDE_BEANS_REGEX = "^(?!" + OVERRIDDEN_BEAN_NAMES + "|" + UNUSED_BEAN_NAMES + ").*$"; } diff --git a/src/starters/webmvc/src/main/java/org/geoserver/cloud/config/servlet/GeoServerServletContextConfiguration.java b/src/starters/webmvc/src/main/java/org/geoserver/cloud/config/servlet/GeoServerServletContextConfiguration.java index 5c84bd5fc..7986bac00 100644 --- a/src/starters/webmvc/src/main/java/org/geoserver/cloud/config/servlet/GeoServerServletContextConfiguration.java +++ b/src/starters/webmvc/src/main/java/org/geoserver/cloud/config/servlet/GeoServerServletContextConfiguration.java @@ -4,6 +4,7 @@ */ package org.geoserver.cloud.config.servlet; +import javax.servlet.Filter; import org.geoserver.filters.FlushSafeFilter; import org.geoserver.filters.SessionDebugFilter; import org.geoserver.filters.SpringDelegatingFilter; @@ -17,8 +18,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.web.context.request.RequestContextListener; -import javax.servlet.Filter; - @Configuration public class GeoServerServletContextConfiguration { diff --git a/src/starters/webmvc/src/main/java/org/geoserver/cloud/config/servlet/GeoServerServletInitializer.java b/src/starters/webmvc/src/main/java/org/geoserver/cloud/config/servlet/GeoServerServletInitializer.java index cfd41bdda..382c6299d 100644 --- a/src/starters/webmvc/src/main/java/org/geoserver/cloud/config/servlet/GeoServerServletInitializer.java +++ b/src/starters/webmvc/src/main/java/org/geoserver/cloud/config/servlet/GeoServerServletInitializer.java @@ -6,7 +6,6 @@ import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.platform.ContextLoadedEvent; import org.geoserver.platform.GeoServerContextLoaderListener; import org.springframework.boot.web.servlet.ServletContextInitializer; diff --git a/src/starters/webmvc/src/main/java/org/geoserver/cloud/virtualservice/VirtualServiceVerifier.java b/src/starters/webmvc/src/main/java/org/geoserver/cloud/virtualservice/VirtualServiceVerifier.java index 9ff69e11d..255bbfb35 100644 --- a/src/starters/webmvc/src/main/java/org/geoserver/cloud/virtualservice/VirtualServiceVerifier.java +++ b/src/starters/webmvc/src/main/java/org/geoserver/cloud/virtualservice/VirtualServiceVerifier.java @@ -4,9 +4,9 @@ */ package org.geoserver.cloud.virtualservice; +import java.util.Optional; import lombok.NonNull; import lombok.RequiredArgsConstructor; - import org.geoserver.catalog.Catalog; import org.geoserver.catalog.LayerGroupInfo; import org.geoserver.catalog.PublishedInfo; @@ -14,8 +14,6 @@ import org.springframework.http.HttpStatus; import org.springframework.web.server.ResponseStatusException; -import java.util.Optional; - /** * Helper service for OWS controllers to verify the existence of virtual services before proceeding. * @@ -42,9 +40,7 @@ public void checkVirtualService(@NonNull String virtualService) { * and layer to a {@link PublishedInfo} inside it */ public void checkVirtualService(String virtualService, String layer) { - WorkspaceInfo ws = - findWorkspace(virtualService) - .orElseThrow(() -> virtualServiceNotFound(virtualService)); + WorkspaceInfo ws = findWorkspace(virtualService).orElseThrow(() -> virtualServiceNotFound(virtualService)); findPublished(ws.getName(), layer).orElseThrow(() -> layerNotFound(virtualService, layer)); } @@ -67,8 +63,7 @@ private Optional findPublished(String workspace, String layer) { private ResponseStatusException virtualServiceNotFound(String service) { return new ResponseStatusException( - HttpStatus.NOT_FOUND, - "Workspace or global LayerGroup does not exist: %s".formatted(service)); + HttpStatus.NOT_FOUND, "Workspace or global LayerGroup does not exist: %s".formatted(service)); } private ResponseStatusException layerNotFound(String workspace, String layer) { diff --git a/src/starters/webmvc/src/test/java/org/geoserver/cloud/autoconfigure/servlet/ServletContextConditionalFiltersTest.java b/src/starters/webmvc/src/test/java/org/geoserver/cloud/autoconfigure/servlet/ServletContextConditionalFiltersTest.java index 46789ee03..32a277d0a 100644 --- a/src/starters/webmvc/src/test/java/org/geoserver/cloud/autoconfigure/servlet/ServletContextConditionalFiltersTest.java +++ b/src/starters/webmvc/src/test/java/org/geoserver/cloud/autoconfigure/servlet/ServletContextConditionalFiltersTest.java @@ -39,14 +39,11 @@ class ServletContextConditionalFiltersTest { private @Autowired ApplicationContext context; public void flushSafeFilter() { - assertThrows( - NoSuchBeanDefinitionException.class, () -> context.getBean(FlushSafeFilter.class)); + assertThrows(NoSuchBeanDefinitionException.class, () -> context.getBean(FlushSafeFilter.class)); } public void sessionDebugFilter() { - assertThrows( - NoSuchBeanDefinitionException.class, - () -> context.getBean(SessionDebugFilter.class)); + assertThrows(NoSuchBeanDefinitionException.class, () -> context.getBean(SessionDebugFilter.class)); } @Test diff --git a/src/starters/webmvc/src/test/java/org/geoserver/cloud/autoconfigure/servlet/ServletContextDisabledSmokeTest.java b/src/starters/webmvc/src/test/java/org/geoserver/cloud/autoconfigure/servlet/ServletContextDisabledSmokeTest.java index 376f0a189..f8b8c8975 100644 --- a/src/starters/webmvc/src/test/java/org/geoserver/cloud/autoconfigure/servlet/ServletContextDisabledSmokeTest.java +++ b/src/starters/webmvc/src/test/java/org/geoserver/cloud/autoconfigure/servlet/ServletContextDisabledSmokeTest.java @@ -29,10 +29,7 @@ */ @SpringBootTest( classes = TestConfiguration.class, - properties = { - "reactive.feign.loadbalancer.enabled=false", - "geoserver.servlet.enabled=false" - }) + properties = {"reactive.feign.loadbalancer.enabled=false", "geoserver.servlet.enabled=false"}) @EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class) @ActiveProfiles("test") class ServletContextDisabledSmokeTest { @@ -41,43 +38,30 @@ class ServletContextDisabledSmokeTest { @Test void contextLoaderListener() { - assertThrows( - NoSuchBeanDefinitionException.class, - () -> context.getBean(GeoServerServletInitializer.class)); + assertThrows(NoSuchBeanDefinitionException.class, () -> context.getBean(GeoServerServletInitializer.class)); } public void requestContextListener() { - assertThrows( - NoSuchBeanDefinitionException.class, - () -> context.getBean(RequestContextListener.class)); + assertThrows(NoSuchBeanDefinitionException.class, () -> context.getBean(RequestContextListener.class)); } public void flushSafeFilter() { - assertThrows( - NoSuchBeanDefinitionException.class, () -> context.getBean(FlushSafeFilter.class)); + assertThrows(NoSuchBeanDefinitionException.class, () -> context.getBean(FlushSafeFilter.class)); } public void sessionDebugFilter() { - assertThrows( - NoSuchBeanDefinitionException.class, - () -> context.getBean(SessionDebugFilter.class)); + assertThrows(NoSuchBeanDefinitionException.class, () -> context.getBean(SessionDebugFilter.class)); } public void advancedDispatchFilter() { - assertThrows( - NoSuchBeanDefinitionException.class, - () -> context.getBean(AdvancedDispatchFilter.class)); + assertThrows(NoSuchBeanDefinitionException.class, () -> context.getBean(AdvancedDispatchFilter.class)); } public void springDelegatingFilter() { - assertThrows( - NoSuchBeanDefinitionException.class, - () -> context.getBean(SpringDelegatingFilter.class)); + assertThrows(NoSuchBeanDefinitionException.class, () -> context.getBean(SpringDelegatingFilter.class)); } public void threadLocalsCleanupFilter() { - assertThrows( - NoSuchBeanDefinitionException.class, - () -> context.getBean(ThreadLocalsCleanupFilter.class)); + assertThrows(NoSuchBeanDefinitionException.class, () -> context.getBean(ThreadLocalsCleanupFilter.class)); } } diff --git a/src/starters/webmvc/src/test/java/org/geoserver/cloud/autoconfigure/servlet/ServletContextEnabledSmokeTest.java b/src/starters/webmvc/src/test/java/org/geoserver/cloud/autoconfigure/servlet/ServletContextEnabledSmokeTest.java index bec398e14..adb10edee 100644 --- a/src/starters/webmvc/src/test/java/org/geoserver/cloud/autoconfigure/servlet/ServletContextEnabledSmokeTest.java +++ b/src/starters/webmvc/src/test/java/org/geoserver/cloud/autoconfigure/servlet/ServletContextEnabledSmokeTest.java @@ -23,9 +23,7 @@ import org.springframework.web.context.request.RequestContextListener; /** Smoke test to load the servlet context beans with auto-configuration enabled */ -@SpringBootTest( - classes = TestConfiguration.class, - properties = "reactive.feign.loadbalancer.enabled=false") +@SpringBootTest(classes = TestConfiguration.class, properties = "reactive.feign.loadbalancer.enabled=false") @EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class) @ActiveProfiles("test") class ServletContextEnabledSmokeTest { diff --git a/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/CssStylingConfiguration.java b/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/CssStylingConfiguration.java index 1b4ba43bf..606947716 100644 --- a/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/CssStylingConfiguration.java +++ b/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/CssStylingConfiguration.java @@ -29,10 +29,7 @@ class CssStylingConfiguration { @Configuration @ConditionalOnBean(name = "sldHandler") - @ConditionalOnProperty( - name = "geoserver.styling.css.enabled", - havingValue = "true", - matchIfMissing = true) + @ConditionalOnProperty(name = "geoserver.styling.css.enabled", havingValue = "true", matchIfMissing = true) @ConditionalOnClass(CssHandler.class) @ImportResource( // reader = FilteringXmlBeanDefinitionReader.class, // @@ -48,10 +45,7 @@ static class Enabled {} */ @Configuration @ConditionalOnBean(name = "sldHandler") - @ConditionalOnProperty( - name = "geoserver.styling.css.enabled", - havingValue = "false", - matchIfMissing = false) + @ConditionalOnProperty(name = "geoserver.styling.css.enabled", havingValue = "false", matchIfMissing = false) static class Disabled { @Bean @@ -59,8 +53,7 @@ ModuleStatus cssDisabledModuleStatus() { ModuleStatusImpl mod = new ModuleStatusImpl(); mod.setAvailable(true); mod.setEnabled(false); - mod.setMessage( - "CSS module disabled through config property geoserver.styling.css.enabled=false"); + mod.setMessage("CSS module disabled through config property geoserver.styling.css.enabled=false"); mod.setComponent("GeoServer CSS Styling"); mod.setModule("gs-css"); mod.setName("CSS"); diff --git a/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/MapBoxStylingConfiguration.java b/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/MapBoxStylingConfiguration.java index 1c877ba82..667e98fe5 100644 --- a/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/MapBoxStylingConfiguration.java +++ b/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/MapBoxStylingConfiguration.java @@ -22,19 +22,12 @@ * @since 1.0 */ @Configuration -@Import( - value = { - MapBoxStylingConfiguration.Enabled.class, - MapBoxStylingConfiguration.Disabled.class - }) +@Import(value = {MapBoxStylingConfiguration.Enabled.class, MapBoxStylingConfiguration.Disabled.class}) class MapBoxStylingConfiguration { @Configuration @ConditionalOnBean(name = "sldHandler") // sldHandler is MBStyleHandler's constructor arg - @ConditionalOnProperty( - name = "geoserver.styling.mapbox.enabled", - havingValue = "true", - matchIfMissing = true) + @ConditionalOnProperty(name = "geoserver.styling.mapbox.enabled", havingValue = "true", matchIfMissing = true) @ConditionalOnClass(MBStyleHandler.class) @ImportResource( // reader = FilteringXmlBeanDefinitionReader.class, // @@ -42,10 +35,7 @@ class MapBoxStylingConfiguration { static class Enabled {} @Configuration - @ConditionalOnProperty( - name = "geoserver.styling.mapbox.enabled", - havingValue = "false", - matchIfMissing = false) + @ConditionalOnProperty(name = "geoserver.styling.mapbox.enabled", havingValue = "false", matchIfMissing = false) @ConditionalOnClass(MBStyleHandler.class) static class Disabled { diff --git a/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/VectorTilesConfiguration.java b/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/VectorTilesConfiguration.java index ad1abdfb3..b85db5a80 100644 --- a/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/VectorTilesConfiguration.java +++ b/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/VectorTilesConfiguration.java @@ -28,19 +28,14 @@ class VectorTilesConfiguration { static final String PREFIX = "geoserver.wms.output-formats.vector-tiles"; VectorTilesConfiguration( - @Qualifier("VectorTilesExtension") - org.geoserver.platform.ModuleStatusImpl extensionInfo, + @Qualifier("VectorTilesExtension") org.geoserver.platform.ModuleStatusImpl extensionInfo, WmsExtensionsConfigProperties config) { VectorTilesConfigProperties vt = config.getWms().getOutputFormats().getVectorTiles(); extensionInfo.setEnabled(vt.anyEnabled()); } - @ConditionalOnProperty( - prefix = PREFIX + ".mapbox", - name = "enabled", - havingValue = "true", - matchIfMissing = true) + @ConditionalOnProperty(prefix = PREFIX + ".mapbox", name = "enabled", havingValue = "true", matchIfMissing = true) @ImportResource( // reader = FilteringXmlBeanDefinitionReader.class, // locations = { @@ -48,11 +43,7 @@ class VectorTilesConfiguration { }) static @Configuration class MapBox {} - @ConditionalOnProperty( - prefix = PREFIX + ".geojson", - name = "enabled", - havingValue = "true", - matchIfMissing = true) + @ConditionalOnProperty(prefix = PREFIX + ".geojson", name = "enabled", havingValue = "true", matchIfMissing = true) @ImportResource( // reader = FilteringXmlBeanDefinitionReader.class, // locations = { @@ -60,11 +51,7 @@ class VectorTilesConfiguration { }) static @Configuration class GeoJson {} - @ConditionalOnProperty( - prefix = PREFIX + ".topojson", - name = "enabled", - havingValue = "true", - matchIfMissing = true) + @ConditionalOnProperty(prefix = PREFIX + ".topojson", name = "enabled", havingValue = "true", matchIfMissing = true) @ImportResource( // reader = FilteringXmlBeanDefinitionReader.class, // locations = { diff --git a/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/WmsExtensionsAutoConfiguration.java b/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/WmsExtensionsAutoConfiguration.java index 363b78d77..0d2bdbf67 100644 --- a/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/WmsExtensionsAutoConfiguration.java +++ b/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/WmsExtensionsAutoConfiguration.java @@ -4,26 +4,19 @@ */ package org.geoserver.cloud.autoconfigure.wms.extensions; +import javax.annotation.PostConstruct; import lombok.extern.slf4j.Slf4j; - import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; -import javax.annotation.PostConstruct; - /** * @since 1.0 */ @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(WmsExtensionsConfigProperties.class) @Slf4j(topic = "org.geoserver.cloud.autoconfigure.wms.extension") -@Import( - value = { - CssStylingConfiguration.class, - MapBoxStylingConfiguration.class, - VectorTilesConfiguration.class - }) +@Import(value = {CssStylingConfiguration.class, MapBoxStylingConfiguration.class, VectorTilesConfiguration.class}) public class WmsExtensionsAutoConfiguration { public @PostConstruct void log() { log.info("WMS extensions configuration detected"); diff --git a/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/WmsExtensionsConfigProperties.java b/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/WmsExtensionsConfigProperties.java index 7d2d0a627..e30b0574d 100644 --- a/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/WmsExtensionsConfigProperties.java +++ b/src/starters/wms-extensions/src/main/java/org/geoserver/cloud/autoconfigure/wms/extensions/WmsExtensionsConfigProperties.java @@ -7,7 +7,6 @@ import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; - import org.springframework.boot.context.properties.ConfigurationProperties; /** @@ -46,8 +45,7 @@ } public static @Data class Wms { - private WmsOutputFormatsConfigProperties outputFormats = - new WmsOutputFormatsConfigProperties(); + private WmsOutputFormatsConfigProperties outputFormats = new WmsOutputFormatsConfigProperties(); public static @Data class WmsOutputFormatsConfigProperties { private VectorTilesConfigProperties vectorTiles = new VectorTilesConfigProperties(); diff --git a/src/starters/wms-extensions/src/test/java/org/geoserver/cloud/autoconfigure/wms/extensions/CssStylingConfigurationTest.java b/src/starters/wms-extensions/src/test/java/org/geoserver/cloud/autoconfigure/wms/extensions/CssStylingConfigurationTest.java index c13b58986..707a023bc 100644 --- a/src/starters/wms-extensions/src/test/java/org/geoserver/cloud/autoconfigure/wms/extensions/CssStylingConfigurationTest.java +++ b/src/starters/wms-extensions/src/test/java/org/geoserver/cloud/autoconfigure/wms/extensions/CssStylingConfigurationTest.java @@ -21,16 +21,14 @@ */ class CssStylingConfigurationTest { - private final ApplicationContextRunner contextRunner = - new ApplicationContextRunner() - .withBean("extensions", GeoServerExtensions.class) - .withConfiguration(AutoConfigurations.of(CssStylingConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withBean("extensions", GeoServerExtensions.class) + .withConfiguration(AutoConfigurations.of(CssStylingConfiguration.class)); @Test void cssHandler_no_config() { - contextRunner - .withBean("sldHandler", SLDHandler.class) - .run(context -> assertThat(context).hasSingleBean(CssHandler.class)); + contextRunner.withBean("sldHandler", SLDHandler.class).run(context -> assertThat(context) + .hasSingleBean(CssHandler.class)); } @Test @@ -46,25 +44,19 @@ void cssHandler_disabled_registers_module_status() { contextRunner .withBean("sldHandler", SLDHandler.class) .withPropertyValues("geoserver.styling.css.enabled=false") - .run( - context -> { - assertThat(context).doesNotHaveBean(CssHandler.class); - assertThat(context).hasBean("cssDisabledModuleStatus"); - assertThat(context) - .getBean("cssDisabledModuleStatus") - .isInstanceOf(ModuleStatusImpl.class); - }); + .run(context -> { + assertThat(context).doesNotHaveBean(CssHandler.class); + assertThat(context).hasBean("cssDisabledModuleStatus"); + assertThat(context).getBean("cssDisabledModuleStatus").isInstanceOf(ModuleStatusImpl.class); + }); } @Test void cssHandler_conditional_on_sldHandler() { - contextRunner - .withPropertyValues("geoserver.styling.css.enabled=true") - .run( - context -> { - assertThat(context).doesNotHaveBean(SLDHandler.class); - assertThat(context).doesNotHaveBean(CssHandler.class); - assertThat(context).doesNotHaveBean("cssDisabledModuleStatus"); - }); + contextRunner.withPropertyValues("geoserver.styling.css.enabled=true").run(context -> { + assertThat(context).doesNotHaveBean(SLDHandler.class); + assertThat(context).doesNotHaveBean(CssHandler.class); + assertThat(context).doesNotHaveBean("cssDisabledModuleStatus"); + }); } } diff --git a/src/starters/wms-extensions/src/test/java/org/geoserver/cloud/autoconfigure/wms/extensions/MapBoxStylingConfigurationTest.java b/src/starters/wms-extensions/src/test/java/org/geoserver/cloud/autoconfigure/wms/extensions/MapBoxStylingConfigurationTest.java index 4bb62efa1..68fcf37b8 100644 --- a/src/starters/wms-extensions/src/test/java/org/geoserver/cloud/autoconfigure/wms/extensions/MapBoxStylingConfigurationTest.java +++ b/src/starters/wms-extensions/src/test/java/org/geoserver/cloud/autoconfigure/wms/extensions/MapBoxStylingConfigurationTest.java @@ -20,20 +20,17 @@ */ class MapBoxStylingConfigurationTest { - private final ApplicationContextRunner contextRunner = - new ApplicationContextRunner() - .withBean("sldHandler", SLDHandler.class) - .withConfiguration(AutoConfigurations.of(MapBoxStylingConfiguration.class)); + private final ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withBean("sldHandler", SLDHandler.class) + .withConfiguration(AutoConfigurations.of(MapBoxStylingConfiguration.class)); @Test void MBStyleHandler_no_config() { contextRunner .run(context -> assertThat(context).hasSingleBean(MBStyleHandler.class)) .run(context -> assertThat(context).hasBean("MBStyleExtension")) - .run( - context -> - assertThat(context.getBean("MBStyleExtension", ModuleStatus.class)) - .hasFieldOrPropertyWithValue("enabled", true)); + .run(context -> assertThat(context.getBean("MBStyleExtension", ModuleStatus.class)) + .hasFieldOrPropertyWithValue("enabled", true)); } @Test @@ -42,10 +39,8 @@ void MBStyleHandler_enabled() { .withPropertyValues("geoserver.styling.mapbox.enabled=true") .run(context -> assertThat(context).hasSingleBean(MBStyleHandler.class)) .run(context -> assertThat(context).hasBean("MBStyleExtension")) - .run( - context -> - assertThat(context.getBean("MBStyleExtension", ModuleStatus.class)) - .hasFieldOrPropertyWithValue("enabled", true)); + .run(context -> assertThat(context.getBean("MBStyleExtension", ModuleStatus.class)) + .hasFieldOrPropertyWithValue("enabled", true)); } @Test @@ -54,9 +49,7 @@ void MBStyleHandler_disabled_registers_module_status() { .withPropertyValues("geoserver.styling.mapbox.enabled=false") .run(context -> assertThat(context).doesNotHaveBean(MBStyleHandler.class)) .run(context -> assertThat(context).hasBean("MBStyleExtension")) - .run( - context -> - assertThat(context.getBean("MBStyleExtension", ModuleStatus.class)) - .hasFieldOrPropertyWithValue("enabled", false)); + .run(context -> assertThat(context.getBean("MBStyleExtension", ModuleStatus.class)) + .hasFieldOrPropertyWithValue("enabled", false)); } } diff --git a/src/starters/wms-extensions/src/test/java/org/geoserver/cloud/autoconfigure/wms/extensions/VectorTilesConfigurationTest.java b/src/starters/wms-extensions/src/test/java/org/geoserver/cloud/autoconfigure/wms/extensions/VectorTilesConfigurationTest.java index 3d3c60a36..bdcc73cba 100644 --- a/src/starters/wms-extensions/src/test/java/org/geoserver/cloud/autoconfigure/wms/extensions/VectorTilesConfigurationTest.java +++ b/src/starters/wms-extensions/src/test/java/org/geoserver/cloud/autoconfigure/wms/extensions/VectorTilesConfigurationTest.java @@ -18,10 +18,9 @@ */ class VectorTilesConfigurationTest { - private ApplicationContextRunner contextRunner = - new ApplicationContextRunner() - // .withBean(WmsExtensionsConfigProperties.class) - .withConfiguration(AutoConfigurations.of(VectorTilesConfiguration.class)); + private ApplicationContextRunner contextRunner = new ApplicationContextRunner() + // .withBean(WmsExtensionsConfigProperties.class) + .withConfiguration(AutoConfigurations.of(VectorTilesConfiguration.class)); @Test void allEnabledByDefault() { @@ -30,11 +29,10 @@ void allEnabledByDefault() { @Test void allEnabledExplicitly() { - contextRunner = - contextRunner.withPropertyValues( - "geoserver.wms.output-formats.vector-tiles.mapbox.enabled=true", - "geoserver.wms.output-formats.vector-tiles.geojson.enabled=true", - "geoserver.wms.output-formats.vector-tiles.topojson.enabled=true"); + contextRunner = contextRunner.withPropertyValues( + "geoserver.wms.output-formats.vector-tiles.mapbox.enabled=true", + "geoserver.wms.output-formats.vector-tiles.geojson.enabled=true", + "geoserver.wms.output-formats.vector-tiles.topojson.enabled=true"); testAllEnabled(); } @@ -51,11 +49,10 @@ private void testAllEnabled() { @Test void enableOne() { - contextRunner = - contextRunner.withPropertyValues( - "geoserver.wms.output-formats.vector-tiles.mapbox.enabled=true", - "geoserver.wms.output-formats.vector-tiles.geojson.enabled=false", - "geoserver.wms.output-formats.vector-tiles.topojson.enabled=false"); + contextRunner = contextRunner.withPropertyValues( + "geoserver.wms.output-formats.vector-tiles.mapbox.enabled=true", + "geoserver.wms.output-formats.vector-tiles.geojson.enabled=false", + "geoserver.wms.output-formats.vector-tiles.topojson.enabled=false"); hasBeans("VectorTilesExtension", "wmsMapBoxBuilderFactory", "wmsMapBoxMapOutputFormat"); doesNotHaveBeans( @@ -67,11 +64,10 @@ void enableOne() { @Test void allDisabled() { - contextRunner = - contextRunner.withPropertyValues( - "geoserver.wms.output-formats.vector-tiles.mapbox.enabled=false", - "geoserver.wms.output-formats.vector-tiles.geojson.enabled=false", - "geoserver.wms.output-formats.vector-tiles.topojson.enabled=false"); + contextRunner = contextRunner.withPropertyValues( + "geoserver.wms.output-formats.vector-tiles.mapbox.enabled=false", + "geoserver.wms.output-formats.vector-tiles.geojson.enabled=false", + "geoserver.wms.output-formats.vector-tiles.topojson.enabled=false"); hasBeans("VectorTilesExtension"); doesNotHaveBeans( @@ -82,28 +78,24 @@ void allDisabled() { "wmsGeoJsonBuilderFactory", "wmsGeoJsonMapOutputFormat"); - contextRunner.run( - context -> - assertThat(context) - .getBean("VectorTilesExtension", ModuleStatus.class) - .hasFieldOrPropertyWithValue("enabled", false)); + contextRunner.run(context -> assertThat(context) + .getBean("VectorTilesExtension", ModuleStatus.class) + .hasFieldOrPropertyWithValue("enabled", false)); } private void hasBeans(String... beans) { - contextRunner.run( - context -> { - for (String bean : beans) { - assertThat(context).hasBean(bean); - } - }); + contextRunner.run(context -> { + for (String bean : beans) { + assertThat(context).hasBean(bean); + } + }); } private void doesNotHaveBeans(String... beans) { - contextRunner.run( - context -> { - for (String bean : beans) { - assertThat(context).doesNotHaveBean(bean); - } - }); + contextRunner.run(context -> { + for (String bean : beans) { + assertThat(context).doesNotHaveBean(bean); + } + }); } }