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 705422058..870631ea3 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 @@ -41,7 +41,7 @@ void testRESTDefaultContentType() throws ParseException { ResponseEntity response = testGetRequestContentType("/gwc/rest/layers", APPLICATION_JSON); JsonElement parsed = JsonParser.parseString(response.getBody()); - assertThat(parsed.isJsonArray()); + assertThat(parsed.isJsonArray()).isTrue(); } @Test @@ -49,7 +49,7 @@ void testRESTPathExtensionContentNegotiation() { ResponseEntity response = testGetRequestContentType("/gwc/rest/layers.json", APPLICATION_JSON); JsonElement parsed = JsonParser.parseString(response.getBody()); - assertThat(parsed.isJsonArray()); + assertThat(parsed.isJsonArray()).isTrue(); testGetRequestContentType("/gwc/rest/layers.xml", APPLICATION_XML); } 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 34f454132..85592b645 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 @@ -92,7 +92,7 @@ WPSXStreamLoader wpsServiceLoader(GeoServerResourceLoader resourceLoader) { @ConditionalOnMissingBean(WPSFactoryExtension.class) @Bean - WPSFactoryExtension WPSFactoryExtension() { + WPSFactoryExtension wpsFactoryExtension() { log(WPSFactoryExtension.class); return new WPSFactoryExtension() {}; // constructor is protected! } 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 b895ae979..fe71f5e34 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 @@ -10,16 +10,14 @@ import org.geotools.http.AbstractHTTPClientFactory; import org.geotools.http.HTTPBehavior; import org.geotools.http.HTTPClient; -import org.geotools.http.HTTPConnectionPooling; -import org.geotools.http.LoggingHTTPClient; import java.util.List; /** */ public class SpringEnvironmentAwareGeoToolsHttpClientFactory extends AbstractHTTPClientFactory { - private static @Setter(value = AccessLevel.PACKAGE) - GeoToolsHttpClientProxyConfigurationProperties proxyConfig = + @Setter(value = AccessLevel.PACKAGE) + private static GeoToolsHttpClientProxyConfigurationProperties proxyConfig = new GeoToolsHttpClientProxyConfigurationProperties(); @Override @@ -31,33 +29,4 @@ public List> clientClasses() { public final HTTPClient createClient(List> behaviors) { return new SpringEnvironmentAwareGeoToolsHttpClient(proxyConfig); } - - protected @Override HTTPClient createLogging(HTTPClient client) { - return new LoggingConnectionPoolingHTTPClient(client); - } - - static class LoggingConnectionPoolingHTTPClient extends LoggingHTTPClient - implements HTTPConnectionPooling { - - public LoggingConnectionPoolingHTTPClient(HTTPClient delegate) { - super(delegate); - } - - public LoggingConnectionPoolingHTTPClient(HTTPClient delegate, String charset) { - super(delegate, charset); - } - - @Override - public int getMaxConnections() { - return ((HTTPConnectionPooling) delegate).getMaxConnections(); - } - - @Override - public void setMaxConnections(int maxConnections) { - ((HTTPConnectionPooling) delegate).setMaxConnections(maxConnections); - } - - @Override - public void close() {} - } } 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 09e657c59..c206b2a4d 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 @@ -10,7 +10,6 @@ import org.geoserver.catalog.Catalog; import org.geoserver.catalog.CatalogInfo; -import org.geoserver.catalog.Info; import org.geoserver.catalog.ResourceInfo; import org.geoserver.catalog.ResourcePool; import org.geoserver.catalog.ResourcePool.CacheClearingListener; @@ -69,7 +68,7 @@ public void onCatalogRemoteModifyEvent(CatalogInfoModified event) { () -> log.trace("Ignoring event from self: {}", event)); } - private void evictFromResourcePool(InfoEvent event) { + private void evictFromResourcePool(InfoEvent event) { final String id = event.getObjectId(); final ConfigInfoType infoType = event.getObjectType(); 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 d4c4c4687..a2abbe700 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 @@ -144,10 +144,12 @@ void default_admin_bad_credentials() { context -> { assertThat(context).hasNotFailed(); Authentication token = userNamePasswordToken("admin", "badPWD"); + EnvironmentAdminAuthenticationProvider envAuthProvider = + envAuthProvider(context); assertThrows( InternalAuthenticationServiceException.class, - () -> envAuthProvider(context).authenticate(token)); + () -> envAuthProvider.authenticate(token)); }); } 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 da901f2fe..2e81e9b02 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 @@ -47,7 +47,6 @@ public class RemoteEventDataDirectoryProcessor { private final @NonNull RepositoryGeoServerFacade configFacade; private final @NonNull ExtendedCatalogFacade catalogFacade; - @SuppressWarnings({"rawtypes"}) @EventListener(classes = {UpdateSequenceEvent.class}) public void onUpdateSequenceEvent(UpdateSequenceEvent updateSequenceEvent) { if (updateSequenceEvent.isRemote()) { @@ -61,7 +60,7 @@ public void onUpdateSequenceEvent(UpdateSequenceEvent updateSequenceEvent) { } @EventListener(InfoRemoved.class) - public void onRemoteRemoveEvent(InfoRemoved event) { + public void onRemoteRemoveEvent(InfoRemoved event) { if (event.isLocal()) { return; } @@ -130,16 +129,10 @@ public void onRemoteAddEvent(InfoAdded event) { case WORKSPACE: catalogFacade.add((WorkspaceInfo) object); break; - case COVERAGE: - case FEATURETYPE: - case WMSLAYER: - case WMTSLAYER: + case COVERAGE, FEATURETYPE, WMSLAYER, WMTSLAYER: catalogFacade.add((ResourceInfo) object); break; - case COVERAGESTORE: - case DATASTORE: - case WMSSTORE: - case WMTSSTORE: + case COVERAGESTORE, DATASTORE, WMSSTORE, WMTSSTORE: catalogFacade.add((StoreInfo) object); break; case LAYERGROUP: @@ -197,7 +190,7 @@ public void onRemoteDefaultDataStoreEvent(DefaultDataStoreSet event) { } @EventListener(InfoModified.class) - public void onRemoteModifyEvent(InfoModified event) { + public void onRemoteModifyEvent(InfoModified event) { if (event.isLocal()) { return; } @@ -222,16 +215,10 @@ public void onRemoteModifyEvent(InfoModified event) { case WORKSPACE: info = catalogFacade.getWorkspace(objectId); break; - case COVERAGE: - case FEATURETYPE: - case WMSLAYER: - case WMTSLAYER: + case COVERAGE, FEATURETYPE, WMSLAYER, WMTSLAYER: info = catalogFacade.getResource(objectId, ResourceInfo.class); break; - case COVERAGESTORE: - case DATASTORE: - case WMSSTORE: - case WMTSSTORE: + case COVERAGESTORE, DATASTORE, WMSSTORE, WMTSSTORE: info = catalogFacade.getStore(objectId, StoreInfo.class); break; case LAYERGROUP: 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 2094c13e0..250322a0b 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 @@ -9,7 +9,6 @@ import lombok.extern.slf4j.Slf4j; import org.geoserver.catalog.CatalogInfo; -import org.geoserver.catalog.Info; import org.geoserver.cloud.event.info.ConfigInfoType; import org.geoserver.cloud.event.info.InfoEvent; import org.geoserver.cloud.event.info.InfoModified; @@ -28,16 +27,16 @@ public class RemoteEventJdbcConfigProcessor { private final @NonNull ConfigDatabase jdbcConfigDatabase; @EventListener(InfoRemoved.class) - public void onRemoteRemoveEvent(InfoRemoved event) { + public void onRemoteRemoveEvent(InfoRemoved event) { evictConfigDatabaseEntry(event); } @EventListener(InfoModified.class) - public void onRemoteModifyEvent(InfoModified event) { + public void onRemoteModifyEvent(InfoModified event) { evictConfigDatabaseEntry(event); } - private void evictConfigDatabaseEntry(InfoEvent event) { + private void evictConfigDatabaseEntry(InfoEvent event) { event.remote() .ifPresent( remoteEvent -> { diff --git a/src/catalog/backends/pgsql/src/main/java/org/geoserver/cloud/backend/pgsql/PgsqlBackendBuilder.java b/src/catalog/backends/pgsql/src/main/java/org/geoserver/cloud/backend/pgsql/PgsqlBackendBuilder.java index a2a16fabf..634bfa684 100644 --- a/src/catalog/backends/pgsql/src/main/java/org/geoserver/cloud/backend/pgsql/PgsqlBackendBuilder.java +++ b/src/catalog/backends/pgsql/src/main/java/org/geoserver/cloud/backend/pgsql/PgsqlBackendBuilder.java @@ -22,7 +22,7 @@ import org.geoserver.config.plugin.RepositoryGeoServerFacade; import org.springframework.jdbc.core.JdbcTemplate; -import java.util.function.Function; +import java.util.function.UnaryOperator; import javax.sql.DataSource; @@ -58,10 +58,11 @@ public ExtendedCatalogFacade createCatalogFacade(Catalog catalog) { public static ExtendedCatalogFacade createResolvingCatalogFacade( Catalog catalog, PgsqlCatalogFacade rawFacade) { - Function resolvingFunction = + UnaryOperator resolvingFunction = CatalogPropertyResolver.of(catalog) - .andThen(ResolvingProxyResolver.of(catalog)) - .andThen(CollectionPropertiesInitializer.instance()); + .andThen(ResolvingProxyResolver.of(catalog)) + .andThen(CollectionPropertiesInitializer.instance()) + ::apply; ResolvingCatalogFacadeDecorator resolving = new ResolvingCatalogFacadeDecorator(rawFacade); resolving.setOutboundResolver(resolvingFunction); diff --git a/src/catalog/backends/pgsql/src/main/java/org/geoserver/cloud/backend/pgsql/catalog/filter/ToPgsqlCompatibleFilterDuplicator.java b/src/catalog/backends/pgsql/src/main/java/org/geoserver/cloud/backend/pgsql/catalog/filter/ToPgsqlCompatibleFilterDuplicator.java index 3c6717cf8..f1f1e6d7e 100644 --- a/src/catalog/backends/pgsql/src/main/java/org/geoserver/cloud/backend/pgsql/catalog/filter/ToPgsqlCompatibleFilterDuplicator.java +++ b/src/catalog/backends/pgsql/src/main/java/org/geoserver/cloud/backend/pgsql/catalog/filter/ToPgsqlCompatibleFilterDuplicator.java @@ -41,7 +41,8 @@ public static Filter adapt(Filter filter) { @Override public Object visit(PropertyName expression, Object extraData) { - boolean matchCase = (extraData instanceof Boolean match) ? match.booleanValue() : true; + boolean matchCase = true; + if (extraData instanceof Boolean match) matchCase = match; if (!matchCase) { return getFactory(null).function("strToLowerCase", expression); } @@ -50,7 +51,8 @@ public Object visit(PropertyName expression, Object extraData) { @Override public Object visit(Literal expression, Object extraData) { - boolean matchCase = (extraData instanceof Boolean match) ? match.booleanValue() : true; + boolean matchCase = true; + if (extraData instanceof Boolean match) matchCase = match; if (!matchCase) { return getFactory(null).function("strToLowerCase", expression); } diff --git a/src/catalog/backends/pgsql/src/main/java/org/geoserver/cloud/backend/pgsql/catalog/repository/PgsqlCatalogInfoRepository.java b/src/catalog/backends/pgsql/src/main/java/org/geoserver/cloud/backend/pgsql/catalog/repository/PgsqlCatalogInfoRepository.java index badefdcdc..58d518743 100644 --- a/src/catalog/backends/pgsql/src/main/java/org/geoserver/cloud/backend/pgsql/catalog/repository/PgsqlCatalogInfoRepository.java +++ b/src/catalog/backends/pgsql/src/main/java/org/geoserver/cloud/backend/pgsql/catalog/repository/PgsqlCatalogInfoRepository.java @@ -217,7 +217,7 @@ private String applyTypeFilter(String sql, @NonNull Class type) { return sql; } - protected String applyOffsetLimit(String sql, Integer offset, Integer limit) { + protected String applyOffsetLimit(String sql, Integer offset, Integer limit) { if (null != offset) sql += " OFFSET %d".formatted(offset); if (null != limit) sql += " LIMIT %d".formatted(limit); return sql; diff --git a/src/catalog/backends/pgsql/src/test/java/org/geoserver/cloud/backend/pgsql/catalog/repository/PgsqlWorkspaceRepositoryTest.java b/src/catalog/backends/pgsql/src/test/java/org/geoserver/cloud/backend/pgsql/catalog/repository/PgsqlWorkspaceRepositoryTest.java index ce82d6557..a4a23947b 100644 --- a/src/catalog/backends/pgsql/src/test/java/org/geoserver/cloud/backend/pgsql/catalog/repository/PgsqlWorkspaceRepositoryTest.java +++ b/src/catalog/backends/pgsql/src/test/java/org/geoserver/cloud/backend/pgsql/catalog/repository/PgsqlWorkspaceRepositoryTest.java @@ -64,6 +64,6 @@ void testAdd() { info.setName("ws1"); repo.add(info); Optional found = repo.findById(info.getId(), repo.getContentType()); - assertThat(found.isPresent()); + assertThat(found).isPresent(); } } diff --git a/src/catalog/backends/pgsql/src/test/java/org/geoserver/cloud/backend/pgsql/resource/PgsqlResourceStoreTest.java b/src/catalog/backends/pgsql/src/test/java/org/geoserver/cloud/backend/pgsql/resource/PgsqlResourceStoreTest.java deleted file mode 100644 index 34de08623..000000000 --- a/src/catalog/backends/pgsql/src/test/java/org/geoserver/cloud/backend/pgsql/resource/PgsqlResourceStoreTest.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * (c) 2023 Open Source Geospatial Foundation - all rights reserved This code is licensed under the - * GPL 2.0 license, available at the root application directory. - */ -package org.geoserver.cloud.backend.pgsql.resource; - -import static org.junit.jupiter.api.Assertions.*; - -import org.junit.jupiter.api.BeforeEach; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import org.springframework.integration.support.locks.LockRegistry; - -/** - * @since 1.4 - */ -@Disabled -class PgsqlResourceStoreTest { - - private PgsqlResourceStore store; - - /** - * @throws java.lang.Exception - */ - @BeforeEach - void setUp() throws Exception { - LockRegistry registry; - // PgsqlLockProvider lockProvider = new PgsqlLockProvider(registry); - // store = new PgsqlResourceStore(new JdbcTemplate(dataSource), lockProvider); - } - - /** - * Test method for {@link - * org.geoserver.cloud.backend.pgsql.resource.PgsqlResourceStore#get(java.lang.String)}. - */ - @Test - void testGet() { - fail("Not yet implemented"); - } - - /** - * Test method for {@link - * org.geoserver.cloud.backend.pgsql.resource.PgsqlResourceStore#save(org.geoserver.cloud.backend.pgsql.resource.PgsqlResource, - * byte[])}. - */ - @Test - void testSave() { - fail("Not yet implemented"); - } - - /** - * Test method for {@link - * org.geoserver.cloud.backend.pgsql.resource.PgsqlResourceStore#remove(java.lang.String)}. - */ - @Test - void testRemove() { - fail("Not yet implemented"); - } - - /** - * Test method for {@link - * org.geoserver.cloud.backend.pgsql.resource.PgsqlResourceStore#move(java.lang.String, - * java.lang.String)}. - */ - @Test - void testMove() { - fail("Not yet implemented"); - } - - /** - * Test method for {@link - * org.geoserver.cloud.backend.pgsql.resource.PgsqlResourceStore#getResourceNotificationDispatcher()}. - */ - @Test - void testGetResourceNotificationDispatcher() { - fail("Not yet implemented"); - } - - /** - * Test method for {@link - * org.geoserver.cloud.backend.pgsql.resource.PgsqlResourceStore#contents(org.geoserver.cloud.backend.pgsql.resource.PgsqlResource)}. - */ - @Test - void testContents() { - fail("Not yet implemented"); - } - - /** - * Test method for {@link - * org.geoserver.cloud.backend.pgsql.resource.PgsqlResourceStore#delete(org.geoserver.cloud.backend.pgsql.resource.PgsqlResource)}. - */ - @Test - void testDelete() { - fail("Not yet implemented"); - } - - /** - * Test method for {@link - * org.geoserver.cloud.backend.pgsql.resource.PgsqlResourceStore#list(org.geoserver.cloud.backend.pgsql.resource.PgsqlResource)}. - */ - @Test - void testList() { - fail("Not yet implemented"); - } - - /** - * Test method for {@link - * org.geoserver.cloud.backend.pgsql.resource.PgsqlResourceStore#move(org.geoserver.cloud.backend.pgsql.resource.PgsqlResource, - * org.geoserver.platform.resource.Resource)}. - */ - @Test - void testRename() { - fail("Not yet implemented"); - } - - /** - * Test method for {@link - * org.geoserver.cloud.backend.pgsql.resource.PgsqlResourceStore#asFile(org.geoserver.cloud.backend.pgsql.resource.PgsqlResource)}. - */ - @Test - void testAsFile() { - fail("Not yet implemented"); - } - - /** - * Test method for {@link - * org.geoserver.cloud.backend.pgsql.resource.PgsqlResourceStore#asDir(org.geoserver.cloud.backend.pgsql.resource.PgsqlResource)}. - */ - @Test - void testAsDir() { - fail("Not yet implemented"); - } - - /** - * Test method for {@link - * org.geoserver.cloud.backend.pgsql.resource.PgsqlResourceStore#getLockProvider()}. - */ - @Test - void testGetLockProvider() { - fail("Not yet implemented"); - } -} 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 08ae11d29..654e63232 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 @@ -33,10 +33,8 @@ public static ServiceInfoKey byType(WorkspaceInfo ws, Class[] interfaces = clazz.getInterfaces(); Class mostConcrete = ServiceInfo.class; for (Class i : interfaces) { - if (ServiceInfo.class.isAssignableFrom(i)) { - if (mostConcrete.isAssignableFrom(i)) { - mostConcrete = (Class) i; - } + if (ServiceInfo.class.isAssignableFrom(i) && mostConcrete.isAssignableFrom(i)) { + mostConcrete = (Class) i; } } typeName = mostConcrete.getCanonicalName(); diff --git a/src/catalog/cache/src/main/java/org/geoserver/cloud/event/remote/cache/RemoteEventCacheEvictor.java b/src/catalog/cache/src/main/java/org/geoserver/cloud/event/remote/cache/RemoteEventCacheEvictor.java index 113e8c166..39299ef83 100644 --- a/src/catalog/cache/src/main/java/org/geoserver/cloud/event/remote/cache/RemoteEventCacheEvictor.java +++ b/src/catalog/cache/src/main/java/org/geoserver/cloud/event/remote/cache/RemoteEventCacheEvictor.java @@ -50,7 +50,6 @@ private final CachingCatalogFacade catalog; private final CachingGeoServerFacade config; - @SuppressWarnings({"rawtypes", "unchecked"}) @EventListener(classes = {UpdateSequenceEvent.class}) public void onUpdateSequenceEvent(UpdateSequenceEvent updateSequenceEvent) { final Long updateSequence = updateSequenceEvent.getUpdateSequence(); @@ -152,7 +151,7 @@ private void applyUpdateSequence(Long updateSequence) { }); } - private void evictCatalogInfo(InfoEvent event) { + private void evictCatalogInfo(InfoEvent event) { evictEntry( event, () -> { @@ -164,7 +163,7 @@ private void evictCatalogInfo(InfoEvent event) { }); } - public void evictConfigEntry(InfoEvent event) { + public void evictConfigEntry(InfoEvent event) { evictEntry( event, () -> { @@ -175,7 +174,7 @@ public void evictConfigEntry(InfoEvent event) { }); } - private void evictEntry(InfoEvent event, BooleanSupplier evictor) { + private void evictEntry(InfoEvent event, BooleanSupplier evictor) { event.remote() .ifPresent( evt -> { 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 b44de962e..8c0567e3e 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 @@ -58,7 +58,6 @@ @SpringBootTest(classes = GeoServerBackendCacheConfiguration.class) @EnableAutoConfiguration(exclude = LocalCatalogEventsAutoConfiguration.class) -@SuppressWarnings("deprecation") class CachingCatalogFacadeTest { private @MockBean @Qualifier("defaultUpdateSequence") UpdateSequence updateSequence; @@ -192,6 +191,7 @@ void testRemoveStoreInfo() { } @Test + @SuppressWarnings("removal") void testSaveStoreInfo() { testEvicts(ds, caching::save); testEvicts(cs, caching::save); @@ -273,6 +273,7 @@ void testRemoveResourceInfo() { } @Test + @SuppressWarnings("removal") void testSaveResourceInfo() { testEvicts(ft, caching::save); testEvicts(c, caching::save); @@ -323,6 +324,7 @@ void testRemoveLayerEvictsLayersPerResource() { } @Test + @SuppressWarnings("removal") void testSaveLayerInfo() { testEvicts(layer, caching::save); } @@ -367,6 +369,7 @@ void testRemoveLayerGroupInfo() { testEvicts(lg, caching::remove); } + @SuppressWarnings("removal") @Disabled("LayerGroups are not cached") @Test void testSaveLayerGroupInfo() { @@ -396,6 +399,7 @@ void testRemoveNamespaceInfo() { } @Test + @SuppressWarnings("removal") void testSaveNamespaceInfo() { testEvicts(ns, caching::save); } @@ -459,6 +463,7 @@ void testRemoveWorkspaceInfo() { } @Test + @SuppressWarnings("removal") void testSaveWorkspaceInfo() { testEvicts(ws, caching::save); } @@ -508,6 +513,7 @@ void testRemoveStyleInfo() { } @Test + @SuppressWarnings("removal") void testSaveStyleInfo() { testEvicts(style, caching::save); } diff --git a/src/catalog/cache/src/test/java/org/geoserver/cloud/event/remote/cache/RemoteEventCacheEvictorTest.java b/src/catalog/cache/src/test/java/org/geoserver/cloud/event/remote/cache/RemoteEventCacheEvictorTest.java index e63f883b6..512b3c9f4 100644 --- a/src/catalog/cache/src/test/java/org/geoserver/cloud/event/remote/cache/RemoteEventCacheEvictorTest.java +++ b/src/catalog/cache/src/test/java/org/geoserver/cloud/event/remote/cache/RemoteEventCacheEvictorTest.java @@ -142,7 +142,7 @@ private Patch patch(String propertyName, Object value) { return patch; } - private > E publishRemote(E event) { + private E publishRemote(E event) { event.setRemote(true); publisher.publishEvent(event); return event; 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 c539f1294..5e36ee04d 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 @@ -21,7 +21,7 @@ import org.geoserver.config.GeoServer; import java.util.Optional; -import java.util.function.Function; +import java.util.function.UnaryOperator; /** * Highest priority listener for incoming {@link RemoteGeoServerEvent} events to resolve the payload @@ -33,8 +33,8 @@ */ public class InfoEventResolver { - private Function configInfoResolver; - private Function catalogInfoResolver; + private UnaryOperator configInfoResolver; + private UnaryOperator catalogInfoResolver; // REVISIT: merge ProxyUtils with ResolvingProxyResolver private ProxyUtils proxyUtils; @@ -44,39 +44,43 @@ public InfoEventResolver(@NonNull Catalog rawCatalog, @NonNull GeoServer geoserv configInfoResolver = CollectionPropertiesInitializer.instance() - .andThen(ResolvingProxyResolver.of(rawCatalog)); + .andThen(ResolvingProxyResolver.of(rawCatalog)) + ::apply; catalogInfoResolver = CollectionPropertiesInitializer.instance() - .andThen(CatalogPropertyResolver.of(rawCatalog)) - .andThen(ResolvingProxyResolver.of(rawCatalog)); + .andThen(CatalogPropertyResolver.of(rawCatalog)) + .andThen(ResolvingProxyResolver.of(rawCatalog)) + ::apply; } - public InfoEvent resolve(InfoEvent event) { - if (event instanceof InfoAdded addEvent) { - I object = addEvent.getObject(); - addEvent.setObject(resolve(object)); - } else if (event instanceof InfoModified modifyEvent) { - modifyEvent.setPatch(resolve(modifyEvent.getPatch())); + @SuppressWarnings("unchecked") + public InfoEvent resolve(InfoEvent event) { + if (event instanceof InfoAdded addEvent) { + Info object = addEvent.getObject(); + addEvent.setObject(resolveInfo(object)); + } else if (event instanceof InfoModified modifyEvent) { + modifyEvent.setPatch(resolvePatch(modifyEvent.getPatch())); } return event; } @SuppressWarnings("unchecked") - private I resolve(I object) { + private I resolveInfo(I object) { if (object == null) return null; if (object instanceof CatalogInfo i) { - return (I) resolve(i); + return (I) resolveCatalogInfo(i); } return (I) configInfoResolver.apply(object); } - private CatalogInfo resolve(CatalogInfo object) { + @SuppressWarnings("unchecked") + private C resolveCatalogInfo(C object) { if (object == null) return null; - return catalogInfoResolver.apply(object); + return (C) catalogInfoResolver.apply(object); } - private Patch resolve(Patch patch) { + private Patch resolvePatch(Patch patch) { return proxyUtils.resolve(patch); } } 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 5129d9cbb..5b594ffe2 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 @@ -90,7 +90,7 @@ private void publishRemoteEvent(RemoteGeoServerEvent remoteEvent) { protected void logOutgoing(RemoteGeoServerEvent remoteEvent) { @NonNull GeoServerEvent event = remoteEvent.getEvent(); String logMsg = "{}: broadcasting {}"; - if (event instanceof InfoModified modEvent) { + if (event instanceof InfoModified modEvent) { Patch patch = modEvent.getPatch(); if (patch.isEmpty()) { logMsg = "{}: broadcasting no-change 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 192067dd2..cea07065a 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 @@ -54,7 +54,7 @@ public GeoServerEvent toLocalRemote(@NonNull RemoteGeoServerEvent incoming) { GeoServerEvent event = incoming.getEvent(); event.setRemote(true); event.setOrigin(incoming.getOriginService()); - if (event instanceof InfoEvent infoEvent) + if (event instanceof InfoEvent infoEvent) event = remoteEventsPropertyResolver.resolve(infoEvent); return event; } 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 8aa1652bb..7c5d00b58 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 @@ -138,7 +138,7 @@ protected void setupClean() { @BeforeEach public void before() { - assertThat(rabbitMQContainer.isRunning()); + assertThat(rabbitMQContainer.isRunning()).isTrue(); BusEventCollector localAppEvents = localAppContext.getBean(BusEventCollector.class); BusEventCollector remoteAppEvents = remoteAppContext.getBean(BusEventCollector.class); this.eventsCaptor = new EventsCaptor(localAppEvents, remoteAppEvents); @@ -155,7 +155,6 @@ void after() { testData.deleteAll(); } - @SuppressWarnings({"rawtypes"}) protected E testRemoteRemoveEvent( T info, Consumer remover, Class eventType) { @@ -200,7 +199,6 @@ protected Patch testConfigInfoModifyEventNoEquals( // return testRemoteModifyEvent(info, modifier, saver, ConfigInfoModified.class, false); } - @SuppressWarnings({"rawtypes"}) protected Patch testRemoteModifyEvent( // @NonNull T info, // @NonNull Consumer modifier, // @@ -209,7 +207,6 @@ protected Patch testRemoteModifyEvent( // return testRemoteModifyEvent(info, modifier, saver, eventType, true); } - @SuppressWarnings({"rawtypes"}) protected Patch testRemoteModifyEvent( // @NonNull T info, // @NonNull Consumer modifier, // @@ -312,7 +309,6 @@ protected RemoteGeoServerEvent testRemoteAddEvent( return remoteRemoteEvent; } - @SuppressWarnings("rawtypes") protected void assertRemoteEvent(T info, RemoteGeoServerEvent busEvent) { assertNotNull(busEvent.getId()); assertNotNull(busEvent.getOriginService()); @@ -363,7 +359,6 @@ protected static class EventsCaptor { final @Getter BusEventCollector local; final @Getter BusEventCollector remote; - @SuppressWarnings("rawtypes") public EventsCaptor capureEventsOf(Class type) { local.capture(type); remote.capture(type); 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 832b7cc5f..2cf8f5346 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 @@ -36,7 +36,6 @@ public class BusEventCollector { private @Value("${spring.cloud.bus.id}") String busId; private @Autowired RemoteGeoServerEventBridge bridge; - @SuppressWarnings("rawtypes") private @NonNull Class eventType = InfoEvent.class; private volatile boolean capturing = false; @@ -57,23 +56,19 @@ public void onApplicationEvent(RemoteGeoServerEvent busEvent) { events.add(busEvent); } - @SuppressWarnings("rawtypes") public void capture(@NonNull Class type) { this.eventType = type; } - @SuppressWarnings("rawtypes") public RemoteGeoServerEvent expectOne(Class payloadType) { return expectOne(payloadType, Predicates.alwaysTrue()); } - @SuppressWarnings("rawtypes") public RemoteGeoServerEvent expectOne( Class payloadType, ConfigInfoType infoType) { return expectOne(payloadType, c -> infoType.equals(c.getObjectType())); } - @SuppressWarnings("rawtypes") public RemoteGeoServerEvent expectOne( Class payloadType, Predicate filter) { final long t = System.nanoTime(); @@ -111,17 +106,14 @@ public RemoteGeoServerEvent expectOne( return matches.get(0); } - @SuppressWarnings("rawtypes") public List allOf(Class payloadType) { return capturedEvents(payloadType).toList(); } - @SuppressWarnings("rawtypes") public Optional first(Class payloadType) { return capturedEvents(payloadType).findFirst(); } - @SuppressWarnings("rawtypes") private Stream capturedEvents( 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 ca6ba6cf9..14a1ce2bb 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 @@ -526,7 +526,6 @@ void testRemoveEvents() { testRemoteRemoveEvent(testData.workspaceA, catalog::remove, eventType); } - @SuppressWarnings("rawtypes") private E testCatalogModifiedEvent( Catalog catalog, Consumer modifier, @@ -546,7 +545,6 @@ private E testCatalogModifiedEvent( return eventType.cast(sentEvent.getEvent()); } - @SuppressWarnings("rawtypes") private void assertCatalogEvent(Catalog catalog, InfoModified event, Patch expected) { assertThat(event.getObjectId()).isEqualTo("catalog"); // i.e. InfoEvent.CATALOG_ID assertThat(event.getObjectType()).isEqualTo(ConfigInfoType.CATALOG); 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 9972200ce..403ab346f 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 @@ -65,7 +65,7 @@ @RequiredArgsConstructor class CatalogApplicationEventPublisher { - private final @NonNull Consumer> eventPublisher; + private final @NonNull Consumer eventPublisher; private final @NonNull Catalog catalog; private final @NonNull GeoServer geoServer; private final @NonNull Supplier updateSequenceIncrementor; @@ -81,7 +81,7 @@ class CatalogApplicationEventPublisher { geoServer.addListener(publishingConfigListener); } - void publish(@NonNull InfoEvent event) { + void publish(@NonNull InfoEvent event) { eventPublisher.accept(event); } @@ -104,7 +104,7 @@ public static class LocalCatalogEventPublisher implements CatalogListener { * @throws CatalogException meaning the operation that generated the event should be * reverted (as handled by Catalog.event()) */ - private void publish(InfoEvent event) throws CatalogException { + private void publish(InfoEvent event) throws CatalogException { try { publisher.publish(event); } catch (RuntimeException e) { @@ -132,13 +132,10 @@ public void handlePostModifyEvent(CatalogPostModifyEvent event) throws CatalogEx publish(CatalogInfoModified.createLocal(incrementSequence(), event)); } - /** - * {@inheritDoc} - * - *

no-op. - */ @Override - public void reloaded() {} + public void reloaded() { + // no-op + } } @RequiredArgsConstructor @@ -180,7 +177,7 @@ private void push(String objectId, Patch patch) { return patch; } - private void publish(InfoEvent event) { + private void publish(InfoEvent event) { publisher.publish(event); } @@ -224,7 +221,7 @@ public void handlePostGlobalChange(GeoServerInfo global) { publish(ConfigInfoAdded.createLocal(incrementSequence(), global)); } else { // already called pop() - ConfigInfoModified event = + ConfigInfoModified event = ConfigInfoModified.createLocal(incrementSequence(), global, patch); publish(event); } 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 cfba6f5c6..52f447d89 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 @@ -5,7 +5,6 @@ package org.geoserver.cloud.config.catalog.events; import org.geoserver.catalog.Catalog; -import org.geoserver.catalog.Info; import org.geoserver.cloud.event.info.InfoEvent; import org.geoserver.config.GeoServer; import org.geoserver.platform.config.UpdateSequence; @@ -28,7 +27,7 @@ CatalogApplicationEventPublisher localApplicationEventPublisher( // UpdateSequence updateSequence // ) { - Consumer> publisher = localContextPublisher::publishEvent; + Consumer publisher = localContextPublisher::publishEvent; Supplier updateSequenceIncrementor = updateSequence::nextValue; return new CatalogApplicationEventPublisher( publisher, catalog, geoServer, updateSequenceIncrementor); 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 8dfe7c0f0..076cdc083 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 @@ -31,7 +31,7 @@ @JsonSubTypes.Type(value = DefaultDataStoreSet.class), }) @SuppressWarnings("serial") -public class CatalogInfoModified extends InfoModified { +public class CatalogInfoModified extends InfoModified { protected CatalogInfoModified() {} 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 3b079468e..4fb5f67ca 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 @@ -18,7 +18,7 @@ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonTypeName("CatalogInfoRemoved") @SuppressWarnings("serial") -public class CatalogInfoRemoved extends InfoRemoved { +public class CatalogInfoRemoved extends InfoRemoved { protected CatalogInfoRemoved() {} 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 a10648523..2dd2ce826 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 @@ -26,8 +26,7 @@ @JsonSubTypes.Type(value = SettingsModified.class), }) @SuppressWarnings("serial") -public abstract class ConfigInfoModified extends InfoModified - implements ConfigInfoEvent { +public abstract class ConfigInfoModified extends InfoModified implements ConfigInfoEvent { protected ConfigInfoModified() { // default constructor, needed for deserialization @@ -41,23 +40,34 @@ protected ConfigInfoModified( super(updateSequence, objectId, objectType, patch); } - @SuppressWarnings("unchecked") - public static @NonNull ConfigInfoModified createLocal( + public static @NonNull ConfigInfoModified createLocal( long updateSequence, @NonNull Info info, @NonNull Patch patch) { final ConfigInfoType type = ConfigInfoType.valueOf(info); - return (ConfigInfoModified) - switch (type) { - case GEOSERVER -> GeoServerInfoModified.createLocal( - updateSequence, (GeoServerInfo) info, patch); - case SERVICE -> ServiceModified.createLocal( - updateSequence, (ServiceInfo) info, patch); - case SETTINGS -> SettingsModified.createLocal( - updateSequence, (SettingsInfo) info, patch); - case LOGGING -> LoggingInfoModified.createLocal( - updateSequence, (LoggingInfo) info, patch); - default -> throw new IllegalArgumentException( - "Uknown or unsupported config Info type: " + type + ". " + info); - }; + return switch (type) { + case GEOSERVER -> geoserver(updateSequence, (GeoServerInfo) info, patch); + case SERVICE -> service(updateSequence, (ServiceInfo) info, patch); + case SETTINGS -> settings(updateSequence, (SettingsInfo) info, patch); + case LOGGING -> logging(updateSequence, (LoggingInfo) info, patch); + default -> throw new IllegalArgumentException( + "Uknown or unsupported config Info type: " + type + ". " + info); + }; + } + + private static LoggingInfoModified logging(long updateSequence, LoggingInfo info, Patch patch) { + return LoggingInfoModified.createLocal(updateSequence, info, patch); + } + + private static SettingsModified settings(long updateSequence, SettingsInfo info, Patch patch) { + return SettingsModified.createLocal(updateSequence, info, patch); + } + + private static ServiceModified service(long updateSequence, ServiceInfo info, Patch patch) { + return ServiceModified.createLocal(updateSequence, info, 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 2afb6ccfd..b503da9f5 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 @@ -21,8 +21,7 @@ @JsonSubTypes.Type(value = SettingsRemoved.class, name = "SettingsInfoRemoved"), }) @SuppressWarnings("serial") -public abstract class ConfigInfoRemoved extends InfoRemoved - implements ConfigInfoEvent { +public abstract class ConfigInfoRemoved extends InfoRemoved implements ConfigInfoEvent { protected ConfigInfoRemoved() { // default constructor, needed for deserialization @@ -33,18 +32,15 @@ protected ConfigInfoRemoved( super(updateSequence, objectId, type); } - @SuppressWarnings("unchecked") - public static @NonNull ConfigInfoRemoved createLocal( - long updateSequence, @NonNull I info) { - - final ConfigInfoType type = ConfigInfoType.valueOf(info); - return (ConfigInfoRemoved) - switch (type) { - case SERVICE -> ServiceRemoved.createLocal(updateSequence, (ServiceInfo) info); - case SETTINGS -> SettingsRemoved.createLocal( - updateSequence, (SettingsInfo) info); - default -> throw new IllegalArgumentException( - "Uknown or unsupported config Info type: " + type + ". " + info); - }; + public static @NonNull ConfigInfoRemoved createLocal( + long updateSequence, @NonNull Info configInfo) { + + final ConfigInfoType type = ConfigInfoType.valueOf(configInfo); + return switch (type) { + case SERVICE -> ServiceRemoved.createLocal(updateSequence, (ServiceInfo) configInfo); + case SETTINGS -> SettingsRemoved.createLocal(updateSequence, (SettingsInfo) configInfo); + default -> throw new IllegalArgumentException( + "Uknown or unsupported config Info type: " + type + ". " + configInfo); + }; } } 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 38685be43..548a737c9 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 @@ -18,8 +18,7 @@ @JsonTypeName("GeoServerInfoModified") @EqualsAndHashCode(callSuper = true) @SuppressWarnings("serial") -public class GeoServerInfoModified extends ConfigInfoModified - implements ConfigInfoEvent { +public class GeoServerInfoModified extends ConfigInfoModified implements ConfigInfoEvent { protected GeoServerInfoModified() { // default constructor, needed for deserialization 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 afad7a640..e1b5338f6 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 @@ -18,8 +18,7 @@ @JsonTypeName("LoggingInfoModified") @EqualsAndHashCode(callSuper = true) @SuppressWarnings("serial") -public class LoggingInfoModified extends ConfigInfoModified - implements ConfigInfoEvent { +public class LoggingInfoModified extends ConfigInfoModified implements ConfigInfoEvent { protected LoggingInfoModified() { // default constructor, needed for deserialization 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 3e4bc2a3f..b270d6c45 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 @@ -14,7 +14,6 @@ import org.geoserver.catalog.plugin.Patch; import org.geoserver.cloud.event.info.ConfigInfoType; import org.geoserver.cloud.event.info.InfoEvent; -import org.geoserver.config.LoggingInfo; import org.geoserver.config.ServiceInfo; import org.springframework.core.style.ToStringCreator; @@ -22,7 +21,7 @@ @JsonTypeName("ServiceModified") @EqualsAndHashCode(callSuper = true) @SuppressWarnings("serial") -public class ServiceModified extends ConfigInfoModified implements ConfigInfoEvent { +public class ServiceModified extends ConfigInfoModified implements ConfigInfoEvent { private @Getter String 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 b30ad9e1a..8657c7c57 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 @@ -18,7 +18,7 @@ @JsonTypeName("ServiceInfoRemoved") @EqualsAndHashCode(callSuper = true) @SuppressWarnings("serial") -public class ServiceRemoved extends ConfigInfoRemoved { +public class ServiceRemoved extends ConfigInfoRemoved { private @Getter String workspaceId; 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 6d8eda9e4..5a43d503b 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 @@ -21,7 +21,7 @@ @JsonTypeName("SettingsModified") @EqualsAndHashCode(callSuper = true) @SuppressWarnings("serial") -public class SettingsModified extends ConfigInfoModified implements ConfigInfoEvent { +public class SettingsModified extends ConfigInfoModified implements ConfigInfoEvent { private @Getter String 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 554a40145..36adee52b 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 @@ -16,7 +16,7 @@ @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT) @JsonTypeName("SettingsInfoRemoved") @SuppressWarnings("serial") -public class SettingsRemoved extends ConfigInfoRemoved { +public class SettingsRemoved extends ConfigInfoRemoved { private @Getter String workspaceId; 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 19bc0c6b3..0e3d09fac 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 @@ -21,7 +21,7 @@ @JsonSubTypes.Type(value = ConfigInfoAdded.class), }) @SuppressWarnings("serial") -public abstract class InfoAdded extends InfoEvent { +public abstract class InfoAdded extends InfoEvent { private @Getter @Setter I object; 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 b7a126d24..f4d5fdbf2 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 @@ -24,7 +24,7 @@ @JsonSubTypes.Type(value = InfoRemoved.class) }) @SuppressWarnings("serial") -public abstract class InfoEvent extends UpdateSequenceEvent { +public abstract class InfoEvent extends UpdateSequenceEvent { private @Getter String objectId; 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 8f998c903..132df30f6 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 @@ -11,7 +11,6 @@ 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; @@ -25,7 +24,7 @@ @JsonSubTypes.Type(value = ConfigInfoModified.class), }) @SuppressWarnings("serial") -public abstract class InfoModified extends InfoEvent { +public abstract class InfoModified extends InfoEvent { private @Getter @Setter Patch patch; 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 df7281bc5..c00b0515a 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 @@ -9,7 +9,6 @@ import lombok.NonNull; -import org.geoserver.catalog.Info; import org.geoserver.cloud.event.catalog.CatalogInfoRemoved; import org.geoserver.cloud.event.config.ConfigInfoRemoved; @@ -19,7 +18,7 @@ @JsonSubTypes.Type(value = ConfigInfoRemoved.class, name = "ConfigInfoRemoved"), }) @SuppressWarnings("serial") -public abstract class InfoRemoved extends InfoEvent { +public abstract class InfoRemoved extends InfoEvent { protected InfoRemoved() {} 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 c59aac578..3a64608b2 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 @@ -197,7 +197,6 @@ void testConfigModifyEvents_GeoServerInfo() { GeoServerInfo global = geoserver.getGlobal(); - @SuppressWarnings("rawtypes") Class eventType = ConfigInfoModified.class; CoverageAccessInfo coverageInfo = new CoverageAccessInfoImpl(); @@ -221,7 +220,6 @@ void testConfigPrePostModifyEvents_SettingsInfo() { catalog.add(testData.workspaceB); geoserver.setGlobal(testData.global); - @SuppressWarnings("rawtypes") Class eventType = ConfigInfoModified.class; // odd API weirdness here, can't modify global settings through @@ -259,7 +257,6 @@ void testConfigModifyEvents_LoggingInfo() { catalog.add(testData.workspaceB); geoserver.setLogging(testData.logging); - @SuppressWarnings("rawtypes") Class eventType = ConfigInfoModified.class; LoggingInfo globalLogging = geoserver.getLogging(); @@ -297,7 +294,6 @@ void testConfigPrePostModifyEvents_ServiceInfo() { private void testConfigModifyService(ServiceInfo service) { service = geoserver.getService(service.getId(), ServiceInfo.class); - @SuppressWarnings("rawtypes") Class postEventType = ConfigInfoModified.class; testModify( @@ -323,14 +319,11 @@ void testConfigRemoveEvents() { } private void testRemove( - T info, - Consumer remover, - @SuppressWarnings("rawtypes") Class eventType) { + T info, Consumer remover, Class eventType) { listener.clear(); listener.start(); remover.accept(info); - @SuppressWarnings("unchecked") - InfoRemoved event = listener.expectOne(eventType); + InfoRemoved event = listener.expectOne(eventType); assertEquals(info.getId(), event.getObjectId()); assertEquals(ConfigInfoType.valueOf(info), event.getObjectType()); } @@ -340,7 +333,7 @@ private void testModify( @NonNull T info, @NonNull Consumer modifier, @NonNull Consumer saver, - @NonNull @SuppressWarnings("rawtypes") Class postEventType) { + @NonNull Class postEventType) { if (null == ModificationProxy.handler(info)) throw new IllegalArgumentException("Expected a ModificationProxy"); @@ -376,7 +369,7 @@ private void testModify( modifier.accept(info); saver.accept(info); - InfoModified post = listener.expectOne(postEventType); + InfoModified post = listener.expectOne(postEventType); assertEquals(proxy.getId(), post.getObjectId()); assertEquals(expected, post.getPatch()); } 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 565953322..0c51702f4 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 @@ -135,14 +135,18 @@ private void addDeserializer(Class clazz) { super.addDeserializer(clazz, new CatalogInfoDeserializer<>()); } - private void addMapperSerializer( + /** + * @param object model type + * @param DTO type + */ + private void addMapperSerializer( Class type, - Function serializerMapper, - Class dtoType, - Function deserializerMapper) { + Function serializerMapper, + Class dtoType, + Function deserializerMapper) { - MapperSerializer serializer = new MapperSerializer<>(type, serializerMapper); - MapperDeserializer deserializer = + MapperSerializer serializer = new MapperSerializer<>(type, serializerMapper); + MapperDeserializer deserializer = new MapperDeserializer<>(dtoType, deserializerMapper); super.addSerializer(type, serializer); super.addDeserializer(type, deserializer); diff --git a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/ValueMappers.java b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/ValueMappers.java index 00613a2f8..06f357bb9 100644 --- a/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/ValueMappers.java +++ b/src/catalog/jackson-bindings/geoserver/src/main/java/org/geoserver/jackson/databind/catalog/mapper/ValueMappers.java @@ -60,7 +60,6 @@ import java.awt.geom.AffineTransform; import java.io.Serializable; -import java.util.Collections; import java.util.HashMap; import java.util.Locale; import java.util.Map; @@ -268,15 +267,15 @@ default Map internationalStringToDto(InternationalString s) { return dto; } if (s instanceof SimpleInternationalString) { - return Collections.singletonMap("", s.toString()); + return Map.of("", s.toString()); } if (s == null) return null; LoggerFactory.getLogger(getClass()) .warn( - "Uknown InternationalString implementation: {}. Returning null", + "Uknown InternationalString implementation: {}. Returning the default value", s.getClass().getName()); - return null; + return Map.of("", s.toString()); } default GrowableInternationalString dtoToInternationalString(Map s) { 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 c961e1001..b7b054025 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 @@ -137,14 +137,18 @@ protected void registerValueSerializers() { VALUE_MAPPER::cogSettingsStore); } - private void addMapperSerializer( + /** + * @param object model type + * @param DTO type + */ + private void addMapperSerializer( Class type, - Function serializerMapper, - Class dtoType, - Function deserializerMapper) { + Function serializerMapper, + Class dtoType, + Function deserializerMapper) { - MapperSerializer serializer = new MapperSerializer<>(type, serializerMapper); - MapperDeserializer deserializer = + MapperSerializer serializer = new MapperSerializer<>(type, serializerMapper); + MapperDeserializer deserializer = new MapperDeserializer<>(dtoType, deserializerMapper); super.addSerializer(type, serializer); super.addDeserializer(type, deserializer); 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 dcb353a97..dbf8a65a5 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 @@ -25,6 +25,7 @@ import java.util.Collection; import java.util.Map; import java.util.function.Function; +import java.util.function.UnaryOperator; @Mapper( unmappedTargetPolicy = ReportingPolicy.ERROR, @@ -90,7 +91,8 @@ private R valueToDto(final V value) { return dto; } - private Object copyOf(Map fromMap, Function 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/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 2e3454382..3bd66451e 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 @@ -115,14 +115,18 @@ private void addCustomLiteralValueSerializers() { VALUES::stringToAwtColor); } - private void addMapperSerializer( + /** + * @param object model type + * @param DTO type + */ + private void addMapperSerializer( Class type, - Function serializerMapper, - Class dtoType, - Function deserializerMapper) { + Function serializerMapper, + Class dtoType, + Function deserializerMapper) { - MapperSerializer serializer = new MapperSerializer<>(type, serializerMapper); - MapperDeserializer deserializer = + MapperSerializer serializer = new MapperSerializer<>(type, serializerMapper); + MapperDeserializer deserializer = new MapperDeserializer<>(dtoType, deserializerMapper); super.addSerializer(type, serializer); super.addDeserializer(type, deserializer); 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 f1f3ef4f3..59a6c07ee 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 @@ -26,7 +26,7 @@ import java.util.Map; import java.util.Objects; import java.util.Set; -import java.util.function.Function; +import java.util.function.UnaryOperator; /** * @@ -177,8 +177,8 @@ private void writeCollection( final Class contentType = findContentType(collection, provider); - final Function valueMapper = - Literal.class.equals(contentType) ? Literal::valueOf : Function.identity(); + final UnaryOperator valueMapper = + Literal.class.equals(contentType) ? Literal::valueOf : UnaryOperator.identity(); gen.writeStringField( TYPE_KEY, classNameMapper().classToCanonicalName(collectionType(collection))); 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 f7e799b89..aaea9e95e 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 @@ -18,18 +18,21 @@ /** * 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. + * + * @param DTO type + * @param object model type */ @Slf4j @RequiredArgsConstructor -public class MapperDeserializer extends JsonDeserializer { +public class MapperDeserializer extends JsonDeserializer { - private final @NonNull Class from; - private final Function mapper; + private final @NonNull Class from; + private final Function mapper; @Override public T deserialize(JsonParser parser, DeserializationContext ctxt) throws IOException { - DTO dto; + D dto; T value; try { dto = parser.readValueAs(from); 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 e174216a9..7a561d76d 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 @@ -20,17 +20,20 @@ /** * Generic {@link JsonSerializer} that applies a function from the original object type to the * encoded object type before {@link JsonGenerator#writeObject(Object) writing} it + * + * @param object model type + * @param DTO type */ @Slf4j -public class MapperSerializer extends StdSerializer { +public class MapperSerializer extends StdSerializer { private static final long serialVersionUID = 1L; - private final transient Function mapper; + private final transient Function mapper; private Class type; - public MapperSerializer(Class type, java.util.function.Function serializerMapper) { + public MapperSerializer(Class type, java.util.function.Function serializerMapper) { super(type); this.type = type; this.mapper = serializerMapper; @@ -53,7 +56,7 @@ public void serializeWithType( public void serialize(I value, JsonGenerator gen, SerializerProvider provider) throws IOException { - DTO dto; + D dto; try { dto = mapper.apply(value); } catch (RuntimeException e) { 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 33bc030cc..b3da66c35 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 @@ -49,7 +49,7 @@ public class CatalogFacadeExtensionAdapter extends ForwardingCatalogFacade implements ExtendedCatalogFacade { - private CatalogInfoTypeRegistry> updateToSaveBridge = + private CatalogInfoTypeRegistry> updateToSaveBridge = new CatalogInfoTypeRegistry<>(); public CatalogFacadeExtensionAdapter(CatalogFacade facade) { @@ -78,12 +78,12 @@ public void setCatalog(Catalog catalog) { if (catalog != null) { if (!(catalog instanceof CatalogPlugin)) { throw new IllegalArgumentException( - "Expected " - + CatalogPlugin.class.getName() - + ", got " - + catalog.getClass().getName()); + "Expected %s, got %s" + .formatted( + CatalogPlugin.class.getName(), + catalog.getClass().getName())); } - if (catalog != null && !(catalog instanceof SilentCatalog)) { + if (!(catalog instanceof SilentCatalog)) { catalog = new SilentCatalog((CatalogPlugin) catalog, this); } } 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 33f0fab7b..b0aea19de 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 @@ -585,11 +585,9 @@ public NamespaceInfo update(final NamespaceInfo value, Patch patch) { NamespaceInfo updated = super.update(value, patch); - if (newValue.isPresent()) { - if (!Objects.equals(oldUri, updated.getURI())) { - removeInternal(updated, oldUri); - addInternal(updated); - } + if (newValue.isPresent() && !Objects.equals(oldUri, updated.getURI())) { + removeInternal(updated, oldUri); + addInternal(updated); } return updated; } finally { 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 664f29414..6357305ae 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 @@ -33,7 +33,7 @@ public class CatalogInfoRepositoryHolderImpl implements CatalogInfoRepositoryHol protected StyleRepository styles; protected MapRepository maps; - protected CatalogInfoTypeRegistry> repos = + protected CatalogInfoTypeRegistry> repos = new CatalogInfoTypeRegistry<>(); @SuppressWarnings("unchecked") 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 2a90f51ee..e264b3b7a 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 @@ -42,7 +42,7 @@ * * @param R the type of resource to be accessed on a class basis for {@link CatalogInfo} subtypes */ -public class CatalogInfoTypeRegistry { +public class CatalogInfoTypeRegistry { private final EnumMap mappings = new EnumMap<>(ClassMappings.class); @@ -50,20 +50,18 @@ public class CatalogInfoTypeRegistry { * Registers the {@code resource} for the given type only, first narrowing {@code type} to its * corresponding {@link CatalogInfo} interface type. */ - @SuppressWarnings("unchecked") - public CatalogInfoTypeRegistry register( - Class type, R resource) { + public CatalogInfoTypeRegistry register(Class type, R resource) { requireNonNull(type); requireNonNull(resource); ClassMappings key = determineKey(type); mappings.put(key, resource); - return (CatalogInfoTypeRegistry) this; + return this; } @SuppressWarnings("unchecked") - public CatalogInfoTypeRegistry> consume( + public CatalogInfoTypeRegistry> consume( Class type, Consumer with) { - return ((CatalogInfoTypeRegistry>) this).registerRecursively(type, with); + return ((CatalogInfoTypeRegistry>) this).registerRecursively(type, with); } /** @@ -73,7 +71,7 @@ public CatalogInfoTypeRegistry> consume( * WMSStoreInfo}, and {@link WMTSStoreInfo}) */ @SuppressWarnings("unchecked") - public CatalogInfoTypeRegistry registerRecursively( + public CatalogInfoTypeRegistry registerRecursively( Class type, R resource) { ClassMappings key = determineKey(type); @@ -84,7 +82,7 @@ public CatalogInfoTypeRegistry registerRecursively Class subtype = (Class) subtypes[i]; register(subtype, resource); } - return (CatalogInfoTypeRegistry) this; + return this; } public R forObject(CatalogInfo object) { @@ -97,7 +95,7 @@ public R of(Class type) { return of(determineKey(type)); } - public R of(ClassMappings key) { + public R of(ClassMappings key) { requireNonNull(key); return mappings.get(key); } 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 225b4655f..247d9af45 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 @@ -63,7 +63,6 @@ import java.util.Set; import java.util.UUID; import java.util.function.Consumer; -import java.util.function.Function; import java.util.function.UnaryOperator; import java.util.logging.Level; import java.util.logging.Logger; @@ -765,7 +764,7 @@ protected Optional classMapping(Class .or(() -> Optional.ofNullable(ClassMappings.fromImpl(type))); } - protected void doAdd(T object, Function inserter) { + protected void doAdd(T object, UnaryOperator inserter) { Objects.requireNonNull(object, "object"); Objects.requireNonNull(inserter, "insert function"); setId(object); 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 a29433256..bd2efda51 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 @@ -31,7 +31,7 @@ import java.util.List; import java.util.Objects; -import java.util.function.Function; +import java.util.function.UnaryOperator; import java.util.stream.Stream; /** @@ -80,8 +80,8 @@ public class ResolvingCatalogFacadeDecorator extends ForwardingExtendedCatalogFacade implements ResolvingCatalogFacade { - private Function outboundResolver = Function.identity(); - private Function inboundResolver = Function.identity(); + private UnaryOperator outboundResolver = UnaryOperator.identity(); + private UnaryOperator inboundResolver = UnaryOperator.identity(); public ResolvingCatalogFacadeDecorator(ExtendedCatalogFacade facade) { super(facade); @@ -92,7 +92,7 @@ public ResolvingCatalogFacadeDecorator(ExtendedCatalogFacade facade) { * before leaving this decorator facade */ @Override - public void setOutboundResolver(Function resolvingFunction) { + public void setOutboundResolver(UnaryOperator resolvingFunction) { Objects.requireNonNull(resolvingFunction); this.outboundResolver = resolvingFunction; } @@ -107,7 +107,7 @@ public void setOutboundResolver(Function resolvingFunc * an object is to be discarded from the final outcome */ @Override - public Function getOutboundResolver() { + public UnaryOperator getOutboundResolver() { return this.outboundResolver; } @@ -116,7 +116,7 @@ public Function getOutboundResolver() { * decorated facade */ @Override - public void setInboundResolver(Function resolvingFunction) { + public void setInboundResolver(UnaryOperator resolvingFunction) { Objects.requireNonNull(resolvingFunction); this.inboundResolver = resolvingFunction; } @@ -129,29 +129,29 @@ public void setInboundResolver(Function resolvingFunct * add traits to the current resolver */ @Override - public Function getInboundResolver() { + public UnaryOperator getInboundResolver() { return this.inboundResolver; } @SuppressWarnings("unchecked") - protected Function outbound() { - return (Function) outboundResolver; + protected UnaryOperator outbound() { + return (UnaryOperator) outboundResolver; } @SuppressWarnings("unchecked") - protected Function inbound() { - return (Function) inboundResolver; + protected UnaryOperator inbound() { + return (UnaryOperator) inboundResolver; } @Override public C resolveOutbound(C info) { - Function outboundResolve = outbound(); + UnaryOperator outboundResolve = outbound(); return outboundResolve.apply(info); } @Override public C resolveInbound(C info) { - Function inboundResolve = inbound(); + UnaryOperator inboundResolve = inbound(); return inboundResolve.apply(info); } 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 3a00252b9..7f4187a4b 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 @@ -22,7 +22,7 @@ import org.geoserver.catalog.plugin.CatalogPlugin; import java.util.function.Consumer; -import java.util.function.Function; +import java.util.function.UnaryOperator; /** * A locking catalog, akin to {@link LockingCatalogFacade}, but at a higher level of granularity, @@ -107,7 +107,7 @@ public void setDefaultWorkspace(WorkspaceInfo defaultWorkspace) { } /** {@inheritDoc} */ - protected @Override void doAdd(T info, Function inserter) { + protected @Override void doAdd(T info, UnaryOperator inserter) { locking.runInWriteLock( () -> super.doAdd(info, inserter), format("add(%s[%s])", typeOf(info), nameOf(info))); 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 07a747b45..2ab80764e 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 @@ -12,6 +12,7 @@ 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 @@ -22,7 +23,7 @@ * object, and {@link #resolveInbound} on each received object. * *

- * By default the function applied is the {@link Function#identity() identity} function, use + * By default the function applied is the {@link UnaryOperator#identity() identity} function, use * {@link #setOutboundResolver} to establish the function to apply to each object before being * returned. * @@ -37,12 +38,12 @@ *

  * {@code
  * Catalog catalog = ...
- * Function resolvingFunction;
+ * UnaryOperator resolvingFunction;
  * resolvingFunction =
  *   CatalogPropertyResolver.of(catalog)
  *   .andThen(ResolvingProxyResolver.of(catalog)
  *   .andThen(CollectionPropertiesInitializer.instance())
- *   .andThen(ModificationProxyDecorator.wrap());
+ *   .andThen(ModificationProxyDecorator.wrap())::apply;
  *
  * ResolvingCatalogFacade facade = ...
  * facade.setOutboundResolver(resolvingFunction);
@@ -64,7 +65,7 @@ public interface ResolvingFacade {
      * Function applied to all outgoing {@link } objects returned by the facade before leaving
      * the called method
      */
-    void setOutboundResolver(Function resolvingFunction);
+    void setOutboundResolver(UnaryOperator resolvingFunction);
 
     /**
      * Function applied to all incoming {@link } objects before proceeding to execute the called
@@ -75,12 +76,12 @@ public interface ResolvingFacade {
      * to filter out objects based on some externally defined conditions, returning {@code null} if
      * an object is to be discarded from the final outcome
      */
-    Function getOutboundResolver();
+    UnaryOperator getOutboundResolver();
 
     /**
      * Function applied to all incoming {@link } objects before deferring to the decorated facade
      */
-    void setInboundResolver(Function resolvingFunction);
+    void setInboundResolver(UnaryOperator resolvingFunction);
 
     /**
      * Function applied to all incoming {@link } objects before deferring to the decorated
@@ -89,7 +90,7 @@ public interface ResolvingFacade {
      * 

Use {@code facade.setInboundResolver(facade.getInboundResolver().andThen(myFunction))} to * add traits to the current resolver */ - Function getInboundResolver(); + UnaryOperator getInboundResolver(); C resolveOutbound(C info); 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 e832f47c0..c683a3ad9 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 @@ -11,6 +11,7 @@ import org.geoserver.catalog.CatalogInfo; import org.geoserver.catalog.CatalogValidator; import org.geoserver.catalog.CatalogVisitor; +import org.geoserver.catalog.CatalogVisitorAdapter; import org.geoserver.catalog.CoverageInfo; import org.geoserver.catalog.CoverageStoreInfo; import org.geoserver.catalog.DataStoreInfo; @@ -241,7 +242,7 @@ private ValidationResult postValidate(CatalogInfo info, boolean isNew) { return new ValidationResult(errors); } - static class CatalogValidatorVisitor implements CatalogVisitor { + static class CatalogValidatorVisitor extends CatalogVisitorAdapter { CatalogValidator validator; boolean isNew; @@ -251,9 +252,6 @@ static class CatalogValidatorVisitor implements CatalogVisitor { this.isNew = isNew; } - @Override - public void visit(Catalog catalog) {} - @Override public void visit(WorkspaceInfo workspace) { validator.validate(workspace, isNew); 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 f54f7ec1f..66b6981fa 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 @@ -127,8 +127,10 @@ public void validate(StoreInfo store, boolean isNew) { if (isNew) { newObjectPropertiesResolver.resolve(store); } - checkNotEmpty(store.getName(), "Store name must not be null"); - checkNotNull(store.getWorkspace(), "Store must be part of a workspace"); + // note: throwing IAE if null to match CatalogImpl's behavior, though it should be NPE + checkArgument(null != store.getName(), "Store name must not be null"); + checkNotEmpty(store.getName(), "Store name must not be empty"); + checkArgument(null != store.getWorkspace(), "Store must be part of a workspace"); WorkspaceInfo workspace = store.getWorkspace(); StoreInfo existing = catalog.getStoreByName(workspace, store.getName(), StoreInfo.class); @@ -154,8 +156,8 @@ public void validate(ResourceInfo resource, boolean isNew) { && coverage.getNativeCoverageName() != null)) { throw new NullPointerException("Resource native name must not be null"); } - checkNotNull(resource.getStore(), "Resource must be part of a store"); - checkNotNull(resource.getNamespace(), "Resource must be part of a namespace"); + 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 = 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 a263d615f..9dc0683c0 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 @@ -273,15 +273,12 @@ public void add(ServiceInfo service) { validate(service); resolve(service); WorkspaceInfo workspace = service.getWorkspace(); - if (workspace != null) { - if (facade.getServiceByName(service.getName(), workspace, ServiceInfo.class) != null) { - throw new IllegalArgumentException( - "service with name '" - + service.getName() - + "' already exists in workspace '" - + 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); 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 76f7f22aa..3a60dc662 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 @@ -46,9 +46,9 @@ public long nextValue() { lock.lock(); try { GeoServerInfo global = info().orElse(null); - if (global == null) return 0; - long nextVal = sequence.incrementAndGet(); + long nextVal = 0L; if (global != null) { + nextVal = sequence.incrementAndGet(); global = ModificationProxy.unwrap(global); global.setUpdateSequence(nextVal); } 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 fddb108ae..62a676cb3 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 @@ -24,7 +24,6 @@ import static org.junit.jupiter.api.Assertions.assertSame; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doThrow; @@ -290,33 +289,29 @@ void testAddNamespace() { NamespaceInfo ns2 = catalog.getFactory().createNamespace(); - try { - catalog.add(ns2); - fail("adding without a prefix should throw exception"); - } catch (Exception e) { - } + assertThrows( + NullPointerException.class, + () -> catalog.add(ns2), + "adding without a prefix should throw exception"); ns2.setPrefix("ns2Prefix"); - try { - catalog.add(ns2); - fail("adding without a uri should throw exception"); - } catch (Exception e) { - } + assertThrows( + NullPointerException.class, + () -> catalog.add(ns2), + "adding without a uri should throw exception"); ns2.setURI("bad uri"); - try { - catalog.add(ns2); - fail("adding an invalid uri should throw exception"); - } catch (Exception e) { - } + assertThrows( + IllegalArgumentException.class, + () -> catalog.add(ns2), + "adding an invalid uri should throw exception"); ns2.setURI("ns2URI"); - - try { - catalog.getNamespaces().add(ns2); - fail("adding directly should throw an exception"); - } catch (Exception e) { - } + List namespaces = catalog.getNamespaces(); + assertThrows( + UnsupportedOperationException.class, + () -> namespaces.add(ns2), + "adding directly should throw an exception"); catalog.add(ns2); } @@ -370,11 +365,11 @@ void testRemoveNamespace() { catalog.add(data.namespaceA); assertEquals(1, catalog.getNamespaces().size()); - try { - assertFalse(catalog.getNamespaces().remove(data.namespaceA)); - fail("removing directly should throw an exception"); - } catch (Exception e) { - } + List namespaces = catalog.getNamespaces(); + assertThrows( + UnsupportedOperationException.class, + () -> namespaces.remove(data.namespaceA), + "removing directly should throw an exception"); catalog.remove(data.namespaceA); assertTrue(catalog.getNamespaces().isEmpty()); @@ -422,12 +417,13 @@ void testGetNamespaceByURI() { @Test void testSetDefaultNamespaceInvalid() { - try { - catalog.setDefaultNamespace(data.namespaceA); - fail("Default namespace must exist in catalog"); - } catch (IllegalArgumentException e) { - assertEquals("No such namespace: 'wsName'", e.getMessage()); - } + IllegalArgumentException iae = + assertThrows( + IllegalArgumentException.class, + () -> catalog.setDefaultNamespace(data.namespaceA), + "Default namespace must exist in catalog"); + + assertEquals("No such namespace: 'wsName'", iae.getMessage()); } @Test @@ -436,20 +432,19 @@ void testModifyNamespace() { NamespaceInfo ns2 = catalog.getNamespaceByPrefix(data.namespaceA.getPrefix()); ns2.setPrefix(null); - ns2.setURI(null); + ns2.setURI("ns2URI"); - try { - catalog.save(ns2); - fail("setting prefix to null should throw exception"); - } catch (Exception e) { - } + assertThrows( + NullPointerException.class, + () -> catalog.save(ns2), + "setting prefix to null should throw exception"); ns2.setPrefix("ns2Prefix"); - try { - catalog.save(ns2); - fail("setting uri to null should throw exception"); - } catch (Exception e) { - } + ns2.setURI(null); + assertThrows( + NullPointerException.class, + () -> catalog.save(ns2), + "setting uri to null should throw exception"); ns2.setURI("ns2URI"); @@ -515,17 +510,16 @@ void testAddWorkspace() { WorkspaceInfo ws2 = catalog.getFactory().createWorkspace(); - try { - catalog.getWorkspaces().add(ws2); - fail("adding directly should throw an exception"); - } catch (Exception e) { - } + List workspaces = catalog.getWorkspaces(); + assertThrows( + UnsupportedOperationException.class, + () -> workspaces.add(ws2), + "adding directly should throw an exception"); - try { - catalog.add(ws2); - fail("addign without a name should throw an exception"); - } catch (Exception e) { - } + assertThrows( + NullPointerException.class, + () -> catalog.add(ws2), + "adding without a name should throw an exception"); ws2.setName("ws2"); catalog.add(ws2); @@ -536,11 +530,11 @@ void testRemoveWorkspace() { catalog.add(data.workspaceA); assertEquals(1, catalog.getWorkspaces().size()); - try { - assertFalse(catalog.getWorkspaces().remove(data.workspaceA)); - fail("removing directly should throw an exception"); - } catch (Exception e) { - } + List workspaces = catalog.getWorkspaces(); + assertThrows( + UnsupportedOperationException.class, + () -> workspaces.remove(data.workspaceA), + "removing directly should throw an exception"); catalog.remove(data.workspaceA); assertTrue(catalog.getWorkspaces().isEmpty()); @@ -672,12 +666,12 @@ void testGetWorkspaceByName() { @Test void testSetDefaultWorkspaceInvalid() { - try { - catalog.setDefaultWorkspace(data.workspaceA); - fail("Default workspace must exist in catalog"); - } catch (IllegalArgumentException e) { - assertEquals("No such workspace: 'wsName'", e.getMessage()); - } + IllegalArgumentException iae = + assertThrows( + IllegalArgumentException.class, + () -> catalog.setDefaultWorkspace(data.workspaceA), + "Default workspace must exist in catalog"); + assertEquals("No such workspace: 'wsName'", iae.getMessage()); } @Test @@ -686,11 +680,10 @@ void testModifyWorkspace() { WorkspaceInfo ws2 = catalog.getWorkspaceByName(data.workspaceA.getName()); ws2.setName(null); - try { - catalog.save(ws2); - fail("setting name to null should throw exception"); - } catch (Exception e) { - } + assertThrows( + NullPointerException.class, + () -> catalog.save(ws2), + "setting name to null should throw exception"); ws2.setName("ws2"); @@ -744,11 +737,10 @@ void testAddDataStore() { assertTrue(catalog.getDataStores().isEmpty()); data.dataStoreA.setWorkspace(null); - try { - catalog.add(data.dataStoreA); - fail("adding with no workspace should throw exception"); - } catch (Exception e) { - } + assertThrows( + IllegalArgumentException.class, + () -> catalog.add(data.dataStoreA), + "adding with no workspace should throw exception"); data.dataStoreA.setWorkspace(data.workspaceA); catalog.add(data.workspaceA); @@ -761,18 +753,17 @@ void testAddDataStore() { assertSame(catalog, retrieved.getCatalog()); DataStoreInfo ds2 = catalog.getFactory().createDataStore(); - try { - catalog.add(ds2); - fail("adding without a name should throw exception"); - } catch (Exception e) { - } + assertThrows( + IllegalArgumentException.class, + () -> catalog.add(ds2), + "adding without a name should throw exception"); ds2.setName("ds2Name"); - try { - catalog.getDataStores().add(ds2); - fail("adding directly should throw an exception"); - } catch (Exception e) { - } + List dataStores = catalog.getDataStores(); + assertThrows( + UnsupportedOperationException.class, + () -> dataStores.add(ds2), + "adding directly should throw an exception"); ds2.setWorkspace(data.workspaceA); @@ -797,11 +788,12 @@ void testRemoveDataStore() { addDataStore(); assertEquals(1, catalog.getDataStores().size()); - try { - assertFalse(catalog.getDataStores().remove(data.dataStoreA)); - fail("removing directly should throw an exception"); - } catch (Exception e) { - } + List dataStores = catalog.getDataStores(); + assertFalse(catalog.getDataStores().isEmpty()); + assertThrows( + UnsupportedOperationException.class, + () -> dataStores.remove(data.dataStoreA), + "removing directly should throw an exception"); catalog.remove(data.dataStoreA); assertTrue(catalog.getDataStores().isEmpty()); @@ -1135,19 +1127,17 @@ void testAddFeatureType() { assertEquals(1, catalog.getFeatureTypes().size()); FeatureTypeInfo ft2 = catalog.getFactory().createFeatureType(); - try { - catalog.add(ft2); - fail("adding with no name should throw exception"); - } catch (Exception e) { - } + assertThrows( + NullPointerException.class, + () -> catalog.add(ft2), + "adding with no name should throw exception"); ft2.setName("ft2Name"); - try { - catalog.add(ft2); - fail("adding with no store should throw exception"); - } catch (Exception e) { - } + assertThrows( + IllegalArgumentException.class, + () -> catalog.add(ft2), + "adding with no store should throw exception"); ft2.setStore(data.dataStoreA); ft2.getKeywords().add(new Keyword("keyword")); @@ -1158,11 +1148,12 @@ void testAddFeatureType() { FeatureTypeInfo ft3 = catalog.getFactory().createFeatureType(); ft3.setName("ft3Name"); - try { - catalog.getFeatureTypes().add(ft3); - fail("adding directly should throw an exception"); - } catch (Exception e) { - } + + List featureTypes = catalog.getFeatureTypes(); + assertThrows( + UnsupportedOperationException.class, + () -> featureTypes.add(ft3), + "adding directly should throw an exception"); } @Test @@ -1175,18 +1166,16 @@ void testAddCoverage() { assertEquals(1, catalog.getCoverages().size()); CoverageInfo cv2 = catalog.getFactory().createCoverage(); - try { - catalog.add(cv2); - fail("adding with no name should throw exception"); - } catch (Exception e) { - } + assertThrows( + NullPointerException.class, + () -> catalog.add(cv2), + "adding with no name should throw exception"); cv2.setName("cv2Name"); - try { - catalog.add(cv2); - fail("adding with no store should throw exception"); - } catch (Exception e) { - } + assertThrows( + IllegalArgumentException.class, + () -> catalog.add(cv2), + "adding with no store should throw exception"); cv2.setStore(data.coverageStoreA); catalog.add(cv2); @@ -1200,11 +1189,11 @@ void testAddCoverage() { CoverageInfo cv3 = catalog.getFactory().createCoverage(); cv3.setName("cv3Name"); - try { - catalog.getCoverages().add(cv3); - fail("adding directly should throw an exception"); - } catch (Exception e) { - } + List coverages = catalog.getCoverages(); + assertThrows( + UnsupportedOperationException.class, + () -> coverages.add(cv3), + "adding directly should throw an exception"); } @Test @@ -1227,11 +1216,11 @@ void testRemoveFeatureType() { addFeatureType(); assertFalse(catalog.getFeatureTypes().isEmpty()); - try { - catalog.getFeatureTypes().remove(data.featureTypeA); - fail("removing directly should cause exception"); - } catch (Exception e) { - } + List featureTypes = catalog.getFeatureTypes(); + assertThrows( + UnsupportedOperationException.class, + () -> featureTypes.remove(data.featureTypeA), + "removing directly should cause exception"); catalog.remove(data.featureTypeA); assertTrue(catalog.getFeatureTypes().isEmpty()); @@ -1498,18 +1487,16 @@ void testAddLayer() { assertEquals(1, catalog.getLayers().size()); LayerInfo l2 = catalog.getFactory().createLayer(); - try { - catalog.add(l2); - fail("adding with no name should throw exception"); - } catch (Exception e) { - } + assertThrows( + NullPointerException.class, + () -> catalog.add(l2), + "adding with no name should throw exception"); // l2.setName( "l2" ); - try { - catalog.add(l2); - fail("adding with no resource should throw exception"); - } catch (Exception e) { - } + assertThrows( + NullPointerException.class, + () -> catalog.add(l2), + "adding with no resource should throw exception"); l2.setResource(data.featureTypeA); // try { @@ -1520,13 +1507,13 @@ void testAddLayer() { // l2.setDefaultStyle(data.style1); - try { - catalog.add(l2); - fail( - "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"); - } catch (Exception e) { - assertTrue(e.getMessage().contains("already exists")); - } + 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")); assertEquals(1, catalog.getLayers().size()); } @@ -1739,11 +1726,10 @@ void testModifyLayer() { // catch( Exception e ) {} // // l2.setName( "changed" ); - try { - catalog.save(l2); - fail("setting resource to null should throw exception"); - } catch (Exception e) { - } + assertThrows( + NullPointerException.class, + () -> catalog.save(l2), + "setting resource to null should throw exception"); l2.setResource(data.featureTypeA); catalog.save(l2); @@ -1839,25 +1825,23 @@ void testAddStyle() { assertEquals(1, catalog.getStyles().size()); StyleInfo s2 = catalog.getFactory().createStyle(); - try { - catalog.add(s2); - fail("adding without name should throw exception"); - } catch (Exception e) { - } + assertThrows( + NullPointerException.class, + () -> catalog.add(s2), + "adding without name should throw exception"); s2.setName("s2Name"); - try { - catalog.add(s2); - fail("adding without fileName should throw exception"); - } catch (Exception e) { - } + assertThrows( + NullPointerException.class, + () -> catalog.add(s2), + "adding without fileName should throw exception"); s2.setFilename("s2Filename"); - try { - catalog.getStyles().add(s2); - fail("adding directly should throw exception"); - } catch (Exception e) { - } + List styles = catalog.getStyles(); + assertThrows( + UnsupportedOperationException.class, + () -> styles.add(s2), + "adding directly should throw exception"); catalog.add(s2); assertEquals(2, catalog.getStyles().size()); @@ -1872,11 +1856,10 @@ void testAddStyleWithNameConflict() throws Exception { s2.setName(data.style1.getName()); s2.setFilename(data.style1.getFilename()); - try { - catalog.add(s2); - fail("Should have failed with existing global style with same name"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> catalog.add(s2), + "Should have failed with existing global style with same name"); List currStyles = catalog.getStyles(); @@ -1892,18 +1875,10 @@ void testAddStyleWithNameConflict() throws Exception { s3.setName(s2.getName()); s3.setFilename(s2.getFilename()); - try { - catalog.add(s3); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> catalog.add(s3)); s3.setWorkspace(data.workspaceA); - try { - catalog.add(s3); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> catalog.add(s3)); } @Test @@ -2010,18 +1985,16 @@ void testModifyStyle() { StyleInfo s3 = catalog.getStyleByName(data.style1.getName()); assertEquals(data.style1, s3); - try { - catalog.save(s2); - fail("setting name to null should fail"); - } catch (Exception e) { - } + assertThrows( + NullPointerException.class, + () -> catalog.save(s2), + "setting name to null should fail"); s2.setName(data.style1.getName()); - try { - catalog.save(s2); - fail("setting filename to null should fail"); - } catch (Exception e) { - } + assertThrows( + NullPointerException.class, + () -> catalog.save(s2), + "setting filename to null should fail"); s2.setName("s2Name"); s2.setFilename("s2Name.sld"); @@ -2038,23 +2011,21 @@ void testModifyStyle() { void testModifyDefaultStyle() { addWorkspace(); addDefaultStyle(); - StyleInfo s = catalog.getStyleByName(StyleInfo.DEFAULT_LINE); + final StyleInfo s = catalog.getStyleByName(StyleInfo.DEFAULT_LINE); s.setName("foo"); - try { - catalog.save(s); - fail("changing name of default style should fail"); - } catch (Exception e) { - } + assertThrows( + IllegalArgumentException.class, + () -> catalog.save(s), + "changing name of default style should fail"); - s = catalog.getStyleByName(StyleInfo.DEFAULT_LINE); - s.setWorkspace(data.workspaceA); - try { - catalog.save(s); - fail("changing workspace of default style should fail"); - } catch (Exception e) { - } + final StyleInfo s2 = catalog.getStyleByName(StyleInfo.DEFAULT_LINE); + s2.setWorkspace(data.workspaceA); + assertThrows( + IllegalArgumentException.class, + () -> catalog.save(s2), + "changing workspace of default style should fail"); } @Test @@ -2072,11 +2043,10 @@ void testRemoveDefaultStyle() { addDefaultStyle(); StyleInfo s = catalog.getStyleByName(StyleInfo.DEFAULT_LINE); - try { - catalog.remove(s); - fail("removing default style should fail"); - } catch (Exception e) { - } + assertThrows( + IllegalArgumentException.class, + () -> catalog.remove(s), + "removing default style should fail"); } @Test @@ -2142,7 +2112,7 @@ void testProxyListBehaviour() throws Exception { s2.setFilename("a.sld"); catalog.add(s2); - List styles = catalog.getStyles(); + final List styles = catalog.getStyles(); assertEquals(2, styles.size()); // test immutability @@ -2153,18 +2123,16 @@ public int compare(StyleInfo o1, StyleInfo o2) { return o1.getName().compareTo(o2.getName()); } }; - try { - Collections.sort(styles, comparator); - fail("Expected runtime exception, immutable collection"); - } catch (RuntimeException e) { - assertTrue(true); - } + assertThrows( + RuntimeException.class, + () -> Collections.sort(styles, comparator), + "Expected runtime exception, immutable collection"); - styles = new ArrayList(styles); - Collections.sort(styles, comparator); + List sorted = new ArrayList(styles); + Collections.sort(sorted, comparator); - assertEquals("a" + data.style1.getName(), styles.get(0).getName()); - assertEquals(data.style1.getName(), styles.get(1).getName()); + assertEquals("a" + data.style1.getName(), sorted.get(0).getName()); + assertEquals(data.style1.getName(), sorted.get(1).getName()); } @Test @@ -2181,15 +2149,13 @@ void testExceptionThrowingListener() throws Exception { catalog.add(ws); l.throwCatalogException = true; - ws = catalog.getFactory().createWorkspace(); - ws.setName("bar"); + final WorkspaceInfo ws2 = catalog.getFactory().createWorkspace(); + ws2.setName("bar"); - try { - catalog.add(ws); - fail(); - } catch (CatalogException ce) { - // good - } + CatalogException ce = assertThrows(CatalogException.class, () -> catalog.add(ws2)); + assertThat( + ce.getMessage(), + containsString("expected, testing Catalog's CatalogException handling")); } @Test @@ -2286,11 +2252,10 @@ void testAddLayerGroupNameConflict() throws Exception { lg2.setName("layerGroup"); lg2.getLayers().add(data.layerFeatureTypeA); lg2.getStyles().add(data.style1); - try { - catalog.add(lg2); - fail("should have failed because same name and no workspace set"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> catalog.add(lg2), + "should have failed because same name and no workspace set"); // setting a workspace shluld pass lg2.setWorkspace(data.workspaceA); @@ -2308,11 +2273,7 @@ void testAddLayerGroupWithWorkspaceWithResourceFromAnotherWorkspace() { lg2.setName("layerGroup2"); lg2.getLayers().add(data.layerFeatureTypeA); lg2.getStyles().add(data.style1); - try { - catalog.add(lg2); - fail(); - } catch (IllegalArgumentException expected) { - } + assertThrows(IllegalArgumentException.class, () -> catalog.add(lg2)); } @Test @@ -2563,7 +2524,7 @@ void testLayerGroupType() { @Test void testLayerGroupRootLayer() { addLayer(); - LayerGroupInfo lg2 = catalog.getFactory().createLayerGroup(); + final LayerGroupInfo lg2 = catalog.getFactory().createLayerGroup(); lg2.setWorkspace(null); lg2.setName("layerGroup2"); lg2.getLayers().add(data.layerFeatureTypeA); @@ -2571,55 +2532,45 @@ void testLayerGroupRootLayer() { lg2.setRootLayer(data.layerFeatureTypeA); lg2.setMode(LayerGroupInfo.Mode.SINGLE); - try { - catalog.add(lg2); - fail("only EO layer groups can have a root layer"); - } catch (IllegalArgumentException e) { - assertTrue(true); - } + assertThrows( + IllegalArgumentException.class, + () -> catalog.add(lg2), + "only EO layer groups can have a root layer"); lg2.setMode(LayerGroupInfo.Mode.NAMED); - try { - catalog.add(lg2); - fail("only EO layer groups can have a root layer"); - } catch (IllegalArgumentException e) { - assertTrue(true); - } + assertThrows( + IllegalArgumentException.class, + () -> catalog.add(lg2), + "only EO layer groups can have a root layer"); lg2.setMode(LayerGroupInfo.Mode.CONTAINER); - try { - catalog.add(lg2); - fail("only EO layer groups can have a root layer"); - } catch (IllegalArgumentException e) { - assertTrue(true); - } + assertThrows( + IllegalArgumentException.class, + () -> catalog.add(lg2), + "only EO layer groups can have a root layer"); lg2.setMode(LayerGroupInfo.Mode.EO); lg2.setRootLayer(null); - try { - catalog.add(lg2); - fail("EO layer groups must have a root layer"); - } catch (IllegalArgumentException e) { - assertTrue(true); - } + assertThrows( + IllegalArgumentException.class, + () -> catalog.add(lg2), + "EO layer groups must have a root layer"); lg2.setRootLayer(data.layerFeatureTypeA); - try { - catalog.add(lg2); - fail("EO layer groups must have a root layer style"); - } catch (IllegalArgumentException e) { - assertTrue(true); - } + assertThrows( + IllegalArgumentException.class, + () -> catalog.add(lg2), + "EO layer groups must have a root layer style"); lg2.setRootLayerStyle(data.style1); catalog.add(lg2); assertEquals(1, catalog.getLayerGroups().size()); - lg2 = catalog.getLayerGroupByName("layerGroup2"); - assertEquals(LayerGroupInfo.Mode.EO, lg2.getMode()); - assertEquals(data.layerFeatureTypeA, lg2.getRootLayer()); - assertEquals(data.style1, lg2.getRootLayerStyle()); + LayerGroupInfo lg2Saved = catalog.getLayerGroupByName("layerGroup2"); + assertEquals(LayerGroupInfo.Mode.EO, lg2Saved.getMode()); + assertEquals(data.layerFeatureTypeA, lg2Saved.getRootLayer()); + assertEquals(data.style1, lg2Saved.getRootLayerStyle()); } @Test @@ -2687,18 +2638,14 @@ void testLayerGroupRenderingLayers() { assertEquals(lg2.getStyles(), lg2.styles()); lg2.setMode(LayerGroupInfo.Mode.CONTAINER); - try { - assertEquals(lg2.getLayers(), lg2.layers()); - fail("Layer group of Type Container can not be rendered"); - } catch (UnsupportedOperationException e) { - assertTrue(true); - } - try { - assertEquals(lg2.getStyles(), lg2.styles()); - fail("Layer group of Type Container can not be rendered"); - } catch (UnsupportedOperationException e) { - assertTrue(true); - } + assertThrows( + 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"); lg2.setMode(LayerGroupInfo.Mode.EO); assertEquals(1, lg2.layers().size()); @@ -2718,11 +2665,10 @@ void testRemoveLayerGroupInLayerGroup() throws Exception { lg2.getStyles().add(data.style1); catalog.add(lg2); - try { - catalog.remove(data.layerGroup1); - fail("should have failed because lg is in another lg"); - } catch (IllegalArgumentException expected) { - } + assertThrows( + IllegalArgumentException.class, + () -> catalog.remove(data.layerGroup1), + "should have failed because lg is in another lg"); // removing the containing layer first should work catalog.remove(lg2); @@ -2834,28 +2780,24 @@ void testGet() { catalog.add(l1); catalog.add(l2); - Filter filter = acceptAll(); - try { - catalog.get(null, filter); - fail("Expected precondition validation exception"); - } catch (RuntimeException nullCheck) { - assertTrue(true); - } - try { - catalog.get(FeatureTypeInfo.class, null); - fail("Expected precondition validation exception"); - } catch (RuntimeException nullCheck) { - assertTrue(true); - } - - try { - catalog.get(FeatureTypeInfo.class, filter); - fail("Expected IAE on multiple results"); - } catch (IllegalArgumentException multipleResults) { - assertTrue(true); - } - - filter = equal("id", ft1.getId()); + { + final Filter filter = acceptAll(); + assertThrows( + NullPointerException.class, + () -> catalog.get(null, filter), + "Expected precondition validation exception"); + assertThrows( + IllegalArgumentException.class, + () -> catalog.get(FeatureTypeInfo.class, null), + "Expected precondition validation exception"); + + assertThrows( + IllegalArgumentException.class, + () -> catalog.get(FeatureTypeInfo.class, filter), + "Expected IAE on multiple results"); + } + + Filter filter = equal("id", ft1.getId()); FeatureTypeInfo featureTypeInfo = catalog.get(FeatureTypeInfo.class, filter); assertEquals(ft1.getId(), featureTypeInfo.getId()); assertSame(catalog, featureTypeInfo.getCatalog()); @@ -2869,13 +2811,11 @@ void testGet() { filter = equal("keywords[2]", ft2.getKeywords().get(1)); assertEquals(ft2.getName(), catalog.get(FeatureTypeInfo.class, filter).getName()); - filter = equal("keywords[3].value", "repeatedKw"); - try { - catalog.get(FeatureTypeInfo.class, filter).getName(); - fail("Expected IAE on multiple results"); - } catch (IllegalArgumentException multipleResults) { - assertTrue(true); - } + Filter filterMultipleResults = equal("keywords[3].value", "repeatedKw"); + assertThrows( + IllegalArgumentException.class, + () -> catalog.get(FeatureTypeInfo.class, filterMultipleResults), + "Expected IAE on multiple results"); assertEquals( s1.getId(), catalog.get(StyleInfo.class, equal("filename", "s1Filename")).getId()); @@ -2891,13 +2831,12 @@ void testGet() { filter = equal("styles.id", s2.getId(), MatchAction.ONE); assertEquals(l1.getId(), catalog.get(LayerInfo.class, filter).getId()); - filter = equal("styles.id", s3.getId(), MatchAction.ANY); // s3 is shared by l1 and l2 - try { - catalog.get(LayerInfo.class, filter); - fail("Expected IAE on multiple results"); - } catch (IllegalArgumentException multipleResults) { - assertTrue(true); - } + Filter filter2 = + equal("styles.id", s3.getId(), MatchAction.ANY); // s3 is shared by l1 and l2 + assertThrows( + IllegalArgumentException.class, + () -> catalog.get(LayerInfo.class, filter2), + "Expected IAE on multiple results"); } @Test 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 a5e6dad8d..d69adb567 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 @@ -13,6 +13,8 @@ import org.geoserver.config.util.XStreamPersisterFactory; import org.junit.jupiter.api.Disabled; +import java.util.function.UnaryOperator; + class XmlCatalogInfoLookupConformanceTest extends CatalogConformanceTest { protected @Override CatalogPlugin createCatalog() { @@ -34,10 +36,12 @@ class XmlCatalogInfoLookupConformanceTest extends CatalogConformanceTest { ResolvingCatalogFacadeDecorator resolving = new ResolvingCatalogFacadeDecorator(rawFacade); - resolving.setOutboundResolver( // + UnaryOperator chainedResolver = CatalogPropertyResolver.of(catalog) // - .andThen(ResolvingProxyResolver.of(catalog)) // - .andThen(CollectionPropertiesInitializer.instance())); + .andThen(ResolvingProxyResolver.of(catalog)) // + .andThen(CollectionPropertiesInitializer.instance()) + ::apply; + resolving.setOutboundResolver(chainedResolver); catalog.setFacade(resolving); return catalog; } 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 63fe6080d..42c998b19 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 @@ -119,7 +119,7 @@ ForwardGetMapToGwcAspect gwcGetMapAdvise(GWC gwc) { static @Configuration class GeoServerWebUI { @Bean - HeaderContribution GWCSettingsPage_WMSIntegationDisabledCssContribution() { + HeaderContribution gwcSettingsPageWMSIntegationDisabledCssContribution() { log.info("GeoWebCache direct WMS integration disabled in GWCSettingsPage"); HeaderContribution contribution = new HeaderContribution(); contribution.setScope(GWCSettingsPage.class); 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 81f504757..ccd46ab79 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 @@ -71,7 +71,7 @@ void disabledByDefault() { assertThat(context).doesNotHaveBean(ForwardGetMapToGwcAspect.class); assertThat(context) .doesNotHaveBean( - "GWCSettingsPage_WMSIntegationDisabledCssContribution"); + "gwcSettingsPageWMSIntegationDisabledCssContribution"); }); } @@ -85,7 +85,7 @@ void enabledByConfigAndGeoServerWebMapServiceNotFound() { assertThat(context).doesNotHaveBean(ForwardGetMapToGwcAspect.class); assertThat(context) .doesNotHaveBean( - "GWCSettingsPage_WMSIntegationDisabledCssContribution"); + "gwcSettingsPageWMSIntegationDisabledCssContribution"); }); } @@ -100,7 +100,7 @@ void enabledByConfigAndGeoServerWebMapServiceFound() { assertThat(context).hasSingleBean(ForwardGetMapToGwcAspect.class); assertThat(context) .doesNotHaveBean( - "GWCSettingsPage_WMSIntegationDisabledCssContribution"); + "gwcSettingsPageWMSIntegationDisabledCssContribution"); }); } @@ -114,11 +114,10 @@ void disabledContributesCssToHideWebUIComponents() { .doesNotHaveBean(CachingExtendedCapabilitiesProvider.class); assertThat(context).doesNotHaveBean(ForwardGetMapToGwcAspect.class); assertThat(context) - .hasBean( - "GWCSettingsPage_WMSIntegationDisabledCssContribution"); + .hasBean("gwcSettingsPageWMSIntegationDisabledCssContribution"); HeaderContribution contrib = context.getBean( - "GWCSettingsPage_WMSIntegationDisabledCssContribution", + "gwcSettingsPageWMSIntegationDisabledCssContribution", HeaderContribution.class); assertEquals(GWCSettingsPage.class, contrib.getScope()); assertEquals( 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 1f0f19492..4dc32a407 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 @@ -37,28 +37,26 @@ public class SimpleNamingContext implements Context { private final String contextRoot; - private final ConcurrentMap bindings; + private final ConcurrentMap bindings = new ConcurrentHashMap<>(); private final ConcurrentMap environment = new ConcurrentHashMap<>(); public SimpleNamingContext() { - this(ROOT_NAME, new ConcurrentHashMap<>()); + this(ROOT_NAME, Map.of()); } - SimpleNamingContext(@NonNull String root, @NonNull ConcurrentMap env) { - this(root, new ConcurrentHashMap<>(), env); + SimpleNamingContext(@NonNull String root, @NonNull Map env) { + this(root, Map.of(), env); } SimpleNamingContext( @NonNull String root, - @NonNull ConcurrentMap boundObjects, - @NonNull ConcurrentMap env) { + @NonNull Map boundObjects, + @NonNull Map env) { this.contextRoot = root; - this.bindings = boundObjects; - if (env != null) { - this.environment.putAll(env); - } + this.bindings.putAll(boundObjects); + this.environment.putAll(env); } @Override @@ -159,7 +157,10 @@ public Object removeFromEnvironment(String propName) { } @Override - public void close() {} + public void close() { + this.environment.clear(); + this.bindings.clear(); + } /** * @throws OperationNotSupportedException javax.naming.Name is not supported 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 b286df2d2..46e0dd9d5 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 @@ -29,12 +29,13 @@ public class GatewayPreAuthenticationFilter extends GeoServerRequestHeaderAuthen /** Try to authenticate if there is no authenticated principal */ @Override - public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) + public void doFilter(final ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { - String cacheKey = authenticateFromCache(this, (HttpServletRequest) request); + final HttpServletRequest httpRequest = (HttpServletRequest) request; + String cacheKey = authenticateFromCache(this, httpRequest); - String principalName = getPreAuthenticatedPrincipalName((HttpServletRequest) request); + String principalName = getPreAuthenticatedPrincipalName(httpRequest); Authentication preAuth = SecurityContextHolder.getContext().getAuthentication(); @@ -47,16 +48,18 @@ public void doFilter(ServletRequest request, ServletResponse response, FilterCha if (preAuth == null || principalName != null) { log.debug("Authenticating as {}", principalName); - doAuthenticate((HttpServletRequest) request, (HttpServletResponse) response); + doAuthenticate(httpRequest, (HttpServletResponse) response); Authentication postAuthentication = SecurityContextHolder.getContext().getAuthentication(); - if (postAuthentication != null && cacheKey != null) { - if (cacheAuthentication(postAuthentication, (HttpServletRequest) request)) { - getSecurityManager() - .getAuthenticationCache() - .put(getName(), cacheKey, postAuthentication); - } + + boolean authenticated = postAuthentication != null; + boolean cached = cacheKey != null; + boolean sessionAvailable = cacheAuthentication(postAuthentication, httpRequest); + if (authenticated && cached && sessionAvailable) { + getSecurityManager() + .getAuthenticationCache() + .put(getName(), cacheKey, postAuthentication); } }