From 603328e0fe491c26ed8a9dc10029188a64ad6911 Mon Sep 17 00:00:00 2001 From: Chris Dennis Date: Wed, 6 Oct 2021 13:47:32 -0400 Subject: [PATCH] wip --- azure-pipelines-static-analysis.yml | 3 +- azure-pipelines.yml | 15 +- .../build/conventions/JavaBaseConvention.java | 4 +- build.gradle | 2 +- .../store/CommonServerStoreProxy.java | 2 +- ...terTierManagerClientEntityFactoryTest.java | 11 +- .../internal/UnitTestConnectionService.java | 28 +-- .../ClusteredLoaderWriterStoreTest.java | 5 +- .../lock/VoltronReadWriteLockTest.java | 15 +- ...ClusterStateRepositoryReplicationTest.java | 7 +- .../DefaultClusteringServiceDestroyTest.java | 11 +- .../StateRepositoryWhitelistingTest.java | 14 +- .../internal/store/ClusteredStoreTest.java | 2 +- .../lock/LockRetentionDuringFailoverTest.java | 7 +- .../ActivePassiveClientIdTest.java | 7 +- .../operations/ExpiryChainResolverTest.java | 50 ++--- .../store/operations/LazyValueHolderTest.java | 10 +- clustered/ehcache-clustered/build.gradle | 4 +- .../Store/WhitelistedUnmarshallingTest.java | 18 +- .../internal/messages/ChainCodecTest.java | 11 +- .../internal/messages/EhcacheCodecTest.java | 14 +- .../internal/messages/ResponseCodecTest.java | 2 +- .../ClusteringManagementServiceTest.java | 11 +- .../messages/EhcacheServerCodecTest.java | 19 +- .../store/ClusterTierActiveEntityTest.java | 4 +- clustered/server/ehcache-service/build.gradle | 2 + .../offheap/OffHeapChainStorageEngine.java | 4 +- .../server/offheap/ChainMapExtensionTest.java | 2 +- .../server/offheap/ChainMapTest.java | 2 +- .../EhcacheStateServiceProviderTest.java | 16 +- .../ParsesConfigurationExtensionTest.java | 2 +- .../jsr107/LoadAtomicsWith107Test.java | 8 +- .../jsr107/LoaderWriterConfigTest.java | 11 +- .../org/ehcache/jsr107/LoaderWriterTest.java | 69 +++---- .../ehcache/core/EhcacheBasicClearTest.java | 5 +- .../core/EhcacheBasicContainsKeyTest.java | 9 +- .../ehcache/core/EhcacheBasicCrudBase.java | 8 +- .../ehcache/core/EhcacheBasicGetAllTest.java | 7 +- .../org/ehcache/core/EhcacheBasicGetTest.java | 5 +- .../core/EhcacheBasicIteratorTest.java | 1 - .../ehcache/core/EhcacheBasicPutAllTest.java | 3 +- .../core/EhcacheBasicPutIfAbsentTest.java | 6 +- .../org/ehcache/core/EhcacheBasicPutTest.java | 6 +- .../core/EhcacheBasicRemoveAllTest.java | 3 +- .../ehcache/core/EhcacheBasicRemoveTest.java | 5 +- .../core/EhcacheBasicRemoveValueTest.java | 7 +- .../ehcache/core/EhcacheBasicReplaceTest.java | 5 +- .../core/EhcacheBasicReplaceValueTest.java | 7 +- .../ehcache/core/EhcacheBulkMethodsTest.java | 1 + ehcache-impl/build.gradle | 8 +- .../commonslang/reflect/MemberUtils.java | 1 + .../serialization/PlainJavaSerializer.java | 1 + .../CacheConfigurationBuilderTest.java | 17 +- .../ehcache/docs/ConfigurationDerivation.java | 3 +- ...ustLoaderWriterResilienceStrategyTest.java | 6 +- .../store/heap/OnHeapStrategyTest.java | 10 +- .../offheap/AssertingOffHeapValueHolder.java | 6 +- .../store/tiering/TieredStoreTest.java | 18 +- .../impl/serialization/AddedFieldTest.java | 4 +- .../serialization/AddedSuperClassTest.java | 4 +- .../CompactJavaSerializerClassLoaderTest.java | 4 +- ...mpactJavaSerializerClassUnloadingTest.java | 2 +- .../ehcache/impl/serialization/EnumTest.java | 7 +- .../impl/serialization/GetFieldTest.java | 2 +- .../impl/serialization/JavaSerializer.java | 2 +- .../impl/serialization/PutFieldTest.java | 4 +- .../serialization/ReadObjectNoDataTest.java | 2 +- .../SerializeAfterEvolutionTest.java | 4 +- .../concurrent/ConcurrentHashMap.java | 189 ++++++++---------- .../DefaultManagementRegistryServiceTest.java | 9 +- .../xa/internal/SoftLockSerializer.java | 2 +- .../LookupTransactionManagerProvider.java | 4 +- .../xa/internal/EhcacheXAResourceTest.java | 11 +- .../transactions/xa/utils/JavaSerializer.java | 6 +- ehcache-xml/build.gradle | 13 +- .../src/common/schema/ehcache-core.xsd | 10 - .../org/ehcache/xml/ConfigurationParser.java | 11 +- .../xml/CoreCacheConfigurationParser.java | 10 +- .../org/ehcache/xml/XmlConfiguration.java | 42 ++-- .../org/ehcache/xml/ConfigurationParser.java | 6 +- .../xml/CoreCacheConfigurationParser.java | 10 +- .../org/ehcache/xml/XmlConfiguration.java | 10 +- .../xml/IntegrationConfigurationTest.java | 9 +- ...patcherFactoryConfigurationParserTest.java | 8 +- ...gerPersistenceConfigurationParserTest.java | 7 +- ...ltCopyProviderConfigurationParserTest.java | 7 +- ...zationProviderConfigurationParserTest.java | 7 +- ...EngineProviderConfigurationParserTest.java | 8 +- ...kStoreProviderConfigurationParserTest.java | 8 +- ...ecutionServiceConfigurationParserTest.java | 7 +- ...BehindProviderConfigurationParserTest.java | 8 +- ehcache/build.gradle | 4 +- gradle.properties | 2 +- .../LoaderWriterSimpleEhcacheTest.java | 8 +- .../integration/OverSizeMappingTest.java | 1 + 95 files changed, 430 insertions(+), 562 deletions(-) diff --git a/azure-pipelines-static-analysis.yml b/azure-pipelines-static-analysis.yml index 4c3f99b9a8..3df8f3b39e 100644 --- a/azure-pipelines-static-analysis.yml +++ b/azure-pipelines-static-analysis.yml @@ -20,10 +20,11 @@ resources: repositories: - repository: templates - type: git + type: git name: terracotta/terracotta jobs: - template: build-templates/gradle-common.yml@templates parameters: + jdkVersion: '1.11' gradleTasks: 'check' diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 590980b08b..fd7947aa1d 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -26,24 +26,13 @@ resources: jobs: - template: build-templates/gradle-common.yml@templates parameters: - jdkVersion: '1.8' - jobName: 'LinuxJava8' - -- template: build-templates/gradle-common.yml@templates - parameters: - jdkVersion: '1.8' + jdkVersion: '1.11' options: '-PtestVM=java11Home' jobName: 'LinuxJava11' - template: build-templates/gradle-common.yml@templates parameters: vmImage: 'windows-latest' - jdkVersion: '1.8' - jobName: 'WindowsJava8' - -- template: build-templates/gradle-common.yml@templates - parameters: - vmImage: 'windows-latest' - jdkVersion: '1.8' + jdkVersion: '1.11' options: '-PtestVM=java11Home' jobName: 'WindowsJava11' diff --git a/build-logic/src/main/java/org/ehcache/build/conventions/JavaBaseConvention.java b/build-logic/src/main/java/org/ehcache/build/conventions/JavaBaseConvention.java index 83ce040a2c..ff5d089158 100644 --- a/build-logic/src/main/java/org/ehcache/build/conventions/JavaBaseConvention.java +++ b/build-logic/src/main/java/org/ehcache/build/conventions/JavaBaseConvention.java @@ -33,8 +33,8 @@ public void apply(Project project) { project.getExtensions().getExtraProperties().set("testJava", testJava); project.getExtensions().configure(JavaPluginExtension.class, java -> { - java.setSourceCompatibility(JavaVersion.VERSION_1_8); - java.setTargetCompatibility(JavaVersion.VERSION_1_8); + java.setSourceCompatibility(JavaVersion.VERSION_11); + java.setTargetCompatibility(JavaVersion.VERSION_11); }); project.getTasks().withType(Jar.class).configureEach(jar -> { diff --git a/build.gradle b/build.gradle index 1e9acbdb44..d79200553d 100644 --- a/build.gradle +++ b/build.gradle @@ -61,7 +61,7 @@ tasks.named('closeAndReleaseRepository') { enabled = false; } -assert (JavaVersion.current().isJava8Compatible()) : 'The Ehcache 3 build requires Java 8+ to run' +assert (JavaVersion.current().isJava11Compatible()) : 'The Ehcache 3 build requires Java 11+ to run' dependencyCheck { failBuildOnCVSS = 0 diff --git a/clustered/ehcache-client/src/main/java/org/ehcache/clustered/client/internal/store/CommonServerStoreProxy.java b/clustered/ehcache-client/src/main/java/org/ehcache/clustered/client/internal/store/CommonServerStoreProxy.java index 81ef2c294c..286f3cac70 100644 --- a/clustered/ehcache-client/src/main/java/org/ehcache/clustered/client/internal/store/CommonServerStoreProxy.java +++ b/clustered/ehcache-client/src/main/java/org/ehcache/clustered/client/internal/store/CommonServerStoreProxy.java @@ -231,7 +231,7 @@ public Map.Entry next() { } } - @Override + @Override @SuppressWarnings("deprecation") protected void finalize() throws Throwable { if (!lastBatch) { entity.invokeAndWaitForReceive(new ServerStoreOpMessage.IteratorCloseMessage(iteratorId), false); diff --git a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/ClusterTierManagerClientEntityFactoryTest.java b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/ClusterTierManagerClientEntityFactoryTest.java index d82db588d0..d38c30810d 100644 --- a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/ClusterTierManagerClientEntityFactoryTest.java +++ b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/ClusterTierManagerClientEntityFactoryTest.java @@ -19,10 +19,10 @@ import org.ehcache.clustered.common.internal.ClusterTierManagerConfiguration; import org.ehcache.clustered.common.internal.lock.LockMessaging.HoldType; import org.ehcache.clustered.client.internal.lock.VoltronReadWriteLockClient; -import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; import org.terracotta.connection.Connection; import static org.hamcrest.MatcherAssert.assertThat; @@ -47,6 +47,7 @@ import org.terracotta.exception.EntityConfigurationException; import org.terracotta.exception.EntityNotFoundException; +@RunWith(MockitoJUnitRunner.class) public class ClusterTierManagerClientEntityFactoryTest { @Mock @@ -56,11 +57,6 @@ public class ClusterTierManagerClientEntityFactoryTest { @Mock private Connection connection; - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - @Test public void testCreate() throws Exception { when(getEntityRef(ClusterTierManagerClientEntity.class)).thenReturn(entityRef); @@ -140,7 +136,6 @@ public void testRetrieveFailedValidate() throws Exception { @SuppressWarnings("unchecked") public void testRetrieveWhenNotExisting() throws Exception { when(entityRef.fetchEntity(null)).thenThrow(EntityNotFoundException.class); - doThrow(EntityAlreadyExistsException.class).when(entityRef).create(any()); when(getEntityRef(ClusterTierManagerClientEntity.class)).thenReturn(entityRef); addMockUnlockedLock(connection, "VoltronReadWriteLock-ClusterTierManagerClientEntityFactory-AccessLock-test"); diff --git a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/UnitTestConnectionService.java b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/UnitTestConnectionService.java index c6b66f3f6d..1e530dcad0 100644 --- a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/UnitTestConnectionService.java +++ b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/UnitTestConnectionService.java @@ -22,7 +22,6 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; -import java.math.BigInteger; import java.net.InetSocketAddress; import java.net.URI; import java.net.URISyntaxException; @@ -35,7 +34,6 @@ import java.util.List; import java.util.Map; import java.util.Properties; -import java.util.stream.Collectors; import org.ehcache.clustered.client.internal.lock.VoltronReadWriteLockEntityClientService; import org.ehcache.clustered.client.internal.store.ClusterTierClientEntityService; @@ -46,6 +44,8 @@ import org.ehcache.impl.internal.concurrent.ConcurrentHashMap; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.terracotta.common.struct.Measure; +import org.terracotta.common.struct.MemoryUnit; import org.terracotta.connection.Connection; import org.terracotta.connection.ConnectionException; import org.terracotta.connection.ConnectionPropertyNames; @@ -62,15 +62,11 @@ import org.terracotta.exception.EntityNotProvidedException; import org.terracotta.exception.PermanentEntityException; import org.terracotta.offheapresource.OffHeapResourcesProvider; -import org.terracotta.offheapresource.config.MemoryUnit; -import org.terracotta.offheapresource.config.OffheapResourcesType; -import org.terracotta.offheapresource.config.ResourceType; import org.terracotta.passthrough.IAsynchronousServerCrasher; import org.terracotta.passthrough.PassthroughConnection; import org.terracotta.passthrough.PassthroughServer; import org.terracotta.passthrough.PassthroughServerRegistry; -import static java.util.stream.Collectors.toCollection; import static java.util.stream.Collectors.toList; import static org.mockito.Mockito.mock; @@ -175,20 +171,6 @@ public static void removeStripe(String stripeName) { stripeDescriptor.removeConnections(); } - public static OffheapResourcesType getOffheapResourcesType(String resourceName, int size, MemoryUnit unit) { - OffheapResourcesType resources = new OffheapResourcesType(); - resources.getResource().add(getResource(resourceName, size, unit)); - return resources; - } - - private static ResourceType getResource(String resourceName, int size, MemoryUnit unit) { - final ResourceType resource = new ResourceType(); - resource.setName(resourceName); - resource.setUnit(unit); - resource.setValue(BigInteger.valueOf((long)size)); - return resource; - } - /** * Adds a {@link PassthroughServer} if, and only if, a mapping for the URI supplied does not * already exist. The server is started as it is added. @@ -286,7 +268,7 @@ public static final class PassthroughServerBuilder { private final Map serviceProviders = new IdentityHashMap<>(); - private final OffheapResourcesType resources = new OffheapResourcesType(); + private final Map> resources = new HashMap<>(); public PassthroughServerBuilder resource(String resourceName, int size, org.ehcache.config.units.MemoryUnit unit) { return this.resource(resourceName, size, convert(unit)); @@ -299,7 +281,7 @@ private MemoryUnit convert(org.ehcache.config.units.MemoryUnit unit) { convertedUnit = MemoryUnit.B; break; case KB: - convertedUnit = MemoryUnit.K_B; + convertedUnit = MemoryUnit.KB; break; case MB: convertedUnit = MemoryUnit.MB; @@ -320,7 +302,7 @@ private MemoryUnit convert(org.ehcache.config.units.MemoryUnit unit) { } private PassthroughServerBuilder resource(String resourceName, int size, MemoryUnit unit) { - this.resources.getResource().add(getResource(resourceName, size, unit)); + this.resources.put(resourceName, Measure.of(size, unit)); return this; } diff --git a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/loaderwriter/ClusteredLoaderWriterStoreTest.java b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/loaderwriter/ClusteredLoaderWriterStoreTest.java index b7ee9e0c2d..60a7e73328 100644 --- a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/loaderwriter/ClusteredLoaderWriterStoreTest.java +++ b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/loaderwriter/ClusteredLoaderWriterStoreTest.java @@ -48,7 +48,7 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class ClusteredLoaderWriterStoreTest { @@ -117,8 +117,7 @@ public void testGetValuePresentInCache() throws Exception { ClusteredLoaderWriterStore store = new ClusteredLoaderWriterStore<>(configuration, codec, resolver, storeProxy, timeSource, loaderWriter, new DefaultStatisticsService()); assertThat(store.get(1L).get(), equalTo("one")); - verify(loaderWriter, times(0)).load(anyLong()); - verifyZeroInteractions(loaderWriter); + verifyNoInteractions(loaderWriter); } @Test diff --git a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/lock/VoltronReadWriteLockTest.java b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/lock/VoltronReadWriteLockTest.java index 41de1e0c4f..61eabefd8b 100644 --- a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/lock/VoltronReadWriteLockTest.java +++ b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/lock/VoltronReadWriteLockTest.java @@ -16,11 +16,11 @@ package org.ehcache.clustered.client.internal.lock; -import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; import org.terracotta.connection.Connection; import org.terracotta.connection.entity.EntityRef; @@ -32,10 +32,12 @@ import static org.mockito.ArgumentMatchers.isNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import org.terracotta.exception.EntityAlreadyExistsException; +@RunWith(MockitoJUnitRunner.class) public class VoltronReadWriteLockTest { @Mock @@ -47,11 +49,6 @@ public class VoltronReadWriteLockTest { @Mock private Connection connection; - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - @Test public void testCreateLockEntityWhenNotExisting() throws Exception { when(entityRef.fetchEntity(null)).thenReturn(client); @@ -66,7 +63,7 @@ public void testCreateLockEntityWhenNotExisting() throws Exception { @Test public void testFetchExistingLockEntityWhenExists() throws Exception { - doThrow(EntityAlreadyExistsException.class).when(entityRef).create(any(Void.class)); + doThrow(EntityAlreadyExistsException.class).when(entityRef).create(any()); when(entityRef.fetchEntity(null)).thenReturn(client); when(connection.getEntityRef(VoltronReadWriteLockClient.class, 1, "VoltronReadWriteLock-TestLock")).thenReturn(entityRef); diff --git a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/service/ClusterStateRepositoryReplicationTest.java b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/service/ClusterStateRepositoryReplicationTest.java index 86429fd73f..b832fba24e 100644 --- a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/service/ClusterStateRepositoryReplicationTest.java +++ b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/service/ClusterStateRepositoryReplicationTest.java @@ -36,8 +36,9 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.terracotta.common.struct.Measure; +import org.terracotta.common.struct.MemoryUnit; import org.terracotta.offheapresource.OffHeapResourcesProvider; -import org.terracotta.offheapresource.config.MemoryUnit; import org.terracotta.passthrough.PassthroughClusterControl; import org.terracotta.passthrough.PassthroughTestHelpers; @@ -45,8 +46,8 @@ import java.lang.reflect.Field; import java.net.URI; +import static java.util.Collections.singletonMap; import static org.ehcache.clustered.client.config.builders.ClusteredResourcePoolBuilder.clusteredDedicated; -import static org.ehcache.clustered.client.internal.UnitTestConnectionService.getOffheapResourcesType; import static org.ehcache.config.Eviction.noAdvice; import static org.ehcache.config.builders.ExpiryPolicyBuilder.noExpiration; import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; @@ -71,7 +72,7 @@ public void setUp() throws Exception { server.registerClientEntityService(new ClusterTierClientEntityService()); server.registerServerEntityService(new VoltronReadWriteLockServerEntityService()); server.registerClientEntityService(new VoltronReadWriteLockEntityClientService()); - server.registerExtendedConfiguration(new OffHeapResourcesProvider(getOffheapResourcesType("test", 32, MemoryUnit.MB))); + server.registerExtendedConfiguration(new OffHeapResourcesProvider(singletonMap("test", Measure.of(32, MemoryUnit.MB)))); UnitTestConnectionService.addServerToStripe(STRIPENAME, server); } diff --git a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/service/DefaultClusteringServiceDestroyTest.java b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/service/DefaultClusteringServiceDestroyTest.java index 157f7cbdb5..359c4e6dcf 100644 --- a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/service/DefaultClusteringServiceDestroyTest.java +++ b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/service/DefaultClusteringServiceDestroyTest.java @@ -26,8 +26,9 @@ import org.ehcache.spi.service.MaintainableService; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; import org.terracotta.connection.Connection; import org.terracotta.connection.entity.Entity; import org.terracotta.connection.entity.EntityRef; @@ -46,6 +47,7 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.same; import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -54,6 +56,7 @@ /** * DefaultClusteringServiceDestroyTest */ +@RunWith(MockitoJUnitRunner.class) public class DefaultClusteringServiceDestroyTest { @Mock @@ -67,7 +70,6 @@ public class DefaultClusteringServiceDestroyTest { @Before public void setUp() { - MockitoAnnotations.initMocks(this); MockConnectionService.mockConnection = connection; } @@ -167,7 +169,6 @@ public void testDestroyOnPartialDestroyState() throws Exception { when(getEntityRef(ClusterTierManagerClientEntity.class)).thenReturn(managerEntityRef); ClusterTierManagerClientEntity managerEntity = mock(ClusterTierManagerClientEntity.class); when(managerEntityRef.fetchEntity(null)).thenReturn(managerEntity); - doThrow(new DestroyInProgressException("destroying")).when(managerEntity).validate(any()); Set stores = new HashSet<>(); stores.add("store1"); @@ -194,7 +195,7 @@ private void mockLockForWriteLockSuccess() throws org.terracotta.exception.Entit VoltronReadWriteLockClient lockClient = mock(VoltronReadWriteLockClient.class); when(lockEntityRef.fetchEntity(null)).thenReturn(lockClient); - when(lockClient.tryLock(LockMessaging.HoldType.WRITE)).thenReturn(true); + lenient().when(lockClient.tryLock(LockMessaging.HoldType.WRITE)).thenReturn(true); } private void mockLockForReadLockSuccess() throws org.terracotta.exception.EntityNotProvidedException, org.terracotta.exception.EntityNotFoundException, org.terracotta.exception.EntityVersionMismatchException { @@ -202,7 +203,7 @@ private void mockLockForReadLockSuccess() throws org.terracotta.exception.Entity VoltronReadWriteLockClient lockClient = mock(VoltronReadWriteLockClient.class); when(lockEntityRef.fetchEntity(null)).thenReturn(lockClient); - when(lockClient.tryLock(LockMessaging.HoldType.READ)).thenReturn(true); + lenient().when(lockClient.tryLock(LockMessaging.HoldType.READ)).thenReturn(true); } private EntityRef getEntityRef(Class value) throws org.terracotta.exception.EntityNotProvidedException { diff --git a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/service/StateRepositoryWhitelistingTest.java b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/service/StateRepositoryWhitelistingTest.java index ffe57b376c..2cdbe7c180 100644 --- a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/service/StateRepositoryWhitelistingTest.java +++ b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/service/StateRepositoryWhitelistingTest.java @@ -35,8 +35,9 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.terracotta.common.struct.Measure; +import org.terracotta.common.struct.MemoryUnit; import org.terracotta.offheapresource.OffHeapResourcesProvider; -import org.terracotta.offheapresource.config.MemoryUnit; import org.terracotta.passthrough.PassthroughClusterControl; import org.terracotta.passthrough.PassthroughTestHelpers; @@ -44,9 +45,10 @@ import java.lang.reflect.Field; import java.net.URI; import java.util.Arrays; +import java.util.List; +import static java.util.Collections.singletonMap; import static org.ehcache.clustered.client.config.builders.ClusteredResourcePoolBuilder.clusteredDedicated; -import static org.ehcache.clustered.client.internal.UnitTestConnectionService.getOffheapResourcesType; import static org.ehcache.config.Eviction.noAdvice; import static org.ehcache.config.builders.ExpiryPolicyBuilder.noExpiration; import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; @@ -74,7 +76,7 @@ public void setUp() throws Exception { server.registerClientEntityService(new ClusterTierClientEntityService()); server.registerServerEntityService(new VoltronReadWriteLockServerEntityService()); server.registerClientEntityService(new VoltronReadWriteLockEntityClientService()); - server.registerExtendedConfiguration(new OffHeapResourcesProvider(getOffheapResourcesType("test", 32, MemoryUnit.MB))); + server.registerExtendedConfiguration(new OffHeapResourcesProvider(singletonMap("test", Measure.of(32, MemoryUnit.MB)))); UnitTestConnectionService.addServerToStripe(STRIPENAME, server); } @@ -160,11 +162,11 @@ public void testWhiteListedMissingClass() throws Exception { public void testWhitelistingForPrimitiveClass() throws Exception { // No whitelisting for primitive classes are required as we do not deserialize them at client side StateHolder testMap = stateRepository.getPersistentStateHolder("testMap", Integer.class, Integer.class, - Arrays.asList(Child.class)::contains, null); + List.of(Child.class)::contains, null); - testMap.putIfAbsent(new Integer(10), new Integer(20)); + testMap.putIfAbsent(10, 20); - assertThat(testMap.get(new Integer(10)), is(new Integer(20))); + assertThat(testMap.get(10), is(20)); assertThat(testMap.entrySet(), hasSize(1)); } diff --git a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java index 0ce631c4a9..836477bb49 100644 --- a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java +++ b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/store/ClusteredStoreTest.java @@ -230,7 +230,7 @@ public void testGetThrowsOnlySAE() throws Exception { @SuppressWarnings("unchecked") public void testGetTimeout() throws Exception { ServerStoreProxy proxy = mock(ServerStoreProxy.class); - long longKey = HashUtils.intHashToLong(new Long(1L).hashCode()); + long longKey = HashUtils.intHashToLong(Long.valueOf(1L).hashCode()); when(proxy.get(longKey)).thenThrow(TimeoutException.class); ClusteredStore store = new ClusteredStore<>(config,null, null, proxy, null, null, new DefaultStatisticsService()); assertThat(store.get(1L), nullValue()); diff --git a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/store/lock/LockRetentionDuringFailoverTest.java b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/store/lock/LockRetentionDuringFailoverTest.java index c443c8776f..feab6488fa 100644 --- a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/store/lock/LockRetentionDuringFailoverTest.java +++ b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/internal/store/lock/LockRetentionDuringFailoverTest.java @@ -31,8 +31,9 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.terracotta.common.struct.Measure; +import org.terracotta.common.struct.MemoryUnit; import org.terracotta.offheapresource.OffHeapResourcesProvider; -import org.terracotta.offheapresource.config.MemoryUnit; import org.terracotta.passthrough.PassthroughClusterControl; import org.terracotta.passthrough.PassthroughTestHelpers; @@ -43,9 +44,9 @@ import java.util.concurrent.Executors; import java.util.concurrent.Future; +import static java.util.Collections.singletonMap; import static org.ehcache.clustered.client.config.builders.ClusteredResourcePoolBuilder.clusteredDedicated; import static org.ehcache.clustered.client.config.builders.ClusteringServiceConfigurationBuilder.cluster; -import static org.ehcache.clustered.client.internal.UnitTestConnectionService.getOffheapResourcesType; import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; @@ -72,7 +73,7 @@ public void setUp() throws Exception { server.registerClientEntityService(new ClusterTierClientEntityService()); server.registerServerEntityService(new VoltronReadWriteLockServerEntityService()); server.registerClientEntityService(new VoltronReadWriteLockEntityClientService()); - server.registerExtendedConfiguration(new OffHeapResourcesProvider(getOffheapResourcesType("test", 32, MemoryUnit.MB))); + server.registerExtendedConfiguration(new OffHeapResourcesProvider(singletonMap("test", Measure.of(32, MemoryUnit.MB)))); UnitTestConnectionService.addServerToStripe(STRIPENAME, server); } diff --git a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/replication/ActivePassiveClientIdTest.java b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/replication/ActivePassiveClientIdTest.java index 4094626ddd..dd3c69c89d 100644 --- a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/replication/ActivePassiveClientIdTest.java +++ b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/client/replication/ActivePassiveClientIdTest.java @@ -39,8 +39,9 @@ import org.junit.Before; import org.junit.Test; import org.terracotta.client.message.tracker.OOOMessageHandler; +import org.terracotta.common.struct.Measure; +import org.terracotta.common.struct.MemoryUnit; import org.terracotta.offheapresource.OffHeapResourcesProvider; -import org.terracotta.offheapresource.config.MemoryUnit; import org.terracotta.passthrough.PassthroughClusterControl; import org.terracotta.passthrough.PassthroughTestHelpers; @@ -49,12 +50,12 @@ import java.util.function.Predicate; import java.util.stream.Collectors; +import static java.util.Collections.singletonMap; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import static org.ehcache.clustered.ChainUtils.chainOf; import static org.ehcache.clustered.ChainUtils.createPayload; import static org.ehcache.clustered.client.config.builders.ClusteredResourcePoolBuilder.clusteredDedicated; -import static org.ehcache.clustered.client.internal.UnitTestConnectionService.getOffheapResourcesType; import static org.ehcache.config.builders.ResourcePoolsBuilder.newResourcePoolsBuilder; import static org.mockito.Mockito.mock; @@ -91,7 +92,7 @@ public void setUp() throws Exception { server.registerClientEntityService(new ClusterTierClientEntityService()); server.registerServerEntityService(new VoltronReadWriteLockServerEntityService()); server.registerClientEntityService(new VoltronReadWriteLockEntityClientService()); - server.registerExtendedConfiguration(new OffHeapResourcesProvider(getOffheapResourcesType("test", 32, MemoryUnit.MB))); + server.registerExtendedConfiguration(new OffHeapResourcesProvider(singletonMap("test", Measure.of(32, MemoryUnit.MB)))); UnitTestConnectionService.addServerToStripe(STRIPENAME, server); } diff --git a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/common/internal/store/operations/ExpiryChainResolverTest.java b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/common/internal/store/operations/ExpiryChainResolverTest.java index e17bc673ef..ce60624f54 100644 --- a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/common/internal/store/operations/ExpiryChainResolverTest.java +++ b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/common/internal/store/operations/ExpiryChainResolverTest.java @@ -42,6 +42,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.RETURNS_SMART_NULLS; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; @@ -103,6 +104,8 @@ public void testGetExpiryForAccessIsIgnored() { ChainResolver chainResolver = createChainResolver(expiry); when(expiry.getExpiryForCreation(anyLong(), anyString())).thenReturn(ExpiryPolicy.INFINITE); + when(expiry.getExpiryForAccess(anyLong(), any())).thenReturn(null); + when(expiry.getExpiryForUpdate(anyLong(), any(), any())).thenReturn(null); ServerStoreProxy.ChainEntry chain = getEntryFromOperations( @@ -127,6 +130,8 @@ public void testGetExpiryForCreationIsInvokedOnlyOnce() { ChainResolver chainResolver = createChainResolver(expiry); when(expiry.getExpiryForCreation(anyLong(), anyString())).thenReturn(ExpiryPolicy.INFINITE); + when(expiry.getExpiryForAccess(anyLong(), any())).thenReturn(null); + when(expiry.getExpiryForUpdate(anyLong(), any(), any())).thenReturn(null); ServerStoreProxy.ChainEntry chain = getEntryFromOperations( new PutOperation<>(1L, "One", timeSource.getTimeMillis()), @@ -153,6 +158,8 @@ public void testGetExpiryForCreationIsNotInvokedForReplacedChains() { ChainResolver chainResolver = createChainResolver(expiry); when(expiry.getExpiryForCreation(anyLong(), anyString())).thenReturn(ExpiryPolicy.INFINITE); + when(expiry.getExpiryForAccess(anyLong(), any())).thenReturn(null); + when(expiry.getExpiryForUpdate(anyLong(), any(), any())).thenReturn(null); ServerStoreProxy.ChainEntry chain = getEntryFromOperations( @@ -172,21 +179,22 @@ public void testGetExpiryForCreationIsNotInvokedForReplacedChains() { @Test @SuppressWarnings("unchecked") public void testGetExpiryForCreationIsInvokedAfterRemoveOperations() { - TimeSource timeSource = new TestTimeSource(); ExpiryPolicy expiry = mock(ExpiryPolicy.class); ChainResolver chainResolver = createChainResolver(expiry); when(expiry.getExpiryForCreation(anyLong(), anyString())).thenReturn(ExpiryPolicy.INFINITE); + when(expiry.getExpiryForAccess(anyLong(), any())).thenReturn(null); + when(expiry.getExpiryForUpdate(anyLong(), any(), any())).thenReturn(null); ServerStoreProxy.ChainEntry chainA = getEntryFromOperations( - new PutOperation<>(1L, "Replaced", 10L), - new PutOperation<>(1L, "SecondAfterReplace", 3L), - new RemoveOperation<>(1L, 4L), - new PutOperation<>(1L, "FourthAfterReplace", 5L) + new PutOperation<>(1L, "Replaced", 1L), + new PutOperation<>(1L, "SecondAfterReplace", 2L), + new RemoveOperation<>(1L, 3L), + new PutOperation<>(1L, "FourthAfterReplace", 4L) ); - Store.ValueHolder valueHolder = chainResolver.resolve(chainA, 1L, timeSource.getTimeMillis()); + Store.ValueHolder valueHolder = chainResolver.resolve(chainA, 1L, 5L); InOrder inOrder = inOrder(expiry); @@ -196,29 +204,6 @@ public void testGetExpiryForCreationIsInvokedAfterRemoveOperations() { inOrder.verify(expiry, times(1)).getExpiryForCreation(anyLong(), anyString()); verify(chainA).replaceAtHead(any()); - - reset(expiry); - - when(expiry.getExpiryForCreation(anyLong(), anyString())).thenReturn(ExpiryPolicy.INFINITE); - - - ServerStoreProxy.ChainEntry chainB = getEntryFromOperations( - new PutOperation<>(1L, "One", timeSource.getTimeMillis()), - new PutOperation<>(1L, "Second", timeSource.getTimeMillis()), - new RemoveOperation<>(1L, timeSource.getTimeMillis()), - new PutOperation<>(1L, "Four", timeSource.getTimeMillis()) - ); - - chainResolver.resolve(chainB, 1L, timeSource.getTimeMillis()); - - inOrder = inOrder(expiry); - - verify(expiry, times(0)).getExpiryForAccess(anyLong(), any()); - inOrder.verify(expiry, times(1)).getExpiryForCreation(anyLong(), anyString()); - inOrder.verify(expiry, times(1)).getExpiryForUpdate(anyLong(), any(), anyString()); - inOrder.verify(expiry, times(1)).getExpiryForCreation(anyLong(), anyString()); - - verify(chainB).replaceAtHead(any()); } @Test @@ -229,6 +214,8 @@ public void testNullGetExpiryForCreation() { ChainResolver chainResolver = createChainResolver(expiry); when(expiry.getExpiryForCreation(anyLong(), anyString())).thenReturn(null); + when(expiry.getExpiryForAccess(anyLong(), any())).thenReturn(null); + when(expiry.getExpiryForUpdate(anyLong(), any(), any())).thenReturn(null); ServerStoreProxy.ChainEntry chain = getEntryFromOperations(new PutOperation<>(1L, "Replaced", 10L)); @@ -245,6 +232,8 @@ public void testNullGetExpiryForUpdate() { ExpiryPolicy expiry = mock(ExpiryPolicy.class); ChainResolver chainResolver = createChainResolver(expiry); + when(expiry.getExpiryForCreation(anyLong(), any())).thenReturn(null); + when(expiry.getExpiryForAccess(anyLong(), any())).thenReturn(null); when(expiry.getExpiryForUpdate(anyLong(), any(), anyString())).thenReturn(null); ServerStoreProxy.ChainEntry chain = getEntryFromOperations( @@ -266,6 +255,8 @@ public void testGetExpiryForUpdateUpdatesExpirationTimeStamp() { ExpiryPolicy expiry = mock(ExpiryPolicy.class); ChainResolver chainResolver = createChainResolver(expiry); + when(expiry.getExpiryForCreation(anyLong(), any())).thenReturn(null); + when(expiry.getExpiryForAccess(anyLong(), any())).thenReturn(null); when(expiry.getExpiryForUpdate(anyLong(), any(), anyString())).thenReturn(ofMillis(2L)); ServerStoreProxy.ChainEntry chain = getEntryFromOperations( @@ -288,6 +279,7 @@ public void testExpiryThrowsException() { when(expiry.getExpiryForUpdate(anyLong(), any(), anyString())).thenThrow(new RuntimeException("Test Update Expiry")); when(expiry.getExpiryForCreation(anyLong(), anyString())).thenThrow(new RuntimeException("Test Create Expiry")); + when(expiry.getExpiryForAccess(anyLong(), any())).thenReturn(null); ServerStoreProxy.ChainEntry chain = getEntryFromOperations( new PutOperation<>(1L, "One", -10L), diff --git a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/common/internal/store/operations/LazyValueHolderTest.java b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/common/internal/store/operations/LazyValueHolderTest.java index d9d0a9f163..2058d9c56a 100644 --- a/clustered/ehcache-client/src/test/java/org/ehcache/clustered/common/internal/store/operations/LazyValueHolderTest.java +++ b/clustered/ehcache-client/src/test/java/org/ehcache/clustered/common/internal/store/operations/LazyValueHolderTest.java @@ -17,10 +17,10 @@ package org.ehcache.clustered.common.internal.store.operations; import org.ehcache.spi.serialization.Serializer; -import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; import java.nio.ByteBuffer; import java.util.Date; @@ -33,16 +33,12 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; +@RunWith(MockitoJUnitRunner.class) public class LazyValueHolderTest { @Mock private Serializer serializer; - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - @Test public void testGetValueDecodeOnlyOnce() throws Exception { Date date = mock(Date.class); diff --git a/clustered/ehcache-clustered/build.gradle b/clustered/ehcache-clustered/build.gradle index 92ddb8616e..a2ee8a57b3 100644 --- a/clustered/ehcache-clustered/build.gradle +++ b/clustered/ehcache-clustered/build.gradle @@ -105,8 +105,8 @@ javadoc { tasks.named('jar') { osgi { instruction Constants.BUNDLE_SYMBOLICNAME, 'org.ehcache.clustered' - instruction Constants.EXPORT_PACKAGE, '!com.tc.*, !com.terracotta.*, !org.terracotta.*, !org.ehcache.*.internal.*, !sun.misc, org.ehcache.clustered.client.*, org.ehcache.clustered.common.*' - instruction Constants.IMPORT_PACKAGE, '!sun.misc.*, org.ehcache.xml.*;resolution:=optional, jdk.jfr.*;resolution:=optional, !com.fasterxml.jackson.*, !org.terracotta.json, javax.xml.bind*;version="[2.2,3)", *' + instruction Constants.EXPORT_PACKAGE, '!com.tc.*, !com.terracotta.*, !org.terracotta.*, !org.ehcache.*.internal.*, org.ehcache.clustered.client.*, org.ehcache.clustered.common.*' + instruction Constants.IMPORT_PACKAGE, 'jdk.internal.vm.annotation;resolution:=optional, org.ehcache.xml.*;resolution:=optional, jdk.jfr.*;resolution:=optional, !com.fasterxml.jackson.*, !org.terracotta.json, javax.xml.bind*;version="[2.2,3)", *' } } diff --git a/clustered/ehcache-common/src/test/java/org/ehcache/clustered/common/internal/Store/WhitelistedUnmarshallingTest.java b/clustered/ehcache-common/src/test/java/org/ehcache/clustered/common/internal/Store/WhitelistedUnmarshallingTest.java index cfad3d3a7e..8e994fb78d 100644 --- a/clustered/ehcache-common/src/test/java/org/ehcache/clustered/common/internal/Store/WhitelistedUnmarshallingTest.java +++ b/clustered/ehcache-common/src/test/java/org/ehcache/clustered/common/internal/Store/WhitelistedUnmarshallingTest.java @@ -61,48 +61,48 @@ private void unmarshallingStateRepoMessagesCheck(T t) { @Test public void unmarshallingIntegerTest() throws Exception { - unmarshallingStateRepoMessagesCheck(new Integer(10)); + unmarshallingStateRepoMessagesCheck(10); } @Test public void unmarshallingLongTest() throws Exception { - unmarshallingStateRepoMessagesCheck(new Long(10)); + unmarshallingStateRepoMessagesCheck(10L); } @Test public void unmarshallingFloatTest() throws Exception { - unmarshallingStateRepoMessagesCheck(new Float(10.0)); + unmarshallingStateRepoMessagesCheck(10.0F); } @Test public void unmarshallingDoubleTest() throws Exception { - unmarshallingStateRepoMessagesCheck(new Double(10.0)); + unmarshallingStateRepoMessagesCheck(10.0); } @Test public void unmarshallingByteTest() throws Exception { byte b = 101; - unmarshallingStateRepoMessagesCheck(new Byte(b)); + unmarshallingStateRepoMessagesCheck(b); } @Test public void unmarshallingCharacterTest() throws Exception { - unmarshallingStateRepoMessagesCheck(new Character('b')); + unmarshallingStateRepoMessagesCheck('b'); } @Test public void unmarshallingStringTest() throws Exception { - unmarshallingStateRepoMessagesCheck(new String("John")); + unmarshallingStateRepoMessagesCheck("John"); } @Test public void unmarshallingBooleanTest() throws Exception { - unmarshallingStateRepoMessagesCheck(new Boolean(true)); + unmarshallingStateRepoMessagesCheck(Boolean.TRUE); } @Test public void unmarshallingShortTest() throws Exception { - unmarshallingStateRepoMessagesCheck(new Short((short) 1)); + unmarshallingStateRepoMessagesCheck((short) 1); } @Test diff --git a/clustered/ehcache-common/src/test/java/org/ehcache/clustered/common/internal/messages/ChainCodecTest.java b/clustered/ehcache-common/src/test/java/org/ehcache/clustered/common/internal/messages/ChainCodecTest.java index 7fa0a7b0ba..13277f7fb3 100644 --- a/clustered/ehcache-common/src/test/java/org/ehcache/clustered/common/internal/messages/ChainCodecTest.java +++ b/clustered/ehcache-common/src/test/java/org/ehcache/clustered/common/internal/messages/ChainCodecTest.java @@ -21,7 +21,6 @@ import org.junit.Test; import org.terracotta.runnel.encoding.StructEncoder; -import java.nio.ByteBuffer; import java.util.AbstractMap.SimpleImmutableEntry; import java.util.Iterator; import java.util.Map; @@ -114,7 +113,7 @@ public void testChainEntryWithSingleElement() { StructEncoder encoder = ChainCodec.CHAIN_ENTRY_STRUCT.encoder(); ChainCodec.encodeChainEntry(encoder, entry); - Map.Entry decoded = ChainCodec.decodeChainEntry(ChainCodec.CHAIN_ENTRY_STRUCT.decoder((ByteBuffer) encoder.encode().flip())); + Map.Entry decoded = ChainCodec.decodeChainEntry(ChainCodec.CHAIN_ENTRY_STRUCT.decoder(encoder.encode().flip())); assertThat(decoded.getKey(), is(42L)); @@ -131,7 +130,7 @@ public void testChainEntryWithSingleSequencedElement() { StructEncoder encoder = ChainCodec.CHAIN_ENTRY_STRUCT.encoder(); ChainCodec.encodeChainEntry(encoder, entry); - Map.Entry decoded = ChainCodec.decodeChainEntry(ChainCodec.CHAIN_ENTRY_STRUCT.decoder((ByteBuffer) encoder.encode().flip())); + Map.Entry decoded = ChainCodec.decodeChainEntry(ChainCodec.CHAIN_ENTRY_STRUCT.decoder(encoder.encode().flip())); assertThat(decoded.getKey(), is(43L)); assertThat(decoded.getValue().isEmpty(), is(false)); @@ -149,7 +148,7 @@ public void testChainEntryWithMultipleElements() { StructEncoder encoder = ChainCodec.CHAIN_ENTRY_STRUCT.encoder(); ChainCodec.encodeChainEntry(encoder, entry); - Map.Entry decoded = ChainCodec.decodeChainEntry(ChainCodec.CHAIN_ENTRY_STRUCT.decoder((ByteBuffer) encoder.encode().flip())); + Map.Entry decoded = ChainCodec.decodeChainEntry(ChainCodec.CHAIN_ENTRY_STRUCT.decoder(encoder.encode().flip())); assertThat(decoded.getKey(), is(44L)); assertThat(decoded.getValue().isEmpty(), is(false)); @@ -163,7 +162,7 @@ public void testChainEntryWithMultipleSequencedElements() { StructEncoder encoder = ChainCodec.CHAIN_ENTRY_STRUCT.encoder(); ChainCodec.encodeChainEntry(encoder, entry); - Map.Entry decoded = ChainCodec.decodeChainEntry(ChainCodec.CHAIN_ENTRY_STRUCT.decoder((ByteBuffer) encoder.encode().flip())); + Map.Entry decoded = ChainCodec.decodeChainEntry(ChainCodec.CHAIN_ENTRY_STRUCT.decoder(encoder.encode().flip())); assertThat(decoded.getKey(), is(45L)); assertThat(decoded.getValue().isEmpty(), is(false)); @@ -179,7 +178,7 @@ public void testEmptyChainEntry() { StructEncoder encoder = ChainCodec.CHAIN_ENTRY_STRUCT.encoder(); ChainCodec.encodeChainEntry(encoder, entry); - Map.Entry decoded = ChainCodec.decodeChainEntry(ChainCodec.CHAIN_ENTRY_STRUCT.decoder((ByteBuffer) encoder.encode().flip())); + Map.Entry decoded = ChainCodec.decodeChainEntry(ChainCodec.CHAIN_ENTRY_STRUCT.decoder(encoder.encode().flip())); assertThat(decoded.getKey(), is(46L)); assertThat(decoded.getValue().isEmpty(), is(true)); diff --git a/clustered/ehcache-common/src/test/java/org/ehcache/clustered/common/internal/messages/EhcacheCodecTest.java b/clustered/ehcache-common/src/test/java/org/ehcache/clustered/common/internal/messages/EhcacheCodecTest.java index e4ed27154c..2b199ab295 100644 --- a/clustered/ehcache-common/src/test/java/org/ehcache/clustered/common/internal/messages/EhcacheCodecTest.java +++ b/clustered/ehcache-common/src/test/java/org/ehcache/clustered/common/internal/messages/EhcacheCodecTest.java @@ -18,7 +18,9 @@ import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; import java.nio.ByteBuffer; @@ -27,9 +29,9 @@ import static org.mockito.Mockito.only; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.MockitoAnnotations.initMocks; +import static org.mockito.Mockito.verifyNoInteractions; +@RunWith(MockitoJUnitRunner.class) public class EhcacheCodecTest { @Mock @@ -45,8 +47,6 @@ public class EhcacheCodecTest { @Before public void setUp() { - initMocks(this); - codec = new EhcacheCodec(serverStoreOpCodec, lifeCycleMessageCodec, stateRepositoryOpCodec, null); } @@ -79,7 +79,7 @@ public void decodeLifeCycleMessages() throws Exception { codec.decodeMessage(encodedBuffer.array()); } verify(lifeCycleMessageCodec, times(EhcacheMessageType.LIFECYCLE_MESSAGES.size())).decode(any(EhcacheMessageType.class), any(ByteBuffer.class)); - verifyZeroInteractions(serverStoreOpCodec, stateRepositoryOpCodec); + verifyNoInteractions(serverStoreOpCodec, stateRepositoryOpCodec); } @Test @@ -89,7 +89,7 @@ public void decodeServerStoreMessages() throws Exception { codec.decodeMessage(encodedBuffer.array()); } verify(serverStoreOpCodec, times(EhcacheMessageType.STORE_OPERATION_MESSAGES.size())).decode(any(EhcacheMessageType.class), any(ByteBuffer.class)); - verifyZeroInteractions(lifeCycleMessageCodec, stateRepositoryOpCodec); + verifyNoInteractions(lifeCycleMessageCodec, stateRepositoryOpCodec); } @Test @@ -99,7 +99,7 @@ public void decodeStateRepoMessages() throws Exception { codec.decodeMessage(encodedBuffer.array()); } verify(stateRepositoryOpCodec, times(EhcacheMessageType.STATE_REPO_OPERATION_MESSAGES.size())).decode(any(EhcacheMessageType.class), any(ByteBuffer.class)); - verifyZeroInteractions(lifeCycleMessageCodec, serverStoreOpCodec); + verifyNoInteractions(lifeCycleMessageCodec, serverStoreOpCodec); } } diff --git a/clustered/ehcache-common/src/test/java/org/ehcache/clustered/common/internal/messages/ResponseCodecTest.java b/clustered/ehcache-common/src/test/java/org/ehcache/clustered/common/internal/messages/ResponseCodecTest.java index 967a263def..deec5b89ca 100644 --- a/clustered/ehcache-common/src/test/java/org/ehcache/clustered/common/internal/messages/ResponseCodecTest.java +++ b/clustered/ehcache-common/src/test/java/org/ehcache/clustered/common/internal/messages/ResponseCodecTest.java @@ -75,7 +75,7 @@ public void testGetResponseCodec() { @Test public void testMapValueCodec() throws Exception { - Object subject = new Integer(10); + Object subject = 10; EhcacheEntityResponse mapValue = mapValue(subject); EhcacheEntityResponse.MapValue decoded = (EhcacheEntityResponse.MapValue) RESPONSE_CODEC.decode(RESPONSE_CODEC.encode(mapValue)); diff --git a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java index 91955e8130..6ad911cc89 100644 --- a/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java +++ b/clustered/integration-test/src/test/java/org/ehcache/clustered/management/ClusteringManagementServiceTest.java @@ -15,6 +15,7 @@ */ package org.ehcache.clustered.management; +import org.assertj.core.api.Assertions; import org.ehcache.Cache; import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; @@ -181,7 +182,7 @@ public void test_C_client_capabilities_exposed() throws Exception { allDescriptors.addAll(OFFHEAP_DESCRIPTORS); allDescriptors.addAll(CLUSTERED_DESCRIPTORS); - assertThat(descriptors).containsOnlyElementsOf(allDescriptors); + Assertions.assertThat(descriptors).containsOnlyElementsOf(allDescriptors); } @Test @@ -211,9 +212,9 @@ public void test_D_server_capabilities_exposed() throws Exception { // stats - assertThat(tierCapabilities[3].getDescriptors()).containsOnlyElementsOf(SERVER_STORE_DESCRIPTORS); - assertThat(managerCapabilities[2].getDescriptors()).containsOnlyElementsOf(POOL_DESCRIPTORS); - assertThat(tierCapabilities[1].getDescriptors()).containsOnlyElementsOf(POOL_DESCRIPTORS); + Assertions.assertThat(tierCapabilities[3].getDescriptors()).containsOnlyElementsOf(SERVER_STORE_DESCRIPTORS); + Assertions.assertThat(managerCapabilities[2].getDescriptors()).containsOnlyElementsOf(POOL_DESCRIPTORS); + Assertions.assertThat(tierCapabilities[1].getDescriptors()).containsOnlyElementsOf(POOL_DESCRIPTORS); // ClusterTierManagerSettings @@ -279,7 +280,7 @@ public void test_D_server_capabilities_exposed() throws Exception { assertThat(managerCapabilities[0].getDescriptors()).hasSize(3); // time + 2 resources - assertThat(managerCapabilities[1].getDescriptors()).containsOnlyElementsOf(OFFHEAP_RES_DESCRIPTORS); + Assertions.assertThat(managerCapabilities[1].getDescriptors()).containsOnlyElementsOf(OFFHEAP_RES_DESCRIPTORS); } @Test diff --git a/clustered/server/ehcache-entity/src/test/java/org/ehcache/clustered/server/internal/messages/EhcacheServerCodecTest.java b/clustered/server/ehcache-entity/src/test/java/org/ehcache/clustered/server/internal/messages/EhcacheServerCodecTest.java index 9f0bb360f5..d89ae98a50 100644 --- a/clustered/server/ehcache-entity/src/test/java/org/ehcache/clustered/server/internal/messages/EhcacheServerCodecTest.java +++ b/clustered/server/ehcache-entity/src/test/java/org/ehcache/clustered/server/internal/messages/EhcacheServerCodecTest.java @@ -23,19 +23,21 @@ import org.ehcache.clustered.server.internal.messages.PassiveReplicationMessage.InvalidationCompleteMessage; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; import java.nio.ByteBuffer; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; -import static org.mockito.MockitoAnnotations.initMocks; +import static org.mockito.Mockito.verifyNoInteractions; /** * EhcacheServerCodecTest */ +@RunWith(MockitoJUnitRunner.class) public class EhcacheServerCodecTest { @Mock @@ -48,7 +50,6 @@ public class EhcacheServerCodecTest { @Before public void setUp() { - initMocks(this); serverCodec = new EhcacheServerCodec(clientCodec, replicationCodec); } @@ -66,7 +67,7 @@ public EhcacheMessageType getMessageType() { serverCodec.encodeMessage(lifecycleMessage); verify(clientCodec).encodeMessage(any(EhcacheEntityMessage.class)); - verifyZeroInteractions(replicationCodec); + verifyNoInteractions(replicationCodec); } @Test @@ -75,7 +76,7 @@ public void testDelegatesToPassiveReplicationCodeForEncoding() throws Exception serverCodec.encodeMessage(message); verify(replicationCodec).encode(message); - verifyZeroInteractions(clientCodec); + verifyNoInteractions(clientCodec); } @Test @@ -85,7 +86,7 @@ public void decodeLifeCycleMessages() throws Exception { serverCodec.decodeMessage(encodedBuffer.array()); } verify(clientCodec, times(EhcacheMessageType.LIFECYCLE_MESSAGES.size())).decodeMessage(any(ByteBuffer.class), any(EhcacheMessageType.class)); - verifyZeroInteractions(replicationCodec); + verifyNoInteractions(replicationCodec); } @Test @@ -95,7 +96,7 @@ public void decodeServerStoreMessages() throws Exception { serverCodec.decodeMessage(encodedBuffer.array()); } verify(clientCodec, times(EhcacheMessageType.STORE_OPERATION_MESSAGES.size())).decodeMessage(any(ByteBuffer.class), any(EhcacheMessageType.class)); - verifyZeroInteractions(replicationCodec); + verifyNoInteractions(replicationCodec); } @Test @@ -105,7 +106,7 @@ public void decodeStateRepoMessages() throws Exception { serverCodec.decodeMessage(encodedBuffer.array()); } verify(clientCodec, times(EhcacheMessageType.STATE_REPO_OPERATION_MESSAGES.size())).decodeMessage(any(ByteBuffer.class), any(EhcacheMessageType.class)); - verifyZeroInteractions(replicationCodec); + verifyNoInteractions(replicationCodec); } @Test @@ -115,6 +116,6 @@ public void decodeClientIDTrackerMessages() throws Exception { serverCodec.decodeMessage(encodedBuffer.array()); } verify(replicationCodec, times(EhcacheMessageType.PASSIVE_REPLICATION_MESSAGES.size())).decode(any(EhcacheMessageType.class), any(ByteBuffer.class)); - verifyZeroInteractions(clientCodec); + verifyNoInteractions(clientCodec); } } diff --git a/clustered/server/ehcache-entity/src/test/java/org/ehcache/clustered/server/store/ClusterTierActiveEntityTest.java b/clustered/server/ehcache-entity/src/test/java/org/ehcache/clustered/server/store/ClusterTierActiveEntityTest.java index 12eb467c5e..012eccb3b6 100644 --- a/clustered/server/ehcache-entity/src/test/java/org/ehcache/clustered/server/store/ClusterTierActiveEntityTest.java +++ b/clustered/server/ehcache-entity/src/test/java/org/ehcache/clustered/server/store/ClusterTierActiveEntityTest.java @@ -120,7 +120,7 @@ import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; public class ClusterTierActiveEntityTest { @@ -859,7 +859,7 @@ public void testSyncToPassiveNoData() throws Exception { PassiveSynchronizationChannel syncChannel = mock(PassiveSynchronizationChannel.class); activeEntity.synchronizeKeyToPassive(syncChannel, 3); - verifyZeroInteractions(syncChannel); + verifyNoInteractions(syncChannel); } @Test diff --git a/clustered/server/ehcache-service/build.gradle b/clustered/server/ehcache-service/build.gradle index c26735f52f..39d61f7971 100644 --- a/clustered/server/ehcache-service/build.gradle +++ b/clustered/server/ehcache-service/build.gradle @@ -36,4 +36,6 @@ dependencies { testImplementation project(':clustered:test-utils') testImplementation "org.terracotta.management:monitoring-service-api:$terracottaPlatformVersion" testImplementation "org.terracotta:passthrough-server:$terracottaPassthroughTestingVersion" + + testCompileOnly 'javax.xml.bind:jaxb-api:[2,3)' } diff --git a/clustered/server/ehcache-service/src/main/java/org/ehcache/clustered/server/offheap/OffHeapChainStorageEngine.java b/clustered/server/ehcache-service/src/main/java/org/ehcache/clustered/server/offheap/OffHeapChainStorageEngine.java index a41e80afdf..2c1d2df4a8 100644 --- a/clustered/server/ehcache-service/src/main/java/org/ehcache/clustered/server/offheap/OffHeapChainStorageEngine.java +++ b/clustered/server/ehcache-service/src/main/java/org/ehcache/clustered/server/offheap/OffHeapChainStorageEngine.java @@ -214,7 +214,7 @@ public ByteBuffer readBinaryValue(long chain) { detachedContiguousBuffer.reset(); element = storage.readLong(element + ELEMENT_HEADER_NEXT_OFFSET); } while (element != chain); - return (ByteBuffer)detachedContiguousBuffer.flip(); + return detachedContiguousBuffer.flip(); } @Override @@ -697,7 +697,7 @@ private void append(long head, long tail) { } private Element element(ByteBuffer attachedBuffer, final long sequence) { - final ByteBuffer detachedBuffer = (ByteBuffer) ByteBuffer.allocate(attachedBuffer.remaining()).put(attachedBuffer).flip(); + final ByteBuffer detachedBuffer = ByteBuffer.allocate(attachedBuffer.remaining()).put(attachedBuffer).flip(); return new SequencedElement() { diff --git a/clustered/server/ehcache-service/src/test/java/org/ehcache/clustered/server/offheap/ChainMapExtensionTest.java b/clustered/server/ehcache-service/src/test/java/org/ehcache/clustered/server/offheap/ChainMapExtensionTest.java index 8a79bd0daf..ce120a007f 100644 --- a/clustered/server/ehcache-service/src/test/java/org/ehcache/clustered/server/offheap/ChainMapExtensionTest.java +++ b/clustered/server/ehcache-service/src/test/java/org/ehcache/clustered/server/offheap/ChainMapExtensionTest.java @@ -143,7 +143,7 @@ private static ByteBuffer buffer(int i) { while (buffer.hasRemaining()) { buffer.put((byte) i); } - return (ByteBuffer) buffer.flip(); + return buffer.flip(); } private static Matcher element(int i) { diff --git a/clustered/server/ehcache-service/src/test/java/org/ehcache/clustered/server/offheap/ChainMapTest.java b/clustered/server/ehcache-service/src/test/java/org/ehcache/clustered/server/offheap/ChainMapTest.java index d3f95b0770..8ac1b7eb18 100644 --- a/clustered/server/ehcache-service/src/test/java/org/ehcache/clustered/server/offheap/ChainMapTest.java +++ b/clustered/server/ehcache-service/src/test/java/org/ehcache/clustered/server/offheap/ChainMapTest.java @@ -482,7 +482,7 @@ private static ByteBuffer buffer(int i) { while (buffer.hasRemaining()) { buffer.put((byte) i); } - return (ByteBuffer) buffer.flip(); + return buffer.flip(); } private static Matcher element(final int i) { diff --git a/clustered/server/ehcache-service/src/test/java/org/ehcache/clustered/server/state/EhcacheStateServiceProviderTest.java b/clustered/server/ehcache-service/src/test/java/org/ehcache/clustered/server/state/EhcacheStateServiceProviderTest.java index fc1e2881ad..2441c7d344 100644 --- a/clustered/server/ehcache-service/src/test/java/org/ehcache/clustered/server/state/EhcacheStateServiceProviderTest.java +++ b/clustered/server/ehcache-service/src/test/java/org/ehcache/clustered/server/state/EhcacheStateServiceProviderTest.java @@ -22,20 +22,18 @@ import org.ehcache.clustered.server.state.config.EhcacheStateServiceConfig; import org.junit.Before; import org.junit.Test; +import org.terracotta.common.struct.Measure; +import org.terracotta.common.struct.MemoryUnit; import org.terracotta.entity.PlatformConfiguration; import org.terracotta.entity.ServiceProviderCleanupException; import org.terracotta.entity.ServiceProviderConfiguration; import org.terracotta.offheapresource.OffHeapResources; import org.terracotta.offheapresource.OffHeapResourcesProvider; -import org.terracotta.offheapresource.config.MemoryUnit; -import org.terracotta.offheapresource.config.OffheapResourcesType; -import org.terracotta.offheapresource.config.ResourceType; -import java.math.BigInteger; -import java.util.Collection; import java.util.Collections; import static java.util.Collections.emptyMap; +import static java.util.Collections.singletonMap; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.not; import static org.hamcrest.Matchers.sameInstance; @@ -56,13 +54,7 @@ public class EhcacheStateServiceProviderTest { @Before public void setUp() { - ResourceType resource = new ResourceType(); - resource.setName("primary"); - resource.setUnit(MemoryUnit.MB); - resource.setValue(BigInteger.valueOf(4L)); - OffheapResourcesType configuration = new OffheapResourcesType(); - configuration.getResource().add(resource); - OffHeapResources offheapResources = new OffHeapResourcesProvider(configuration); + OffHeapResources offheapResources = new OffHeapResourcesProvider(singletonMap("primary", Measure.of(4, MemoryUnit.MB))); platformConfiguration = mock(PlatformConfiguration.class); when(platformConfiguration.getExtendedConfiguration(OffHeapResources.class)).thenReturn(Collections.singletonList(offheapResources)); diff --git a/ehcache-107/src/test/java/org/ehcache/ParsesConfigurationExtensionTest.java b/ehcache-107/src/test/java/org/ehcache/ParsesConfigurationExtensionTest.java index 26f774dff6..463015a6af 100644 --- a/ehcache-107/src/test/java/org/ehcache/ParsesConfigurationExtensionTest.java +++ b/ehcache-107/src/test/java/org/ehcache/ParsesConfigurationExtensionTest.java @@ -65,7 +65,7 @@ public void testConfigParse() throws ClassNotFoundException, SAXException, Insta @SuppressWarnings("rawtypes") @Test - public void testXmlExample() throws ClassNotFoundException, SAXException, InstantiationException, IOException, IllegalAccessException { + public void testXmlExample() throws ReflectiveOperationException { XmlConfiguration config = new XmlConfiguration(ParsesConfigurationExtensionTest.class.getResource("/ehcache-example.xml")); final DefaultJsr107Service jsr107Service = new DefaultJsr107Service(ServiceUtils.findSingletonAmongst(Jsr107Configuration.class, config.getServiceCreationConfigurations())); diff --git a/ehcache-107/src/test/java/org/ehcache/jsr107/LoadAtomicsWith107Test.java b/ehcache-107/src/test/java/org/ehcache/jsr107/LoadAtomicsWith107Test.java index 27043ea2af..e58ef7524d 100644 --- a/ehcache-107/src/test/java/org/ehcache/jsr107/LoadAtomicsWith107Test.java +++ b/ehcache-107/src/test/java/org/ehcache/jsr107/LoadAtomicsWith107Test.java @@ -20,13 +20,13 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; import javax.cache.Cache; import javax.cache.CacheManager; import javax.cache.Caching; -import javax.cache.configuration.Factory; import javax.cache.configuration.MutableConfiguration; import javax.cache.integration.CacheLoader; import javax.cache.integration.CacheWriter; @@ -35,13 +35,13 @@ import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; /** * LoadAtomicsWith107Test */ +@RunWith(MockitoJUnitRunner.class) public class LoadAtomicsWith107Test { @Mock private CacheLoader cacheLoader; @@ -52,8 +52,6 @@ public class LoadAtomicsWith107Test { @Before public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - CachingProvider provider = Caching.getCachingProvider(); cacheManager = provider.getCacheManager(this.getClass().getResource("/ehcache-loader-writer-107-load-atomics.xml").toURI(), getClass().getClassLoader()); diff --git a/ehcache-107/src/test/java/org/ehcache/jsr107/LoaderWriterConfigTest.java b/ehcache-107/src/test/java/org/ehcache/jsr107/LoaderWriterConfigTest.java index 09671166af..65b90508d7 100644 --- a/ehcache-107/src/test/java/org/ehcache/jsr107/LoaderWriterConfigTest.java +++ b/ehcache-107/src/test/java/org/ehcache/jsr107/LoaderWriterConfigTest.java @@ -19,14 +19,14 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; import java.util.Set; import javax.cache.Cache; import javax.cache.Caching; -import javax.cache.configuration.Factory; import javax.cache.configuration.MutableConfiguration; import javax.cache.integration.CacheLoader; import javax.cache.integration.CacheWriter; @@ -34,14 +34,14 @@ import static java.util.Collections.singleton; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; /** * LoaderWriterConfigTest */ +@RunWith(MockitoJUnitRunner.class) public class LoaderWriterConfigTest { @Mock @@ -52,7 +52,6 @@ public class LoaderWriterConfigTest { @Before public void setUp() { - MockitoAnnotations.initMocks(this); cachingProvider = Caching.getCachingProvider(); } @@ -87,7 +86,7 @@ public void enablingReadThroughDoesNotForceWriteThrough() throws Exception { cache.get(100L); - verifyZeroInteractions(cacheWriter); + verifyNoInteractions(cacheWriter); verify(cacheLoader).load(100L); } diff --git a/ehcache-107/src/test/java/org/ehcache/jsr107/LoaderWriterTest.java b/ehcache-107/src/test/java/org/ehcache/jsr107/LoaderWriterTest.java index bd7265e365..6f54d6b1c0 100644 --- a/ehcache-107/src/test/java/org/ehcache/jsr107/LoaderWriterTest.java +++ b/ehcache-107/src/test/java/org/ehcache/jsr107/LoaderWriterTest.java @@ -20,16 +20,14 @@ import org.junit.After; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.mockito.invocation.InvocationOnMock; -import org.mockito.stubbing.Answer; +import org.mockito.junit.MockitoJUnitRunner; import javax.cache.Cache; import javax.cache.CacheManager; import javax.cache.Caching; -import javax.cache.configuration.Factory; import javax.cache.configuration.MutableConfiguration; import javax.cache.integration.CacheLoader; import javax.cache.integration.CacheWriter; @@ -40,12 +38,13 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; /** * @author Ludovic Orban */ +@RunWith(MockitoJUnitRunner.class) public class LoaderWriterTest { @Mock @@ -57,8 +56,6 @@ public class LoaderWriterTest { @Before public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - CachingProvider provider = Caching.getCachingProvider(); cacheManager = provider.getCacheManager(this.getClass().getResource("/ehcache-loader-writer-107.xml").toURI(), getClass().getClassLoader()); @@ -81,7 +78,7 @@ public void testSimplePutIfAbsentWithLoaderAndWriter_absent() throws Exception { assertThat(testCache.putIfAbsent(1, "one"), is(true)); assertThat(testCache.get(1), Matchers.equalTo("one")); - verifyZeroInteractions(cacheLoader); + verifyNoInteractions(cacheLoader); verify(cacheWriter, times(1)).write(eq(new Eh107CacheLoaderWriter.Entry(1, "one"))); } @@ -91,7 +88,7 @@ public void testSimplePutIfAbsentWithLoaderAndWriter_existsInSor() throws Except assertThat(testCache.putIfAbsent(1, "one"), is(true)); assertThat(testCache.get(1), Matchers.equalTo("one")); - verifyZeroInteractions(cacheLoader); + verifyNoInteractions(cacheLoader); verify(cacheWriter, times(1)).write(eq(new Eh107CacheLoaderWriter.Entry(1, "one"))); } @@ -103,33 +100,29 @@ public void testSimplePutIfAbsentWithLoaderAndWriter_existsInStore() throws Exce assertThat(testCache.putIfAbsent(1, "one"), is(false)); assertThat(testCache.get(1), Matchers.equalTo("un")); - verifyZeroInteractions(cacheLoader); - verifyZeroInteractions(cacheWriter); + verifyNoInteractions(cacheLoader); + verifyNoInteractions(cacheWriter); } @Test public void testSimpleReplace2ArgsWithLoaderAndWriter_absent() throws Exception { - when(cacheLoader.load(eq(1))).thenAnswer(invocation -> null); - assertThat(testCache.containsKey(1), is(false)); assertThat(testCache.replace(1, "one"), is(false)); assertThat(testCache.containsKey(1), is(false)); - verifyZeroInteractions(cacheLoader); - verifyZeroInteractions(cacheWriter); + verifyNoInteractions(cacheLoader); + verifyNoInteractions(cacheWriter); } @Test public void testSimpleReplace2ArgsWithLoaderAndWriter_existsInSor() throws Exception { - when(cacheLoader.load(eq(1))).thenAnswer(invocation -> "un"); - assertThat(testCache.containsKey(1), is(false)); assertThat(testCache.replace(1, "one"), is(false)); assertThat(testCache.containsKey(1), is(false)); - verifyZeroInteractions(cacheLoader); - verifyZeroInteractions(cacheWriter); + verifyNoInteractions(cacheLoader); + verifyNoInteractions(cacheWriter); } @Test @@ -140,31 +133,27 @@ public void testSimpleReplace2ArgsWithLoaderAndWriter_existsInStore() throws Exc assertThat(testCache.replace(1, "one"), is(true)); assertThat(testCache.get(1), Matchers.equalTo("one")); - verifyZeroInteractions(cacheLoader); + verifyNoInteractions(cacheLoader); verify(cacheWriter, times(1)).write(new Eh107CacheLoaderWriter.Entry(1, "one")); } @Test public void testSimpleReplace3ArgsWithLoaderAndWriter_absent() throws Exception { - when(cacheLoader.load(eq(1))).thenAnswer(invocation -> null); - assertThat(testCache.containsKey(1), is(false)); assertThat(testCache.replace(1, "un", "one"), is(false)); - verifyZeroInteractions(cacheLoader); - verifyZeroInteractions(cacheWriter); + verifyNoInteractions(cacheLoader); + verifyNoInteractions(cacheWriter); } @Test public void testSimpleReplace3ArgsWithLoaderAndWriter_existsInSor() throws Exception { - when(cacheLoader.load(eq(1))).thenAnswer(invocation -> "un"); - assertThat(testCache.containsKey(1), is(false)); assertThat(testCache.replace(1, "un", "one"), is(false)); assertThat(testCache.containsKey(1), is(false)); - verifyZeroInteractions(cacheLoader); - verifyZeroInteractions(cacheWriter); + verifyNoInteractions(cacheLoader); + verifyNoInteractions(cacheWriter); } @Test @@ -175,7 +164,7 @@ public void testSimpleReplace3ArgsWithLoaderAndWriter_existsInStore() throws Exc assertThat(testCache.replace(1, "un", "one"), is(true)); assertThat(testCache.get(1), Matchers.equalTo("one")); - verifyZeroInteractions(cacheLoader); + verifyNoInteractions(cacheLoader); verify(cacheWriter, times(1)).write(new Eh107CacheLoaderWriter.Entry(1, "one")); } @@ -187,30 +176,26 @@ public void testSimpleReplace3ArgsWithLoaderAndWriter_existsInStore_notEquals() assertThat(testCache.replace(1, "uno", "one"), is(false)); assertThat(testCache.get(1), Matchers.equalTo("un")); - verifyZeroInteractions(cacheLoader); - verifyZeroInteractions(cacheWriter); + verifyNoInteractions(cacheLoader); + verifyNoInteractions(cacheWriter); } @Test public void testSimpleRemove2ArgsWithLoaderAndWriter_absent() throws Exception { - when(cacheLoader.load(eq(1))).thenAnswer(invocation -> null); - assertThat(testCache.containsKey(1), is(false)); assertThat(testCache.remove(1, "one"), is(false)); - verifyZeroInteractions(cacheLoader); - verifyZeroInteractions(cacheWriter); + verifyNoInteractions(cacheLoader); + verifyNoInteractions(cacheWriter); } @Test public void testSimpleRemove2ArgsWithLoaderAndWriter_existsInSor() throws Exception { - when(cacheLoader.load(eq(1))).thenAnswer(invocation -> "un"); - assertThat(testCache.containsKey(1), is(false)); assertThat(testCache.remove(1, "un"), is(false)); - verifyZeroInteractions(cacheLoader); - verifyZeroInteractions(cacheWriter); + verifyNoInteractions(cacheLoader); + verifyNoInteractions(cacheWriter); } @Test @@ -220,7 +205,7 @@ public void testSimpleRemove2ArgsWithLoaderAndWriter_existsInStore() throws Exce assertThat(testCache.remove(1, "un"), is(true)); - verifyZeroInteractions(cacheLoader); + verifyNoInteractions(cacheLoader); verify(cacheWriter, times(1)).delete(eq(1)); } @@ -231,8 +216,8 @@ public void testSimpleRemove2ArgsWithLoaderAndWriter_existsInStore_notEquals() t assertThat(testCache.remove(1, "one"), is(false)); - verifyZeroInteractions(cacheLoader); - verifyZeroInteractions(cacheWriter); + verifyNoInteractions(cacheLoader); + verifyNoInteractions(cacheWriter); } private void reset(Object mock) { diff --git a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicClearTest.java b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicClearTest.java index 8b8e3579b6..a1556200ee 100644 --- a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicClearTest.java +++ b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicClearTest.java @@ -32,6 +32,7 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyZeroInteractions; /** @@ -50,7 +51,7 @@ public void testClearEmpty() throws Exception { final Ehcache ehcache = this.getEhcache(); ehcache.clear(); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); assertThat(realStore.getEntryMap().isEmpty(), is(true)); } @@ -81,7 +82,7 @@ public void testClearNonEmpty() throws Exception { assertThat(realStore.getEntryMap().isEmpty(), is(false)); ehcache.clear(); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); assertThat(realStore.getEntryMap().isEmpty(), is(true)); } diff --git a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicContainsKeyTest.java b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicContainsKeyTest.java index 75ec6225f4..750ba447ec 100644 --- a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicContainsKeyTest.java +++ b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicContainsKeyTest.java @@ -35,6 +35,7 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyZeroInteractions; /** @@ -58,7 +59,7 @@ public void testContainsKeyNull() throws Exception { } catch (NullPointerException e) { // Expected } - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); } /** @@ -71,7 +72,7 @@ public void testContainsKeyEmpty() throws Exception { final Ehcache ehcache = this.getEhcache(); assertFalse(ehcache.containsKey("key")); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); } /** @@ -101,7 +102,7 @@ public void testContainsKeyContains() throws Exception { final Ehcache ehcache = this.getEhcache(); assertTrue(ehcache.containsKey("keyA")); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); } /** @@ -131,7 +132,7 @@ public void testContainsKeyMissing() throws Exception { final Ehcache ehcache = this.getEhcache(); assertFalse(ehcache.containsKey("missingKey")); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); } /** diff --git a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java index ab019d6d1b..6e7694986e 100644 --- a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java +++ b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicCrudBase.java @@ -33,8 +33,10 @@ import org.hamcrest.Matcher; import org.hamcrest.TypeSafeMatcher; import org.junit.Before; +import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; import org.terracotta.context.ContextManager; import org.terracotta.context.TreeNode; import org.terracotta.statistics.OperationStatistic; @@ -67,6 +69,7 @@ * * @author Clifford W. Johnson */ +@RunWith(MockitoJUnitRunner.class) public abstract class EhcacheBasicCrudBase { protected static final CacheConfiguration CACHE_CONFIGURATION = new TestCacheConfig<>(String.class, String.class); @@ -78,11 +81,6 @@ public abstract class EhcacheBasicCrudBase { @Mock protected ResilienceStrategy resilienceStrategy; - @Before - public void initMocks() { - MockitoAnnotations.initMocks(this); - } - /** * Validates expected {@link org.terracotta.statistics.OperationStatistic} updates for the * indicated {@code InternalCache} instance. The statistics identified in {@code changed} are diff --git a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicGetAllTest.java b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicGetAllTest.java index 55df1a5c08..6d35325685 100644 --- a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicGetAllTest.java +++ b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicGetAllTest.java @@ -51,6 +51,7 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyZeroInteractions; /** @@ -135,7 +136,7 @@ public void testGetAllStoreNoMatchNoLoader() throws Exception { verify(this.store).bulkComputeIfAbsent(eq(KEY_SET_A), getAnyIterableFunction()); assertThat(fakeStore.getEntryMap(), equalTo(getEntryMap(KEY_SET_B))); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); validateStatsNoneof(ehcache); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.SUCCESS)); @@ -194,7 +195,7 @@ public void testGetAllStoreAllMatchNoLoader() throws Exception { verify(this.store).bulkComputeIfAbsent(eq(fetchKeys), getAnyIterableFunction()); assertThat(fakeStore.getEntryMap(), equalTo(getEntryMap(KEY_SET_A, KEY_SET_B))); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); validateStatsNoneof(ehcache); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.SUCCESS)); @@ -253,7 +254,7 @@ public void testGetAllStoreSomeMatchNoLoader() throws Exception { verify(this.store).bulkComputeIfAbsent(eq(fetchKeys), getAnyIterableFunction()); assertThat(fakeStore.getEntryMap(), equalTo(getEntryMap(KEY_SET_A, KEY_SET_B))); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); validateStatsNoneof(ehcache); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetAllOutcome.SUCCESS)); diff --git a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicGetTest.java b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicGetTest.java index e7bbfde935..e88309359a 100644 --- a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicGetTest.java +++ b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicGetTest.java @@ -35,6 +35,7 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyZeroInteractions; /** @@ -67,7 +68,7 @@ public void testGetNoStoreEntry() throws Exception { assertThat(ehcache.get("key"), is(nullValue())); verify(this.store).get(eq("key")); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetOutcome.MISS)); } @@ -108,7 +109,7 @@ public void testGetHasStoreEntry() throws Exception { assertThat(ehcache.get("key"), equalTo("value")); verify(this.store).get(eq("key")); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.GetOutcome.HIT)); } diff --git a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicIteratorTest.java b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicIteratorTest.java index 097ae95c6e..c6ce4892c8 100644 --- a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicIteratorTest.java +++ b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicIteratorTest.java @@ -222,7 +222,6 @@ public void testIteratorStoreAccessException() throws Exception { doReturn(storeEntry).when(storeIterator).next(); doReturn(storeIterator).when(this.store).iterator(); - doReturn(valueHolder).when(this.store).get(eq("foo")); final InternalCache ehcache = this.getEhcache(); final Iterator> iterator = ehcache.iterator(); diff --git a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicPutAllTest.java b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicPutAllTest.java index c0f49692c3..07dadda3a6 100644 --- a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicPutAllTest.java +++ b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicPutAllTest.java @@ -74,6 +74,7 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; @@ -208,7 +209,7 @@ public void testPutAllStoreSomeOverlapNoWriter() throws Exception { verify(this.store, atLeast(1)).bulkCompute(this.bulkComputeSetCaptor.capture(), getAnyEntryIterableFunction()); assertThat(this.getBulkComputeArgs(), equalTo(contentUpdates.keySet())); assertThat(fakeStore.getEntryMap(), equalTo(union(originalStoreContent, contentUpdates))); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.PutOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutAllOutcome.SUCCESS)); diff --git a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java index a22f3df49d..26149e8108 100644 --- a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java +++ b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicPutIfAbsentTest.java @@ -35,7 +35,7 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.verifyNoInteractions; /** * @author Abhilash @@ -94,7 +94,7 @@ public void testPutIfAbsentNoStoreEntry() throws Exception { assertThat(ehcache.putIfAbsent("key", "value"), is(nullValue())); verify(this.store).putIfAbsent(eq("key"), eq("value"), any()); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.PUT)); } @@ -114,7 +114,7 @@ public void testPutIfAbsentHasStoreEntry() throws Exception { assertThat(ehcache.putIfAbsent("key", "value"), is(equalTo("oldValue"))); verify(this.store).putIfAbsent(eq("key"), eq("value"), any()); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), equalTo("oldValue")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutIfAbsentOutcome.HIT)); } diff --git a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicPutTest.java b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicPutTest.java index 308f1f04e9..b2b708c240 100644 --- a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicPutTest.java +++ b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicPutTest.java @@ -34,8 +34,8 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; /** * @author Abhilash @@ -94,7 +94,7 @@ public void testPutNoStoreEntry() throws Exception { ehcache.put("key", "value"); verify(this.store).put(eq("key"), eq("value")); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutOutcome.PUT)); } @@ -135,7 +135,7 @@ public void testPutHasStoreEntry() throws Exception { ehcache.put("key", "value"); verify(this.store).put(eq("key"), eq("value")); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), equalTo("value")); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.PutOutcome.PUT)); } diff --git a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicRemoveAllTest.java b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicRemoveAllTest.java index 687d6862d3..e79b7bec68 100644 --- a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicRemoveAllTest.java +++ b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicRemoveAllTest.java @@ -69,6 +69,7 @@ import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; @@ -179,7 +180,7 @@ public void testRemoveAllStoreSomeOverlapNoWriter() throws Exception { verify(this.store, atLeast(1)).bulkCompute(this.bulkComputeSetCaptor.capture(), getAnyEntryIterableFunction()); assertThat(this.getBulkComputeArgs(), equalTo(contentUpdates)); assertThat(fakeStore.getEntryMap(), equalTo(copyWithout(originalStoreContent, contentUpdates))); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); validateStats(ehcache, EnumSet.noneOf(CacheOperationOutcomes.RemoveOutcome.class)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveAllOutcome.SUCCESS)); diff --git a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicRemoveTest.java b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicRemoveTest.java index 00fa591ada..fc164e35b4 100644 --- a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicRemoveTest.java +++ b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicRemoveTest.java @@ -33,6 +33,7 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyZeroInteractions; /** @@ -68,7 +69,7 @@ public void testRemoveNoStoreEntry() throws Exception { ehcache.remove("key"); verify(this.store).remove(eq("key")); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); assertThat(fakeStore.getEntryMap().containsKey("key"), is(false)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.NOOP)); } @@ -109,7 +110,7 @@ public void testRemoveHasStoreEntry() throws Exception { ehcache.remove("key"); verify(this.store).remove(eq("key")); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); assertThat(fakeStore.getEntryMap().containsKey("key"), is(false)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.RemoveOutcome.SUCCESS)); } diff --git a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicRemoveValueTest.java b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicRemoveValueTest.java index ca5d172e8f..76edd45662 100644 --- a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicRemoveValueTest.java +++ b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicRemoveValueTest.java @@ -36,6 +36,7 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyZeroInteractions; /** @@ -95,7 +96,7 @@ public void testRemoveValueNoStoreEntry() throws Exception { assertFalse(ehcache.remove("key", "value")); verify(this.store).remove(eq("key"), eq("value")); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); assertThat(fakeStore.getEntryMap().containsKey("key"), is(false)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.ConditionalRemoveOutcome.FAILURE_KEY_MISSING)); } @@ -115,7 +116,7 @@ public void testRemoveValueUnequalStoreEntry() throws Exception { assertFalse(ehcache.remove("key", "value")); verify(this.store).remove(eq("key"), eq("value")); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), is(equalTo("unequalValue"))); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.ConditionalRemoveOutcome.FAILURE_KEY_PRESENT)); } @@ -135,7 +136,7 @@ public void testRemoveValueEqualStoreEntry() throws Exception { assertTrue(ehcache.remove("key", "value")); verify(this.store).remove(eq("key"), eq("value")); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); assertThat(fakeStore.getEntryMap().containsKey("key"), is(false)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.ConditionalRemoveOutcome.SUCCESS)); } diff --git a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicReplaceTest.java b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicReplaceTest.java index f55a9482b7..24c38705f0 100644 --- a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicReplaceTest.java +++ b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicReplaceTest.java @@ -35,6 +35,7 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyZeroInteractions; /** @@ -94,7 +95,7 @@ public void testReplaceNoStoreEntry() throws Exception { assertNull(ehcache.replace("key", "value")); verify(this.store).replace(eq("key"), eq("value")); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); assertThat(fakeStore.getEntryMap().containsKey("key"), is(false)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.ReplaceOutcome.MISS_NOT_PRESENT)); } @@ -135,7 +136,7 @@ public void testReplaceHasStoreEntry() throws Exception { assertThat(ehcache.replace("key", "value"), is(equalTo("oldValue"))); verify(this.store).replace(eq("key"), eq("value")); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), is(equalTo("value"))); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.ReplaceOutcome.HIT)); } diff --git a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicReplaceValueTest.java b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicReplaceValueTest.java index 520d877310..8756d566c7 100644 --- a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicReplaceValueTest.java +++ b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBasicReplaceValueTest.java @@ -36,6 +36,7 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyZeroInteractions; /** @@ -144,7 +145,7 @@ public void testReplaceValueNoStoreEntry() throws Exception { assertFalse(ehcache.replace("key", "oldValue", "newValue")); verify(this.store).replace(eq("key"), eq("oldValue"), eq("newValue")); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); assertThat(fakeStore.getEntryMap().containsKey("key"), is(false)); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.ReplaceOutcome.MISS_NOT_PRESENT)); } @@ -164,7 +165,7 @@ public void testReplaceValueUnequalStoreEntry() throws Exception { assertFalse(ehcache.replace("key", "oldValue", "newValue")); verify(this.store).replace(eq("key"), eq("oldValue"), eq("newValue")); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), is(equalTo("unequalValue"))); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.ReplaceOutcome.MISS_PRESENT)); } @@ -184,7 +185,7 @@ public void testReplaceValueEqualStoreEntry() throws Exception { assertTrue(ehcache.replace("key", "oldValue", "newValue")); verify(this.store).replace(eq("key"), eq("oldValue"), eq("newValue")); - verifyZeroInteractions(this.resilienceStrategy); + verifyNoInteractions(this.resilienceStrategy); assertThat(fakeStore.getEntryMap().get("key"), is(equalTo("newValue"))); validateStats(ehcache, EnumSet.of(CacheOperationOutcomes.ReplaceOutcome.HIT)); } diff --git a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBulkMethodsTest.java b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBulkMethodsTest.java index 2e55654ab4..fc14fe52df 100644 --- a/ehcache-core/src/test/java/org/ehcache/core/EhcacheBulkMethodsTest.java +++ b/ehcache-core/src/test/java/org/ehcache/core/EhcacheBulkMethodsTest.java @@ -40,6 +40,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import static org.mockito.Mockito.withSettings; import static org.mockito.hamcrest.MockitoHamcrest.argThat; /** diff --git a/ehcache-impl/build.gradle b/ehcache-impl/build.gradle index 3d338a724a..7600243017 100644 --- a/ehcache-impl/build.gradle +++ b/ehcache-impl/build.gradle @@ -55,8 +55,8 @@ dependencies { implementation group: 'org.terracotta', name: 'terracotta-utilities-tools', version: parent.terracottaUtilitiesVersion compileOnly 'org.osgi:org.osgi.service.component.annotations:1.3.0' testImplementation project(':core-spi-test') - testImplementation 'org.ow2.asm:asm:6.2' - testImplementation 'org.ow2.asm:asm-commons:6.2' + testImplementation 'org.ow2.asm:asm:7.3.1' + testImplementation 'org.ow2.asm:asm-commons:7.3.1' testImplementation ("org.terracotta:statistics:$parent.statisticVersion") unsafeImplementation project(':ehcache-api') @@ -71,7 +71,7 @@ jar { bnd ( 'Export-Package': '!org.ehcache.impl.internal.*, org.ehcache.impl.*, org.ehcache.config.builders, ' + 'org.ehcache.impl.internal.spi.loaderwriter', //ugly 107 induced internal export wart - 'Import-Package': '!sun.misc, !javax.annotation, *', + 'Import-Package': 'jdk.internal.vm.annotation;resolution:=optional, !javax.annotation, *', ) } @@ -81,5 +81,5 @@ sourcesJar { compileUnsafeJava { //no -Werror due to unsafe - options.compilerArgs = ['-Xlint:all'] + options.compilerArgs = ['-Xlint:all', '--add-exports', 'java.base/jdk.internal.vm.annotation=ALL-UNNAMED'] } diff --git a/ehcache-impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/reflect/MemberUtils.java b/ehcache-impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/reflect/MemberUtils.java index 0849b9d234..f2d2e1b4d5 100644 --- a/ehcache-impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/reflect/MemberUtils.java +++ b/ehcache-impl/src/main/java/org/ehcache/impl/internal/classes/commonslang/reflect/MemberUtils.java @@ -58,6 +58,7 @@ abstract class MemberUtils { * @param o the AccessibleObject to set as accessible * @return a boolean indicating whether the accessibility of the object was set to true. */ + @SuppressWarnings("deprecation") static boolean setAccessibleWorkaround(final AccessibleObject o) { if (o == null || o.isAccessible()) { return false; diff --git a/ehcache-impl/src/main/java/org/ehcache/impl/serialization/PlainJavaSerializer.java b/ehcache-impl/src/main/java/org/ehcache/impl/serialization/PlainJavaSerializer.java index a48c066453..7a4d9db083 100644 --- a/ehcache-impl/src/main/java/org/ehcache/impl/serialization/PlainJavaSerializer.java +++ b/ehcache-impl/src/main/java/org/ehcache/impl/serialization/PlainJavaSerializer.java @@ -100,6 +100,7 @@ protected Class resolveClass(ObjectStreamClass desc) throws ClassNotFoundExce } @Override + @SuppressWarnings("deprecation") protected Class resolveProxyClass(String[] interfaces) throws ClassNotFoundException { Class[] interfaceClasses = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { diff --git a/ehcache-impl/src/test/java/org/ehcache/config/builders/CacheConfigurationBuilderTest.java b/ehcache-impl/src/test/java/org/ehcache/config/builders/CacheConfigurationBuilderTest.java index 4eaa86f64b..02c6cd3a62 100644 --- a/ehcache-impl/src/test/java/org/ehcache/config/builders/CacheConfigurationBuilderTest.java +++ b/ehcache-impl/src/test/java/org/ehcache/config/builders/CacheConfigurationBuilderTest.java @@ -42,9 +42,12 @@ import org.ehcache.test.MockitoUtil; import org.hamcrest.Matcher; import org.hamcrest.Matchers; +import org.hamcrest.core.CombinableMatcher; import org.hamcrest.core.IsSame; import org.junit.Test; +import java.util.Collection; + import static java.util.function.UnaryOperator.identity; import static org.ehcache.config.builders.CacheConfigurationBuilder.newCacheConfigurationBuilder; import static org.ehcache.config.builders.ResourcePoolsBuilder.heap; @@ -379,8 +382,11 @@ public void testIncompatibleServiceRemovesExistingConfiguration() { CacheConfigurationBuilder newBuilder = oldBuilder.withService(newConfig); - assertThat(oldBuilder.build().getServiceConfigurations(), both(hasItem(sameInstance(oldConfig))).and(not(hasItem(sameInstance(newConfig))))); - assertThat(newBuilder.build().getServiceConfigurations(), both(hasItem(sameInstance(newConfig))).and(not(hasItem(sameInstance(oldConfig))))); + Matcher>> hasOldConfig = hasItem(sameInstance(oldConfig)); + Matcher>> hasNewConfig = hasItem(sameInstance(newConfig)); + + assertThat(oldBuilder.build().getServiceConfigurations(), both(hasOldConfig).and(not(hasNewConfig))); + assertThat(newBuilder.build().getServiceConfigurations(), both(hasNewConfig).and(not(hasOldConfig))); } @Test @@ -392,8 +398,11 @@ public void testCompatibleServiceJoinsExistingConfiguration() { CacheConfigurationBuilder newBuilder = oldBuilder.withService(newConfig); - assertThat(oldBuilder.build().getServiceConfigurations(), both(hasItem(sameInstance(oldConfig))).and(not(hasItem(sameInstance(newConfig))))); - assertThat(newBuilder.build().getServiceConfigurations(), both(hasItem(sameInstance(oldConfig))).and(hasItem(sameInstance(newConfig)))); + Matcher>> hasOldConfig = hasItem(sameInstance(oldConfig)); + Matcher>> hasNewConfig = hasItem(sameInstance(newConfig)); + + assertThat(oldBuilder.build().getServiceConfigurations(), both(hasOldConfig).and(not(hasNewConfig))); + assertThat(newBuilder.build().getServiceConfigurations(), both(hasOldConfig).and(hasNewConfig)); } @Test diff --git a/ehcache-impl/src/test/java/org/ehcache/docs/ConfigurationDerivation.java b/ehcache-impl/src/test/java/org/ehcache/docs/ConfigurationDerivation.java index 1e74b8bcdd..9e99a1dfcb 100644 --- a/ehcache-impl/src/test/java/org/ehcache/docs/ConfigurationDerivation.java +++ b/ehcache-impl/src/test/java/org/ehcache/docs/ConfigurationDerivation.java @@ -210,8 +210,7 @@ public OptimizedDateSerializer(ClassLoader classLoader) {} @Override public ByteBuffer serialize(Date object) throws SerializerException { - ByteBuffer buffer = ByteBuffer.allocate(8); - return (ByteBuffer) buffer.putLong(object.getTime()).flip(); + return ByteBuffer.allocate(8).putLong(object.getTime()).flip(); } @Override diff --git a/ehcache-impl/src/test/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategyTest.java b/ehcache-impl/src/test/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategyTest.java index e9505f007a..76380767fb 100644 --- a/ehcache-impl/src/test/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategyTest.java +++ b/ehcache-impl/src/test/java/org/ehcache/impl/internal/resilience/RobustLoaderWriterResilienceStrategyTest.java @@ -38,8 +38,6 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collector; import static java.util.Collections.singletonMap; import static java.util.function.Function.identity; @@ -49,8 +47,8 @@ import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; public class RobustLoaderWriterResilienceStrategyTest { @@ -109,7 +107,7 @@ public void containsKeyFailure() throws Exception { assertThat(strategy.containsKeyFailure(1, accessException)).isFalse(); verify(store).obliterate(1); - verifyZeroInteractions(loaderWriter); + verifyNoInteractions(loaderWriter); } @Test diff --git a/ehcache-impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStrategyTest.java b/ehcache-impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStrategyTest.java index a8fec575a1..7f61562daa 100644 --- a/ehcache-impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStrategyTest.java +++ b/ehcache-impl/src/test/java/org/ehcache/impl/internal/store/heap/OnHeapStrategyTest.java @@ -29,7 +29,7 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyZeroInteractions; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; /** @@ -114,7 +114,7 @@ public void setAccessTimeAndExpiryThenReturnMappingOutsideLock_nullExpiryForAcce assertThat(mapping.expiration).isNull(); assertThat(mapping.now).isEqualTo(timeSource.getTimeMillis()); - verifyZeroInteractions(store); + verifyNoInteractions(store); } @Test @@ -141,7 +141,7 @@ public void setAccessTimeAndExpiryThenReturnMappingOutsideLock_infiniteExpiryOnA assertThat(mapping.expiration).isEqualTo(ExpiryPolicy.INFINITE); assertThat(mapping.now).isEqualTo(timeSource.getTimeMillis()); - verifyZeroInteractions(store); + verifyNoInteractions(store); } @Test @@ -156,7 +156,7 @@ public void setAccessTimeAndExpiryThenReturnMappingOutsideLock_movingTime() { assertThat(mapping.expiration).isEqualTo(Duration.ofMillis(20)); assertThat(mapping.now).isEqualTo(timeSource.getTimeMillis()); - verifyZeroInteractions(store); + verifyNoInteractions(store); timeSource.advanceTime(30); @@ -165,6 +165,6 @@ public void setAccessTimeAndExpiryThenReturnMappingOutsideLock_movingTime() { assertThat(mapping.expiration).isEqualTo(Duration.ofMillis(20)); assertThat(mapping.now).isEqualTo(timeSource.getTimeMillis()); - verifyZeroInteractions(store); + verifyNoInteractions(store); } } diff --git a/ehcache-impl/src/test/java/org/ehcache/impl/internal/store/offheap/AssertingOffHeapValueHolder.java b/ehcache-impl/src/test/java/org/ehcache/impl/internal/store/offheap/AssertingOffHeapValueHolder.java index 35a9e6df03..5dd232268c 100644 --- a/ehcache-impl/src/test/java/org/ehcache/impl/internal/store/offheap/AssertingOffHeapValueHolder.java +++ b/ehcache-impl/src/test/java/org/ehcache/impl/internal/store/offheap/AssertingOffHeapValueHolder.java @@ -40,7 +40,7 @@ import static java.util.Arrays.stream; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.core.Is.is; -import static org.objectweb.asm.Opcodes.ASM6; +import static org.objectweb.asm.Opcodes.ASM7; import static org.objectweb.asm.Type.getObjectType; import static org.objectweb.asm.Type.getType; import static org.objectweb.asm.commons.Method.getMethod; @@ -135,11 +135,11 @@ private static boolean isLockedInFrame(StackTraceElement ste) { NavigableMap lockLevels = new TreeMap<>(); - reader.accept(new ClassVisitor(ASM6) { + reader.accept(new ClassVisitor(ASM7) { @Override public MethodVisitor visitMethod(int access, String name, String descriptor, String signature, String[] exceptions) { if (ste.getMethodName().equals(name)) { - return new InstructionAdapter(ASM6, new MethodVisitor(ASM6) {}) { + return new InstructionAdapter(ASM7, new MethodVisitor(ASM7) {}) { private final Map levels = new HashMap<>(); diff --git a/ehcache-impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreTest.java b/ehcache-impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreTest.java index 63b1601e33..8c47830893 100644 --- a/ehcache-impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreTest.java +++ b/ehcache-impl/src/test/java/org/ehcache/impl/internal/store/tiering/TieredStoreTest.java @@ -36,12 +36,12 @@ import org.ehcache.spi.service.Service; import org.ehcache.spi.service.ServiceProvider; import org.hamcrest.Matchers; -import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Answers; import org.mockito.ArgumentMatchers; import org.mockito.Mock; -import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; import org.mockito.stubbing.Answer; import java.util.AbstractMap; @@ -80,6 +80,7 @@ /** * Tests for {@link TieredStore}. */ +@RunWith(MockitoJUnitRunner.class) public class TieredStoreTest { @Mock @@ -91,11 +92,6 @@ public class TieredStoreTest { @Mock private AuthoritativeTier stringAuthoritativeTier; - @Before - public void setUp() throws Exception { - MockitoAnnotations.initMocks(this); - } - @Test @SuppressWarnings("unchecked") public void testGetHitsCachingTier() throws Exception { @@ -574,9 +570,6 @@ public void testReleaseStoreFlushes() throws Exception { when(resourcePools.getResourceTypeSet()) .thenReturn(new HashSet<>(Arrays.asList(ResourceType.Core.HEAP, ResourceType.Core.OFFHEAP))); - SizedResourcePool heapPool = mock(SizedResourcePool.class); - when(heapPool.getType()).thenReturn((ResourceType)ResourceType.Core.HEAP); - when(resourcePools.getPoolForResource(ResourceType.Core.HEAP)).thenReturn(heapPool); OnHeapStore.Provider onHeapStoreProvider = mock(OnHeapStore.Provider.class); Set> singleton = Collections.>singleton( ResourceType.Core.HEAP); when(onHeapStoreProvider.rankCachingTier(eq(singleton), any(Collection.class))).thenReturn(1); @@ -584,9 +577,6 @@ public void testReleaseStoreFlushes() throws Exception { ArgumentMatchers.any())) .thenReturn(stringCachingTier); - SizedResourcePool offHeapPool = mock(SizedResourcePool.class); - when(heapPool.getType()).thenReturn((ResourceType)ResourceType.Core.OFFHEAP); - when(resourcePools.getPoolForResource(ResourceType.Core.OFFHEAP)).thenReturn(offHeapPool); OffHeapStore.Provider offHeapStoreProvider = mock(OffHeapStore.Provider.class); when(offHeapStoreProvider.rankAuthority(eq(ResourceType.Core.OFFHEAP), any(Collection.class))).thenReturn(1); when(offHeapStoreProvider.createAuthoritativeTier( @@ -601,8 +591,6 @@ public void testReleaseStoreFlushes() throws Exception { Set cachingTiers = new HashSet<>(); cachingTiers.add(onHeapStoreProvider); ServiceProvider serviceProvider = mock(ServiceProvider.class); - when(serviceProvider.getService(OnHeapStore.Provider.class)).thenReturn(onHeapStoreProvider); - when(serviceProvider.getService(OffHeapStore.Provider.class)).thenReturn(offHeapStoreProvider); when(serviceProvider.getServicesOfType(AuthoritativeTier.Provider.class)).thenReturn(authorities); when(serviceProvider.getServicesOfType(CachingTier.Provider.class)).thenReturn(cachingTiers); when(serviceProvider.getService(StatisticsService.class)).thenReturn(new DefaultStatisticsService()); diff --git a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/AddedFieldTest.java b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/AddedFieldTest.java index 6fb918d639..a820c71d86 100644 --- a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/AddedFieldTest.java +++ b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/AddedFieldTest.java @@ -45,7 +45,7 @@ public void addingSerializableField() throws Exception { serializer.init(new TransientStateRepository()); ClassLoader loaderA = createClassNameRewritingLoader(A_write.class, IncompatibleSerializable_write.class, Serializable_write.class); - Serializable a = (Serializable) loaderA.loadClass(newClassName(A_write.class)).newInstance(); + Serializable a = (Serializable) loaderA.loadClass(newClassName(A_write.class)).getDeclaredConstructor().newInstance(); ByteBuffer encodedA = serializer.serialize(a); pushTccl(createClassNameRewritingLoader(A_read.class, IncompatibleSerializable_read.class)); @@ -63,7 +63,7 @@ public void addingExternalizableField() throws Exception { serializer.init(new TransientStateRepository()); ClassLoader loaderA = createClassNameRewritingLoader(B_write.class, Externalizable_write.class); - Serializable a = (Serializable) loaderA.loadClass(newClassName(B_write.class)).newInstance(); + Serializable a = (Serializable) loaderA.loadClass(newClassName(B_write.class)).getDeclaredConstructor().newInstance(); ByteBuffer encodedA = serializer.serialize(a); pushTccl(createClassNameRewritingLoader(B_read.class)); diff --git a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/AddedSuperClassTest.java b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/AddedSuperClassTest.java index 1ba7a7b713..ed17b1f975 100644 --- a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/AddedSuperClassTest.java +++ b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/AddedSuperClassTest.java @@ -39,7 +39,7 @@ public void testAddedSuperClass() throws Exception { serializer.init(new TransientStateRepository()); ClassLoader loaderA = createClassNameRewritingLoader(A_2.class, AddedSuperClass_Hidden.class); - Serializable a = (Serializable) loaderA.loadClass(newClassName(A_2.class)).newInstance(); + Serializable a = (Serializable) loaderA.loadClass(newClassName(A_2.class)).getDeclaredConstructor().newInstance(); ByteBuffer encodedA = serializer.serialize(a); pushTccl(createClassNameRewritingLoader(A_1.class)); @@ -56,7 +56,7 @@ public void testAddedSuperClassNotHidden() throws Exception { serializer.init(new TransientStateRepository()); ClassLoader loaderA = createClassNameRewritingLoader(A_2.class, AddedSuperClass_Hidden.class); - Serializable a = (Serializable) loaderA.loadClass(newClassName(A_2.class)).newInstance(); + Serializable a = (Serializable) loaderA.loadClass(newClassName(A_2.class)).getDeclaredConstructor().newInstance(); ByteBuffer encodedA = serializer.serialize(a); pushTccl(createClassNameRewritingLoader(A_1.class, AddedSuperClass_Hidden.class)); diff --git a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/CompactJavaSerializerClassLoaderTest.java b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/CompactJavaSerializerClassLoaderTest.java index 1cb4e49f0c..bf462dd516 100644 --- a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/CompactJavaSerializerClassLoaderTest.java +++ b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/CompactJavaSerializerClassLoaderTest.java @@ -40,7 +40,7 @@ public void testThreadContextLoader() throws Exception { serializer.init(new TransientStateRepository()); ClassLoader loader = newLoader(); - ByteBuffer encoded = serializer.serialize((Serializable) loader.loadClass(Foo.class.getName()).newInstance()); + ByteBuffer encoded = serializer.serialize((Serializable) loader.loadClass(Foo.class.getName()).getDeclaredConstructor().newInstance()); pushTccl(loader); try { @@ -56,7 +56,7 @@ public void testExplicitLoader() throws Exception { StatefulSerializer serializer = new CompactJavaSerializer<>(loader); serializer.init(new TransientStateRepository()); - ByteBuffer encoded = serializer.serialize((Serializable) loader.loadClass(Foo.class.getName()).newInstance()); + ByteBuffer encoded = serializer.serialize((Serializable) loader.loadClass(Foo.class.getName()).getDeclaredConstructor().newInstance()); // setting TCCL doesn't matter here, but set it to make sure it doesn't get used pushTccl(newLoader()); diff --git a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/CompactJavaSerializerClassUnloadingTest.java b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/CompactJavaSerializerClassUnloadingTest.java index 7264824edc..289cf5a84f 100644 --- a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/CompactJavaSerializerClassUnloadingTest.java +++ b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/CompactJavaSerializerClassUnloadingTest.java @@ -47,7 +47,7 @@ public void createSpecialObject() throws Exception { Class special = (Class) duplicate.loadClass(SpecialClass.class.getName()); classRef = new WeakReference<>(special); - specialObject = special.newInstance(); + specialObject = special.getDeclaredConstructor().newInstance(); } @Test diff --git a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/EnumTest.java b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/EnumTest.java index e2d0b90255..3157949ad8 100644 --- a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/EnumTest.java +++ b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/EnumTest.java @@ -79,9 +79,12 @@ public void shiftingInstanceSerialization() throws ClassNotFoundException { } } - public static enum Foo_W { a, b, c { int i = 5; }, d { float f = 5.0f; } } - public static enum Foo_R { a, b { byte b = 3; }, c, d { double d = 6.0; } } + + } +enum Foo_W { a, b, c { int i = 5; }, d { float f = 5.0f; } } +enum Foo_R { a, b { byte b = 3; }, c, d { double d = 6.0; } } + enum People { Alice, Bob, Eve } enum Dogs { Handel, Cassie { int i = 0; }, Penny { double d = 3.0; } } diff --git a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/GetFieldTest.java b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/GetFieldTest.java index edd6bb1a71..1ead5cf991 100644 --- a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/GetFieldTest.java +++ b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/GetFieldTest.java @@ -42,7 +42,7 @@ public void testGetField() throws Exception { s.init(new TransientStateRepository()); ClassLoader loaderA = createClassNameRewritingLoader(Foo_A.class); - Serializable a = (Serializable) loaderA.loadClass(newClassName(Foo_A.class)).newInstance(); + Serializable a = (Serializable) loaderA.loadClass(newClassName(Foo_A.class)).getDeclaredConstructor().newInstance(); ByteBuffer encodedA = s.serialize(a); pushTccl(createClassNameRewritingLoader(Foo_B.class)); diff --git a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/JavaSerializer.java b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/JavaSerializer.java index ebff194cdb..0102cc615d 100644 --- a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/JavaSerializer.java +++ b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/JavaSerializer.java @@ -106,7 +106,7 @@ protected Class resolveClass(ObjectStreamClass desc) throws IOException, Clas } } - @Override + @Override @SuppressWarnings("deprecation") protected Class resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { Class[] interfaceClasses = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { diff --git a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/PutFieldTest.java b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/PutFieldTest.java index 0cb58e4e6c..11d7b18df0 100644 --- a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/PutFieldTest.java +++ b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/PutFieldTest.java @@ -43,7 +43,7 @@ public void testWithAllPrimitivesAndString() throws Exception { s.init(new TransientStateRepository()); ClassLoader loaderA = createClassNameRewritingLoader(Foo_A.class); - Serializable a = (Serializable) loaderA.loadClass(newClassName(Foo_A.class)).newInstance(); + Serializable a = (Serializable) loaderA.loadClass(newClassName(Foo_A.class)).getDeclaredConstructor().newInstance(); ByteBuffer encodedA = s.serialize(a); pushTccl(Foo.class.getClassLoader()); @@ -70,7 +70,7 @@ public void testWithTwoStrings() throws Exception { s.init(new TransientStateRepository()); ClassLoader loaderA = createClassNameRewritingLoader(Bar_A.class); - Serializable a = (Serializable) loaderA.loadClass(newClassName(Bar_A.class)).newInstance(); + Serializable a = (Serializable) loaderA.loadClass(newClassName(Bar_A.class)).getDeclaredConstructor().newInstance(); ByteBuffer encodedA = s.serialize(a); pushTccl(Bar.class.getClassLoader()); diff --git a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/ReadObjectNoDataTest.java b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/ReadObjectNoDataTest.java index 32a9e5163d..a49640c417 100644 --- a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/ReadObjectNoDataTest.java +++ b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/ReadObjectNoDataTest.java @@ -42,7 +42,7 @@ public void test() throws Exception { ClassLoader loaderW = createClassNameRewritingLoader(C_W.class, B_W.class); - ByteBuffer b = s.serialize((Serializable) loaderW.loadClass(newClassName(C_W.class)).newInstance()); + ByteBuffer b = s.serialize((Serializable) loaderW.loadClass(newClassName(C_W.class)).getDeclaredConstructor().newInstance()); pushTccl(createClassNameRewritingLoader(C_R.class, B_R.class, A_R.class)); try { diff --git a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/SerializeAfterEvolutionTest.java b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/SerializeAfterEvolutionTest.java index 33ca475626..1cddecd5d4 100644 --- a/ehcache-impl/src/test/java/org/ehcache/impl/serialization/SerializeAfterEvolutionTest.java +++ b/ehcache-impl/src/test/java/org/ehcache/impl/serialization/SerializeAfterEvolutionTest.java @@ -39,7 +39,7 @@ public void test() throws Exception { s.init(new TransientStateRepository()); ClassLoader loaderA = createClassNameRewritingLoader(A_old.class); - Serializable a = (Serializable) loaderA.loadClass(newClassName(A_old.class)).newInstance(); + Serializable a = (Serializable) loaderA.loadClass(newClassName(A_old.class)).getDeclaredConstructor().newInstance(); ByteBuffer encodedA = s.serialize(a); ClassLoader loaderB = createClassNameRewritingLoader(A_new.class); @@ -48,7 +48,7 @@ public void test() throws Exception { Serializable outA = s.read(encodedA); assertThat((Integer) outA.getClass().getField("integer").get(outA), Is.is(42)); - Serializable b = (Serializable) loaderB.loadClass(newClassName(A_new.class)).newInstance(); + Serializable b = (Serializable) loaderB.loadClass(newClassName(A_new.class)).getDeclaredConstructor().newInstance(); Serializable outB = s.read(s.serialize(b)); assertThat((Integer) outB.getClass().getField("integer").get(outB), Is.is(42)); } finally { diff --git a/ehcache-impl/src/unsafe/java/org/ehcache/impl/internal/concurrent/ConcurrentHashMap.java b/ehcache-impl/src/unsafe/java/org/ehcache/impl/internal/concurrent/ConcurrentHashMap.java index e113cd8ab6..80539fdff7 100644 --- a/ehcache-impl/src/unsafe/java/org/ehcache/impl/internal/concurrent/ConcurrentHashMap.java +++ b/ehcache-impl/src/unsafe/java/org/ehcache/impl/internal/concurrent/ConcurrentHashMap.java @@ -22,12 +22,12 @@ package org.ehcache.impl.internal.concurrent; -import sun.misc.Unsafe; - import org.ehcache.config.EvictionAdvisor; import java.io.ObjectStreamField; import java.io.Serializable; +import java.lang.invoke.MethodHandles; +import java.lang.invoke.VarHandle; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.AbstractMap; @@ -249,7 +249,7 @@ *

All arguments to all task methods must be non-null. * *

This class is a member of the - * + * * Java Collections Framework. *

* EHCACHE SPECIFIC @@ -257,16 +257,7 @@ * JSR 166 CSV repository revision 1.312. * Main modifications are tagged with "EHCACHE SPECIFIC" in the code. Global changes are: *

    - *
  • Unsafe is retrieved using {@link ThreadLocalRandomUtil#UNSAFE}
  • *
  • ThreadLocalRandom.getProbe is retrieved using {@link ThreadLocalRandomUtil#getProbe}
  • - *
  • getObjectAcquire is replaced by getObject for Java 8 compatibility
  • - *
  • compareAndSetObject is replaced by compareAndSwapObject for Java 8 compatibility
  • - *
  • compareAndSetInt is replaced by compareAndSwapInt for Java 8 compatibility
  • - *
  • compareAndSwapLong is replaced by compareAndSwapLong for Java 8 compatibility
  • - *
  • putObjectRelease is replaced by putObjectVolatile for Java 8 compatibility
  • - *
  • jdk.internal.misc.Unsafe is replaced by sun.misc.Unsafe for Java 8 compatibility
  • - *
  • jdk.internal.vm.annotation.Contended is replaced by sun.misc.Contended for Java 8 compatibility
  • - *
  • jdk.internal.vm.annotation.Contended is replaced by sun.misc.Contended for Java 8 compatibility
  • *
* END OF EHCACHE SPECIFIC * @@ -403,7 +394,7 @@ public class ConcurrentHashMap extends AbstractMap * cases where old nodes can be reused because their next fields * won't change. On average, only about one-sixth of them need * cloning when a table doubles. The nodes they replace will be - * garbage collectable as soon as they are no longer referenced by + * garbage collectible as soon as they are no longer referenced by * any reader thread that may be in the midst of concurrently * traversing table. Upon transfer, the old table bin contains * only a special forwarding node (with hash field "MOVED") that @@ -661,7 +652,7 @@ static class Node implements Map.Entry { public final V getValue() { return val; } public final int hashCode() { return key.hashCode() ^ val.hashCode(); } public final String toString() { - return ThreadLocalRandomUtil.mapEntryToString(key, val); // EHCACHE SPECIFIC: Code taken from java.util.concurrent.Helpers + return ThreadLocalRandomUtil.mapEntryToString(key, val); } public final V setValue(V value) { throw new UnsupportedOperationException(); @@ -712,14 +703,6 @@ Node find(int h, Object k) { * never be used in index calculations because of table bounds. */ static final int spread(int h) { - // EHCACHE SPECIFIC - // We modify the hash spread to help eviction sampling. Because, in a full hashmap, ordered numbers will be hashed as [ 1, 2, 3, e, e, e ] ('e' being empty) - // So everything is at the beginning of the map. Then, is the sampler starts randomly at index 2, it will find empty nodes all the - // way to the end and will then wrap at the beginning. Slow. To prevent that, we perform a rotate left which basically multiplies everything - // by two but also wraps the last bit. The spreading will then be [ 1, e, 2, e, 3, e ] which will be much nicer for sampling and only be a tiny tiny - // bit slower at access. - h = Integer.rotateLeft(h, 1); - // END OF EHCACHE SPECIFIC return (h ^ (h >>> 16)) & HASH_BITS; } @@ -781,18 +764,18 @@ static int compareComparables(Class kc, Object k, Object x) { * and so require only release ordering. */ - @SuppressWarnings("unchecked") + @SuppressWarnings({"unchecked", "cast"}) static final Node tabAt(Node[] tab, int i) { - return (Node)U.getObject(tab, ((long)i << ASHIFT) + ABASE); + return (Node) NODE_ARRAY.getAcquire(tab, i); } static final boolean casTabAt(Node[] tab, int i, Node c, Node v) { - return U.compareAndSwapObject(tab, ((long)i << ASHIFT) + ABASE, c, v); + return NODE_ARRAY.compareAndSet(tab, i, c, v); } static final void setTabAt(Node[] tab, int i, Node v) { - U.putObjectVolatile(tab, ((long)i << ASHIFT) + ABASE, v); + NODE_ARRAY.setRelease(tab, i, v); } /* ---------------- Fields -------------- */ @@ -1693,11 +1676,14 @@ boolean removeValueIf(Predicate function) { * If the specified key is not already associated with a value, * attempts to compute its value using the given mapping function * and enters it into this map unless {@code null}. The entire - * method invocation is performed atomically, so the function is - * applied at most once per key. Some attempted update operations - * on this map by other threads may be blocked while computation - * is in progress, so the computation should be short and simple, - * and must not attempt to update any other mappings of this map. + * method invocation is performed atomically. The supplied + * function is invoked exactly once per invocation of this method + * if the key is absent, else not at all. Some attempted update + * operations on this map by other threads may be blocked while + * computation is in progress, so the computation should be short + * and simple. + * + *

The mapping function must not modify this map during computation. * * @param key key with which the specified value is to be associated * @param mappingFunction the function to compute a value @@ -1804,10 +1790,13 @@ else if (f instanceof ReservationNode) * If the value for the specified key is present, attempts to * compute a new mapping given the key and its current mapped * value. The entire method invocation is performed atomically. - * Some attempted update operations on this map by other threads - * may be blocked while computation is in progress, so the - * computation should be short and simple, and must not attempt to - * update any other mappings of this map. + * The supplied function is invoked exactly once per invocation of + * this method if the key is present, else not at all. Some + * attempted update operations on this map by other threads may be + * blocked while computation is in progress, so the computation + * should be short and simple. + * + *

The remapping function must not modify this map during computation. * * @param key key with which a value may be associated * @param remappingFunction the function to compute a value @@ -1896,10 +1885,12 @@ else if (f instanceof ReservationNode) * Attempts to compute a mapping for the specified key and its * current mapped value (or {@code null} if there is no current * mapping). The entire method invocation is performed atomically. - * Some attempted update operations on this map by other threads - * may be blocked while computation is in progress, so the - * computation should be short and simple, and must not attempt to - * update any other mappings of this Map. + * The supplied function is invoked exactly once per invocation of + * this method. Some attempted update operations on this map by + * other threads may be blocked while computation is in progress, + * so the computation should be short and simple. + * + *

The remapping function must not modify this map during computation. * * @param key key with which the specified value is to be associated * @param remappingFunction the function to compute a value @@ -2311,7 +2302,7 @@ private final Node[] initTable() { while ((tab = table) == null || tab.length == 0) { if ((sc = sizeCtl) < 0) Thread.yield(); // lost initialization race; just spin - else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) { + else if (SIZECTL.compareAndSet(this, sc, -1)) { try { if ((tab = table) == null || tab.length == 0) { int n = (sc > 0) ? sc : DEFAULT_CAPACITY; @@ -2342,13 +2333,13 @@ else if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) { private final void addCount(long x, int check) { CounterCell[] cs; long b, s; if ((cs = counterCells) != null || - !U.compareAndSwapLong(this, BASECOUNT, b = baseCount, s = b + x)) { + !BASECOUNT.compareAndSet(this, b = baseCount, s = b + x)) { CounterCell c; long v; int m; boolean uncontended = true; if (cs == null || (m = cs.length - 1) < 0 || (c = cs[ThreadLocalRandomUtil.getProbe() & m]) == null || !(uncontended = - U.compareAndSwapLong(c, CELLVALUE, v = c.value, v + x))) { + CELLVALUE.compareAndSet(c, v = c.value, v + x))) { fullAddCount(x, uncontended); return; } @@ -2360,17 +2351,15 @@ private final void addCount(long x, int check) { Node[] tab, nt; int n, sc; while (s >= (long)(sc = sizeCtl) && (tab = table) != null && (n = tab.length) < MAXIMUM_CAPACITY) { - int rs = resizeStamp(n); + int rs = resizeStamp(n) << RESIZE_STAMP_SHIFT; if (sc < 0) { - if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 || - sc == rs + MAX_RESIZERS || (nt = nextTable) == null || - transferIndex <= 0) + if (sc == rs + MAX_RESIZERS || sc == rs + 1 || + (nt = nextTable) == null || transferIndex <= 0) break; - if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) + if (SIZECTL.compareAndSet(this, sc, sc + 1)) transfer(tab, nt); } - else if (U.compareAndSwapInt(this, SIZECTL, sc, - (rs << RESIZE_STAMP_SHIFT) + 2)) + else if (SIZECTL.compareAndSet(this, sc, rs + 2)) transfer(tab, null); s = sumCount(); } @@ -2384,13 +2373,13 @@ final Node[] helpTransfer(Node[] tab, Node f) { Node[] nextTab; int sc; if (tab != null && (f instanceof ForwardingNode) && (nextTab = ((ForwardingNode)f).nextTable) != null) { - int rs = resizeStamp(tab.length); + int rs = resizeStamp(tab.length) << RESIZE_STAMP_SHIFT; while (nextTab == nextTable && table == tab && (sc = sizeCtl) < 0) { - if ((sc >>> RESIZE_STAMP_SHIFT) != rs || sc == rs + 1 || - sc == rs + MAX_RESIZERS || transferIndex <= 0) + if (sc == rs + MAX_RESIZERS || sc == rs + 1 || + transferIndex <= 0) break; - if (U.compareAndSwapInt(this, SIZECTL, sc, sc + 1)) { + if (SIZECTL.compareAndSet(this, sc, sc + 1)) { transfer(tab, nextTab); break; } @@ -2413,7 +2402,7 @@ private final void tryPresize(int size) { Node[] tab = table; int n; if (tab == null || (n = tab.length) == 0) { n = (sc > c) ? sc : c; - if (U.compareAndSwapInt(this, SIZECTL, sc, -1)) { + if (SIZECTL.compareAndSet(this, sc, -1)) { try { if (table == tab) { @SuppressWarnings("unchecked") @@ -2430,8 +2419,7 @@ else if (c <= sc || n >= MAXIMUM_CAPACITY) break; else if (tab == table) { int rs = resizeStamp(n); - if (U.compareAndSwapInt(this, SIZECTL, sc, - (rs << RESIZE_STAMP_SHIFT) + 2)) + if (SIZECTL.compareAndSet(this, sc, (rs << RESIZE_STAMP_SHIFT) + 2)) transfer(tab, null); } } @@ -2471,8 +2459,7 @@ else if ((nextIndex = transferIndex) <= 0) { i = -1; advance = false; } - else if (U.compareAndSwapInt - (this, TRANSFERINDEX, nextIndex, + else if (TRANSFERINDEX.compareAndSet(this, nextIndex, nextBound = (nextIndex > stride ? nextIndex - stride : 0))) { bound = nextBound; @@ -2488,7 +2475,7 @@ else if (U.compareAndSwapInt sizeCtl = (n << 1) - (n >>> 1); return; } - if (U.compareAndSwapInt(this, SIZECTL, sc = sizeCtl, sc - 1)) { + if (SIZECTL.compareAndSet(this, sc = sizeCtl, sc - 1)) { if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT) return; finishing = advance = true; @@ -2568,6 +2555,8 @@ else if (f instanceof TreeBin) { setTabAt(tab, i, fwd); advance = true; } + else if (f instanceof ReservationNode) + throw new IllegalStateException("Recursive update"); } } } @@ -2580,8 +2569,7 @@ else if (f instanceof TreeBin) { * A padded cell for distributing counts. Adapted from LongAdder * and Striped64. See their internal docs for explanation. */ - @sun.misc.Contended - static final class CounterCell { + @jdk.internal.vm.annotation.Contended static final class CounterCell { volatile long value; CounterCell(long x) { value = x; } } @@ -2613,7 +2601,7 @@ private final void fullAddCount(long x, boolean wasUncontended) { if (cellsBusy == 0) { // Try to attach new Cell CounterCell r = new CounterCell(x); // Optimistic create if (cellsBusy == 0 && - U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) { + CELLSBUSY.compareAndSet(this, 0, 1)) { boolean created = false; try { // Recheck under lock CounterCell[] rs; int m, j; @@ -2635,14 +2623,14 @@ private final void fullAddCount(long x, boolean wasUncontended) { } else if (!wasUncontended) // CAS already known to fail wasUncontended = true; // Continue after rehash - else if (U.compareAndSwapLong(c, CELLVALUE, v = c.value, v + x)) + else if (CELLVALUE.compareAndSet(c, v = c.value, v + x)) break; else if (counterCells != cs || n >= NCPU) collide = false; // At max size or stale else if (!collide) collide = true; else if (cellsBusy == 0 && - U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) { + CELLSBUSY.compareAndSet(this, 0, 1)) { try { if (counterCells == cs) // Expand table unless stale counterCells = Arrays.copyOf(cs, n << 1); @@ -2655,7 +2643,7 @@ else if (cellsBusy == 0 && h = ThreadLocalRandomUtil.advanceProbe(h); } else if (cellsBusy == 0 && counterCells == cs && - U.compareAndSwapInt(this, CELLSBUSY, 0, 1)) { + CELLSBUSY.compareAndSet(this, 0, 1)) { boolean init = false; try { // Initialize table if (counterCells == cs) { @@ -2670,7 +2658,7 @@ else if (cellsBusy == 0 && counterCells == cs && if (init) break; } - else if (U.compareAndSwapLong(this, BASECOUNT, v = baseCount, v + x)) + else if (BASECOUNT.compareAndSet(this, v = baseCount, v + x)) break; // Fall back on using base } } @@ -2866,7 +2854,7 @@ else if ((kc == null && * Acquires write lock for tree restructuring. */ private final void lockRoot() { - if (!U.compareAndSwapInt(this, LOCKSTATE, 0, WRITER)) + if (!LOCKSTATE.compareAndSet(this, 0, WRITER)) contendedLock(); // offload to separate method } @@ -2884,14 +2872,14 @@ private final void contendedLock() { boolean waiting = false; for (int s;;) { if (((s = lockState) & ~WAITER) == 0) { - if (U.compareAndSwapInt(this, LOCKSTATE, s, WRITER)) { + if (LOCKSTATE.compareAndSet(this, s, WRITER)) { if (waiting) waiter = null; return; } } else if ((s & WAITER) == 0) { - if (U.compareAndSwapInt(this, LOCKSTATE, s, s | WAITER)) { + if (LOCKSTATE.compareAndSet(this, s, s | WAITER)) { waiting = true; waiter = Thread.currentThread(); } @@ -2916,7 +2904,7 @@ final Node find(int h, Object k) { return e; e = e.next; } - else if (U.compareAndSwapInt(this, LOCKSTATE, s, + else if (LOCKSTATE.compareAndSet(this, s, s + READER)) { TreeNode r, p; try { @@ -2924,7 +2912,7 @@ else if (U.compareAndSwapInt(this, LOCKSTATE, s, r.findTreeNode(h, k, null)); } finally { Thread w; - if (U.getAndAddInt(this, LOCKSTATE, -READER) == + if (((int) LOCKSTATE.getAndAdd(this, -READER)) == (READER|WAITER) && (w = waiter) != null) LockSupport.unpark(w); } @@ -3313,15 +3301,15 @@ static boolean checkInvariants(TreeNode t) { return true; } - private static final Unsafe U = ThreadLocalRandomUtil.UNSAFE; - private static final long LOCKSTATE; + private static final VarHandle LOCKSTATE; + static { - try { - LOCKSTATE = U.objectFieldOffset - (TreeBin.class.getDeclaredField("lockState")); - } catch (ReflectiveOperationException e) { - throw new ExceptionInInitializerError(e); - } + try { + MethodHandles.Lookup lookup = MethodHandles.lookup(); + LOCKSTATE = lookup.findVarHandle(TreeBin.class, "lockState", int.class); + } catch (ReflectiveOperationException e) { + throw new AssertionError(e); + } } } @@ -4619,6 +4607,7 @@ public final boolean retainAll(Collection c) { public static class KeySetView extends CollectionView implements Set, java.io.Serializable { private static final long serialVersionUID = 7249069246763182397L; + @SuppressWarnings("serial") // Conditionally serializable private final V value; KeySetView(ConcurrentHashMap map, V value) { // non-public super(map); @@ -6378,36 +6367,24 @@ public final void compute() { } // Unsafe mechanics - private static final Unsafe U = ThreadLocalRandomUtil.UNSAFE; - private static final long SIZECTL; - private static final long TRANSFERINDEX; - private static final long BASECOUNT; - private static final long CELLSBUSY; - private static final long CELLVALUE; - private static final int ABASE; - private static final int ASHIFT; + private static final VarHandle SIZECTL; + private static final VarHandle TRANSFERINDEX; + private static final VarHandle BASECOUNT; + private static final VarHandle CELLSBUSY; + private static final VarHandle CELLVALUE; + private static final VarHandle NODE_ARRAY; static { + MethodHandles.Lookup lookup = MethodHandles.lookup(); try { - SIZECTL = U.objectFieldOffset - (ConcurrentHashMap.class.getDeclaredField("sizeCtl")); - TRANSFERINDEX = U.objectFieldOffset - (ConcurrentHashMap.class.getDeclaredField("transferIndex")); - BASECOUNT = U.objectFieldOffset - (ConcurrentHashMap.class.getDeclaredField("baseCount")); - CELLSBUSY = U.objectFieldOffset - (ConcurrentHashMap.class.getDeclaredField("cellsBusy")); - - CELLVALUE = U.objectFieldOffset - (CounterCell.class.getDeclaredField("value")); - - ABASE = U.arrayBaseOffset(Node[].class); - int scale = U.arrayIndexScale(Node[].class); - if ((scale & (scale - 1)) != 0) - throw new ExceptionInInitializerError("array index scale not a power of two"); - ASHIFT = 31 - Integer.numberOfLeadingZeros(scale); + SIZECTL = lookup.findVarHandle(ConcurrentHashMap.class, "sizeCtl", int.class); + TRANSFERINDEX = lookup.findVarHandle(ConcurrentHashMap.class, "transferIndex", int.class); + BASECOUNT = lookup.findVarHandle(ConcurrentHashMap.class, "baseCount", long.class); + CELLSBUSY = lookup.findVarHandle(ConcurrentHashMap.class, "cellsBusy", int.class); + CELLVALUE = lookup.findVarHandle(CounterCell.class, "value", long.class); + NODE_ARRAY = MethodHandles.arrayElementVarHandle(Node[].class); } catch (ReflectiveOperationException e) { - throw new ExceptionInInitializerError(e); + throw new AssertionError(e); } // Reduce the risk of rare disastrous classloading in first call to @@ -6434,6 +6411,8 @@ private static int treeNodesAt(TreeNode root, Collection int nodesAt(Node b, Collection> nodes) { if (b instanceof TreeBin) { return treeNodesAt(((TreeBin)b).root, nodes); + } else if (b instanceof ReservationNode) { + throw new IllegalStateException("Recursive update"); } else { int count = 0; for (Node q = b; q != null; q = q.next) { diff --git a/ehcache-management/src/test/java/org/ehcache/management/registry/DefaultManagementRegistryServiceTest.java b/ehcache-management/src/test/java/org/ehcache/management/registry/DefaultManagementRegistryServiceTest.java index 9245abef53..3709734e41 100644 --- a/ehcache-management/src/test/java/org/ehcache/management/registry/DefaultManagementRegistryServiceTest.java +++ b/ehcache-management/src/test/java/org/ehcache/management/registry/DefaultManagementRegistryServiceTest.java @@ -23,6 +23,7 @@ import java.util.NoSuchElementException; import java.util.concurrent.ExecutionException; +import org.assertj.core.api.Assertions; import org.ehcache.Cache; import org.ehcache.CacheManager; import org.ehcache.PersistentCacheManager; @@ -119,7 +120,7 @@ public void descriptorOnHeapTest() { allDescriptors.addAll(ONHEAP_DESCRIPTORS); allDescriptors.addAll(CACHE_DESCRIPTORS); - assertThat(descriptors).containsOnlyElementsOf(allDescriptors); + Assertions.assertThat(descriptors).containsOnlyElementsOf(allDescriptors); } } @@ -149,7 +150,7 @@ public void descriptorOnHeapTest_withoutStats() { allDescriptors.addAll(ONHEAP_NO_STATS_DESCRIPTORS); allDescriptors.addAll(CACHE_DESCRIPTORS); - assertThat(descriptors).containsOnlyElementsOf(allDescriptors); + Assertions.assertThat(descriptors).containsOnlyElementsOf(allDescriptors); } } @@ -181,7 +182,7 @@ public void descriptorOffHeapTest() { allDescriptors.addAll(CACHE_DESCRIPTORS); allDescriptors.add(new StatisticDescriptor("OnHeap:OccupiedByteSize" , "GAUGE")); - assertThat(descriptors).containsOnlyElementsOf(allDescriptors); + Assertions.assertThat(descriptors).containsOnlyElementsOf(allDescriptors); } } @@ -215,7 +216,7 @@ public void descriptorDiskStoreTest() throws Exception { allDescriptors.addAll(DISK_DESCRIPTORS); allDescriptors.addAll(CACHE_DESCRIPTORS); - assertThat(descriptors).containsOnlyElementsOf(allDescriptors); + Assertions.assertThat(descriptors).containsOnlyElementsOf(allDescriptors); } } diff --git a/ehcache-transactions/src/main/java/org/ehcache/transactions/xa/internal/SoftLockSerializer.java b/ehcache-transactions/src/main/java/org/ehcache/transactions/xa/internal/SoftLockSerializer.java index 3064b950a2..11d1fba84e 100644 --- a/ehcache-transactions/src/main/java/org/ehcache/transactions/xa/internal/SoftLockSerializer.java +++ b/ehcache-transactions/src/main/java/org/ehcache/transactions/xa/internal/SoftLockSerializer.java @@ -109,7 +109,7 @@ protected Class resolveClass(ObjectStreamClass desc) throws ClassNotFoundExce } } - @Override + @Override @SuppressWarnings("deprecation") protected Class resolveProxyClass(String[] interfaces) throws ClassNotFoundException { Class[] interfaceClasses = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { diff --git a/ehcache-transactions/src/main/java/org/ehcache/transactions/xa/txmgr/provider/LookupTransactionManagerProvider.java b/ehcache-transactions/src/main/java/org/ehcache/transactions/xa/txmgr/provider/LookupTransactionManagerProvider.java index 7e89683bbe..8172be624e 100644 --- a/ehcache-transactions/src/main/java/org/ehcache/transactions/xa/txmgr/provider/LookupTransactionManagerProvider.java +++ b/ehcache-transactions/src/main/java/org/ehcache/transactions/xa/txmgr/provider/LookupTransactionManagerProvider.java @@ -53,8 +53,8 @@ public LookupTransactionManagerProvider(LookupTransactionManagerProviderConfigur throw new NullPointerException("LookupTransactionManagerProviderConfiguration cannot be null"); } try { - lookup = config.getTransactionManagerLookup().newInstance(); - } catch (InstantiationException | IllegalAccessException e) { + lookup = config.getTransactionManagerLookup().getDeclaredConstructor().newInstance(); + } catch (ReflectiveOperationException e) { throw new IllegalArgumentException("Could not instantiate lookup class", e); } } diff --git a/ehcache-transactions/src/test/java/org/ehcache/transactions/xa/internal/EhcacheXAResourceTest.java b/ehcache-transactions/src/test/java/org/ehcache/transactions/xa/internal/EhcacheXAResourceTest.java index 34a17f97bb..d02c19287d 100644 --- a/ehcache-transactions/src/test/java/org/ehcache/transactions/xa/internal/EhcacheXAResourceTest.java +++ b/ehcache-transactions/src/test/java/org/ehcache/transactions/xa/internal/EhcacheXAResourceTest.java @@ -22,8 +22,10 @@ import org.hamcrest.Matchers; import org.junit.Before; import org.junit.Test; +import org.junit.runner.RunWith; import org.mockito.Mock; import org.mockito.MockitoAnnotations; +import org.mockito.junit.MockitoJUnitRunner; import javax.transaction.xa.XAException; import javax.transaction.xa.XAResource; @@ -48,6 +50,7 @@ /** * @author Ludovic Orban */ +@RunWith(MockitoJUnitRunner.class) public class EhcacheXAResourceTest { @Mock @@ -59,11 +62,6 @@ public class EhcacheXAResourceTest { @Mock private XATransactionContext xaTransactionContext; - @Before - public void setUp() { - MockitoAnnotations.initMocks(this); - } - @Test public void testStartEndWorks() throws Exception { EhcacheXAResource xaResource = new EhcacheXAResource<>(underlyingStore, journal, xaTransactionContextFactory); @@ -88,7 +86,6 @@ public void testTwoNonEndedStartsFails() throws Exception { when(xaTransactionContextFactory.createTransactionContext(eq(new TransactionId(new TestXid(0, 0))), refEq(underlyingStore), refEq(journal), anyInt())).thenReturn(xaTransactionContext); xaResource.start(new TestXid(0, 0), XAResource.TMNOFLAGS); - when(xaTransactionContextFactory.createTransactionContext(eq(new TransactionId(new TestXid(1, 0))), refEq(underlyingStore), refEq(journal), anyInt())).thenReturn(xaTransactionContext); try { xaResource.start(new TestXid(1, 0), XAResource.TMNOFLAGS); fail("expected XAException"); @@ -202,7 +199,6 @@ public void testPrepareReadOnly() throws Exception { public void testCannotCommitUnknownXidInFlight() throws Exception { EhcacheXAResource xaResource = new EhcacheXAResource<>(underlyingStore, journal, xaTransactionContextFactory); - when(journal.isInDoubt(eq(new TransactionId(new TestXid(0, 0))))).thenReturn(false); when(xaTransactionContextFactory.get(eq(new TransactionId(new TestXid(0, 0))))).thenReturn(xaTransactionContext); doThrow(IllegalArgumentException.class).when(xaTransactionContext).commit(eq(false)); @@ -496,7 +492,6 @@ public void testRecoveryCommitOnePhaseFails() throws Exception { EhcacheXAResource xaResource = new EhcacheXAResource<>(underlyingStore, journal, xaTransactionContextFactory); when(journal.recover()).thenReturn(Collections.singletonMap(new TransactionId(new TestXid(0, 0)), (Collection) Arrays.asList(1L, 2L, 3L))); - when(journal.getInDoubtKeys(eq(new TransactionId(new TestXid(0, 0))))).thenReturn(Arrays.asList(1L, 2L, 3L)); Xid[] recoveredXids = xaResource.recover(XAResource.TMSTARTRSCAN | XAResource.TMENDRSCAN); assertThat(recoveredXids.length, is(1)); diff --git a/ehcache-transactions/src/test/java/org/ehcache/transactions/xa/utils/JavaSerializer.java b/ehcache-transactions/src/test/java/org/ehcache/transactions/xa/utils/JavaSerializer.java index a2f80d75f3..9aa4394f5e 100644 --- a/ehcache-transactions/src/test/java/org/ehcache/transactions/xa/utils/JavaSerializer.java +++ b/ehcache-transactions/src/test/java/org/ehcache/transactions/xa/utils/JavaSerializer.java @@ -94,7 +94,7 @@ public OIS(InputStream in, ClassLoader classLoader) throws IOException { } @Override - protected Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { + protected Class resolveClass(ObjectStreamClass desc) throws ClassNotFoundException { try { return Class.forName(desc.getName(), false, classLoader); } catch (ClassNotFoundException cnfe) { @@ -106,8 +106,8 @@ protected Class resolveClass(ObjectStreamClass desc) throws IOException, Clas } } - @Override - protected Class resolveProxyClass(String[] interfaces) throws IOException, ClassNotFoundException { + @Override @SuppressWarnings("deprecation") + protected Class resolveProxyClass(String[] interfaces) throws ClassNotFoundException { Class[] interfaceClasses = new Class[interfaces.length]; for (int i = 0; i < interfaces.length; i++) { interfaceClasses[i] = Class.forName(interfaces[i], false, classLoader); diff --git a/ehcache-xml/build.gradle b/ehcache-xml/build.gradle index 32bd861c83..2eda21a731 100644 --- a/ehcache-xml/build.gradle +++ b/ehcache-xml/build.gradle @@ -110,7 +110,7 @@ dependencies { testFixturesApi 'org.xmlunit:xmlunit-core:2.6.0', 'org.xmlunit:xmlunit-matchers:2.6.0' xjcClasspathGlobal 'org.jvnet.jaxb2_commons:jaxb2-fluent-api:3.0' - xjcClasspathGlobal 'org.jvnet.jaxb2_commons:jaxb2-basics-annotate:1.1.0' +// xjcClasspathGlobal 'org.jvnet.jaxb2_commons:jaxb2-basics-annotate:1.1.0' xjcToolJakarta 'com.sun.xml.bind:jaxb-xjc:3.0.0-M4' xjcToolJakarta 'com.sun.xml.bind:jaxb-impl:3.0.0-M4' @@ -136,13 +136,22 @@ tasks.named('jakartaJar', Jar) { xjc { extraArgs.add '-Xfluent-api' - extraArgs.add '-Xannotate' +// extraArgs.add '-Xannotate' // ehcache-multi.xsd references ehcache-core.xsd but we cannot control the order they get presented to XJC in. // Turning off strict checks prevents failing on when seeing the resultant schema parsing issues. strictCheck = false } +compileJava { + //no -Werror due to jaxb generated sources + options.compilerArgs -= '-Werror' +} +compileJakartaJava { + //no -Werror due to jaxb generated sources + options.compilerArgs -= '-Werror' +} + xjcGenerateJakarta { toolClasspath.setFrom configurations.xjcToolJakarta } diff --git a/ehcache-xml/src/common/schema/ehcache-core.xsd b/ehcache-xml/src/common/schema/ehcache-core.xsd index 987316b871..8c87a63868 100644 --- a/ehcache-xml/src/common/schema/ehcache-core.xsd +++ b/ehcache-xml/src/common/schema/ehcache-core.xsd @@ -17,7 +17,6 @@ @@ -535,9 +534,6 @@ - - @java.lang.SuppressWarnings({"unchecked", "serial"}) - @@ -545,9 +541,6 @@ - - @java.lang.SuppressWarnings({"unchecked", "serial"}) - @@ -555,9 +548,6 @@ - - @java.lang.SuppressWarnings({"unchecked", "serial"}) - diff --git a/ehcache-xml/src/jakarta/java/org/ehcache/xml/ConfigurationParser.java b/ehcache-xml/src/jakarta/java/org/ehcache/xml/ConfigurationParser.java index c2e326e122..28e5604cf0 100644 --- a/ehcache-xml/src/jakarta/java/org/ehcache/xml/ConfigurationParser.java +++ b/ehcache-xml/src/jakarta/java/org/ehcache/xml/ConfigurationParser.java @@ -56,6 +56,7 @@ import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import javax.xml.validation.Schema; + import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; @@ -119,12 +120,12 @@ private static Stream stream(Iterable iterable) { ConfigurationParser() throws IOException, SAXException, JAXBException, ParserConfigurationException { serviceCreationConfigurationParser = ConfigurationParser.>stream( - servicesOfType(CacheManagerServiceConfigurationParser.class)) + servicesOfType(CacheManagerServiceConfigurationParser.class)) .collect(collectingAndThen(toMap(CacheManagerServiceConfigurationParser::getServiceType, identity(), (a, b) -> a.getClass().isInstance(b) ? b : a), ServiceCreationConfigurationParser::new)); serviceConfigurationParser = ConfigurationParser.>stream( - servicesOfType(CacheServiceConfigurationParser.class)) + servicesOfType(CacheServiceConfigurationParser.class)) .collect(collectingAndThen(toMap(CacheServiceConfigurationParser::getServiceType, identity(), (a, b) -> a.getClass().isInstance(b) ? b : a), ServiceConfigurationParser::new)); @@ -139,7 +140,7 @@ private static Stream stream(Iterable iterable) { CacheConfigurationBuilder parseServiceConfigurations(CacheConfigurationBuilder cacheBuilder, ClassLoader cacheClassLoader, CacheTemplate cacheDefinition) - throws ClassNotFoundException, IllegalAccessException, InstantiationException { + throws ReflectiveOperationException { cacheBuilder = CORE_CACHE_CONFIGURATION_PARSER.parseConfiguration(cacheDefinition, cacheClassLoader, cacheBuilder); return serviceConfigurationParser.parseConfiguration(cacheDefinition, cacheClassLoader, cacheBuilder); } @@ -183,7 +184,7 @@ private Map getTemplates(ConfigType configTyp private XmlConfiguration.Template parseTemplate(CacheTemplate template) { return new XmlConfiguration.Template() { @Override - public CacheConfigurationBuilder builderFor(ClassLoader classLoader, Class keyType, Class valueType, ResourcePools resources) throws ClassNotFoundException, InstantiationException, IllegalAccessException { + public CacheConfigurationBuilder builderFor(ClassLoader classLoader, Class keyType, Class valueType, ResourcePools resources) throws ReflectiveOperationException { checkTemplateTypeConsistency("key", classLoader, keyType, template); checkTemplateTypeConsistency("value", classLoader, valueType, template); @@ -217,7 +218,7 @@ public Document uriToDocument(URI uri) throws IOException, SAXException { return documentBuilder.parse(uri.toString()); } - public XmlConfigurationWrapper documentToConfig(Document document, ClassLoader classLoader, Map cacheClassLoaders) throws JAXBException, ClassNotFoundException, InstantiationException, IllegalAccessException { + public XmlConfigurationWrapper documentToConfig(Document document, ClassLoader classLoader, Map cacheClassLoaders) throws JAXBException, ReflectiveOperationException { Element root = document.getDocumentElement(); QName rootName = new QName(root.getNamespaceURI(), root.getLocalName()); diff --git a/ehcache-xml/src/jakarta/java/org/ehcache/xml/CoreCacheConfigurationParser.java b/ehcache-xml/src/jakarta/java/org/ehcache/xml/CoreCacheConfigurationParser.java index 89681e3999..a5b4dc0cf2 100644 --- a/ehcache-xml/src/jakarta/java/org/ehcache/xml/CoreCacheConfigurationParser.java +++ b/ehcache-xml/src/jakarta/java/org/ehcache/xml/CoreCacheConfigurationParser.java @@ -30,6 +30,7 @@ import org.ehcache.xml.model.ObjectFactory; import org.ehcache.xml.model.TimeTypeWithPropSubst; +import java.lang.reflect.InvocationTargetException; import java.math.BigInteger; import java.time.Duration; import java.util.stream.Stream; @@ -43,7 +44,7 @@ public class CoreCacheConfigurationParser { public CacheConfigurationBuilder parseConfiguration(CacheTemplate cacheDefinition, ClassLoader cacheClassLoader, - CacheConfigurationBuilder cacheBuilder) throws ClassNotFoundException, IllegalAccessException, InstantiationException { + CacheConfigurationBuilder cacheBuilder) throws ReflectiveOperationException { final Expiry parsedExpiry = cacheDefinition.expiry(); if (parsedExpiry != null) { cacheBuilder = cacheBuilder.withExpiry(getExpiry(cacheClassLoader, parsedExpiry)); @@ -57,8 +58,7 @@ public CacheConfigurationBuilder parseConfiguration(CacheTemplate c } @SuppressWarnings({"unchecked", "deprecation"}) - private static ExpiryPolicy getExpiry(ClassLoader cacheClassLoader, Expiry parsedExpiry) - throws ClassNotFoundException, InstantiationException, IllegalAccessException { + private static ExpiryPolicy getExpiry(ClassLoader cacheClassLoader, Expiry parsedExpiry) throws ReflectiveOperationException { if (parsedExpiry.isUserDef()) { try { return getInstanceOfName(parsedExpiry.type(), cacheClassLoader, ExpiryPolicy.class); @@ -74,12 +74,12 @@ public CacheConfigurationBuilder parseConfiguration(CacheTemplate c } } - static T getInstanceOfName(String name, ClassLoader classLoader, Class type) throws ClassNotFoundException, InstantiationException, IllegalAccessException { + static T getInstanceOfName(String name, ClassLoader classLoader, Class type) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { if (name == null) { return null; } Class klazz = getClassForName(name, classLoader); - return klazz.asSubclass(type).newInstance(); + return klazz.asSubclass(type).getDeclaredConstructor().newInstance(); } public CacheType unparseConfiguration(CacheConfiguration cacheConfiguration, CacheType cacheType) { diff --git a/ehcache-xml/src/jakarta/java/org/ehcache/xml/XmlConfiguration.java b/ehcache-xml/src/jakarta/java/org/ehcache/xml/XmlConfiguration.java index fe0a278d8f..33e96b0df5 100644 --- a/ehcache-xml/src/jakarta/java/org/ehcache/xml/XmlConfiguration.java +++ b/ehcache-xml/src/jakarta/java/org/ehcache/xml/XmlConfiguration.java @@ -16,11 +16,11 @@ package org.ehcache.xml; -import org.ehcache.config.Builder; import org.ehcache.config.CacheConfiguration; import org.ehcache.config.Configuration; -import org.ehcache.config.FluentConfigurationBuilder; import org.ehcache.config.ResourcePools; +import org.ehcache.config.Builder; +import org.ehcache.config.FluentConfigurationBuilder; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.core.util.ClassLoading; import org.ehcache.spi.service.ServiceCreationConfiguration; @@ -44,7 +44,7 @@ import static org.ehcache.xml.XmlConfiguration.PrettyClassFormat.when; /** - * Exposes {@link Configuration} and {@link CacheConfigurationBuilder} expressed + * Exposes {@link org.ehcache.config.Configuration} and {@link CacheConfigurationBuilder} expressed * in a XML file that obeys the core Ehcache schema. *

* Instances of this class are not thread-safe. @@ -72,7 +72,7 @@ public class XmlConfiguration implements Configuration { * @throws XmlConfigurationException if anything went wrong parsing the XML */ public XmlConfiguration(URL url) - throws XmlConfigurationException { + throws XmlConfigurationException { this(url, ClassLoading.getDefaultClassLoader()); } @@ -86,15 +86,15 @@ public XmlConfiguration(URL url) * @throws XmlConfigurationException if anything went wrong parsing the XML */ public XmlConfiguration(URL url, final ClassLoader classLoader) - throws XmlConfigurationException { + throws XmlConfigurationException { this(url, classLoader, Collections.emptyMap()); } /** * Constructs an instance of XmlConfiguration mapping to the XML file located at {@code url} and using the provided * {@code classLoader} to load user types (e.g. key and value Class instances). The {@code cacheClassLoaders} will - * let you specify a different {@link ClassLoader} to use for each {@link org.ehcache.Cache} managed by - * the {@link org.ehcache.CacheManager} configured using this {@link XmlConfiguration}. Caches with + * let you specify a different {@link java.lang.ClassLoader} to use for each {@link org.ehcache.Cache} managed by + * the {@link org.ehcache.CacheManager} configured using this {@link org.ehcache.xml.XmlConfiguration}. Caches with * aliases that do not appear in the map will use {@code classLoader} as a default. * * @param url URL pointing to the XML file's location @@ -104,7 +104,7 @@ public XmlConfiguration(URL url, final ClassLoader classLoader) * @throws XmlConfigurationException if anything went wrong parsing the XML */ public XmlConfiguration(URL url, final ClassLoader classLoader, final Map cacheClassLoaders) - throws XmlConfigurationException { + throws XmlConfigurationException { this.source = requireNonNull(url, "The url can not be null"); requireNonNull(classLoader, "The classLoader can not be null"); @@ -155,8 +155,8 @@ public XmlConfiguration(Document xml, ClassLoader classLoader) throws XmlConfigu /** * Constructs an instance of XmlConfiguration from the given XML DOM and using the provided {@code classLoader} to * load user types (e.g. key and value Class instances). The {@code cacheClassLoaders} will let you specify a - * different {@link ClassLoader} to use for each {@link org.ehcache.Cache} managed by the - * {@link org.ehcache.CacheManager} configured using this {@link XmlConfiguration}. Caches with + * different {@link java.lang.ClassLoader} to use for each {@link org.ehcache.Cache} managed by the + * {@link org.ehcache.CacheManager} configured using this {@link org.ehcache.xml.XmlConfiguration}. Caches with * aliases that do not appear in the map will use {@code classLoader} as a default. * * @param xml XML Document Object Model @@ -211,7 +211,7 @@ public XmlConfiguration(Configuration configuration) throws XmlConfigurationExce } /** - * Return this configuration as an XML {@link Document}. + * Return this configuration as an XML {@link org.w3c.dom.Document}. * * @return configuration XML DOM. */ @@ -261,15 +261,13 @@ public URL getURL() { * * @throws IllegalStateException if the template does not configure resources. * @throws IllegalArgumentException if {@code keyType} or {@code valueType} don't match the declared type(s) of the template - * @throws ClassNotFoundException if a {@link Class} declared in the XML couldn't be found - * @throws InstantiationException if a user provided {@link Class} couldn't get instantiated + * @throws ClassNotFoundException if a {@link java.lang.Class} declared in the XML couldn't be found * @throws IllegalAccessException if a method (including constructor) couldn't be invoked on a user provided type */ - @SuppressWarnings("unchecked") public CacheConfigurationBuilder newCacheConfigurationBuilderFromTemplate(final String name, final Class keyType, final Class valueType) - throws InstantiationException, IllegalAccessException, ClassNotFoundException { + throws ReflectiveOperationException { Template template = templates.get(name); if (template == null) { return null; @@ -295,8 +293,8 @@ public CacheConfigurationBuilder newCacheConfigurationBuilderFromTe * or {@code null} if no cache-template for the provided {@code name} * * @throws IllegalArgumentException if {@code keyType} or {@code valueType} don't match the declared type(s) of the template - * @throws ClassNotFoundException if a {@link Class} declared in the XML couldn't be found - * @throws InstantiationException if a user provided {@link Class} couldn't get instantiated + * @throws ClassNotFoundException if a {@link java.lang.Class} declared in the XML couldn't be found + * @throws InstantiationException if a user provided {@link java.lang.Class} couldn't get instantiated * @throws IllegalAccessException if a method (including constructor) couldn't be invoked on a user provided type */ @SuppressWarnings("unchecked") @@ -304,7 +302,7 @@ public CacheConfigurationBuilder newCacheConfigurationBuilderFromTe final Class keyType, final Class valueType, final ResourcePools resourcePools) - throws InstantiationException, IllegalAccessException, ClassNotFoundException { + throws ReflectiveOperationException { Template template = templates.get(name); if (template == null) { return null; @@ -330,8 +328,8 @@ public CacheConfigurationBuilder newCacheConfigurationBuilderFromTe * or {@code null} if no cache-template for the provided {@code name} * * @throws IllegalArgumentException if {@code keyType} or {@code valueType} don't match the declared type(s) of the template - * @throws ClassNotFoundException if a {@link Class} declared in the XML couldn't be found - * @throws InstantiationException if a user provided {@link Class} couldn't get instantiated + * @throws ClassNotFoundException if a {@link java.lang.Class} declared in the XML couldn't be found + * @throws InstantiationException if a user provided {@link java.lang.Class} couldn't get instantiated * @throws IllegalAccessException if a method (including constructor) couldn't be invoked on a user provided type */ @SuppressWarnings("unchecked") @@ -339,7 +337,7 @@ public CacheConfigurationBuilder newCacheConfigurationBuilderFromTe final Class keyType, final Class valueType, final Builder resourcePoolsBuilder) - throws InstantiationException, IllegalAccessException, ClassNotFoundException { + throws ReflectiveOperationException { return newCacheConfigurationBuilderFromTemplate(name, keyType, valueType, resourcePoolsBuilder.build()); } @@ -364,7 +362,7 @@ public FluentConfigurationBuilder derive() { } public interface Template { - CacheConfigurationBuilder builderFor(ClassLoader classLoader, Class keyType, Class valueType, ResourcePools resourcePools) throws ClassNotFoundException, InstantiationException, IllegalAccessException; + CacheConfigurationBuilder builderFor(ClassLoader classLoader, Class keyType, Class valueType, ResourcePools resourcePools) throws ReflectiveOperationException; } public static Class getClassForName(String name, ClassLoader classLoader) throws ClassNotFoundException { diff --git a/ehcache-xml/src/main/java/org/ehcache/xml/ConfigurationParser.java b/ehcache-xml/src/main/java/org/ehcache/xml/ConfigurationParser.java index 1d53df6c3c..5300819406 100644 --- a/ehcache-xml/src/main/java/org/ehcache/xml/ConfigurationParser.java +++ b/ehcache-xml/src/main/java/org/ehcache/xml/ConfigurationParser.java @@ -139,7 +139,7 @@ private static Stream stream(Iterable iterable) { CacheConfigurationBuilder parseServiceConfigurations(CacheConfigurationBuilder cacheBuilder, ClassLoader cacheClassLoader, CacheTemplate cacheDefinition) - throws ClassNotFoundException, IllegalAccessException, InstantiationException { + throws ReflectiveOperationException { cacheBuilder = CORE_CACHE_CONFIGURATION_PARSER.parseConfiguration(cacheDefinition, cacheClassLoader, cacheBuilder); return serviceConfigurationParser.parseConfiguration(cacheDefinition, cacheClassLoader, cacheBuilder); } @@ -183,7 +183,7 @@ private Map getTemplates(ConfigType configTyp private XmlConfiguration.Template parseTemplate(CacheTemplate template) { return new XmlConfiguration.Template() { @Override - public CacheConfigurationBuilder builderFor(ClassLoader classLoader, Class keyType, Class valueType, ResourcePools resources) throws ClassNotFoundException, InstantiationException, IllegalAccessException { + public CacheConfigurationBuilder builderFor(ClassLoader classLoader, Class keyType, Class valueType, ResourcePools resources) throws ReflectiveOperationException { checkTemplateTypeConsistency("key", classLoader, keyType, template); checkTemplateTypeConsistency("value", classLoader, valueType, template); @@ -217,7 +217,7 @@ public Document uriToDocument(URI uri) throws IOException, SAXException { return documentBuilder.parse(uri.toString()); } - public XmlConfigurationWrapper documentToConfig(Document document, ClassLoader classLoader, Map cacheClassLoaders) throws JAXBException, ClassNotFoundException, InstantiationException, IllegalAccessException { + public XmlConfigurationWrapper documentToConfig(Document document, ClassLoader classLoader, Map cacheClassLoaders) throws JAXBException, ReflectiveOperationException { Element root = document.getDocumentElement(); QName rootName = new QName(root.getNamespaceURI(), root.getLocalName()); diff --git a/ehcache-xml/src/main/java/org/ehcache/xml/CoreCacheConfigurationParser.java b/ehcache-xml/src/main/java/org/ehcache/xml/CoreCacheConfigurationParser.java index 89681e3999..a5b4dc0cf2 100644 --- a/ehcache-xml/src/main/java/org/ehcache/xml/CoreCacheConfigurationParser.java +++ b/ehcache-xml/src/main/java/org/ehcache/xml/CoreCacheConfigurationParser.java @@ -30,6 +30,7 @@ import org.ehcache.xml.model.ObjectFactory; import org.ehcache.xml.model.TimeTypeWithPropSubst; +import java.lang.reflect.InvocationTargetException; import java.math.BigInteger; import java.time.Duration; import java.util.stream.Stream; @@ -43,7 +44,7 @@ public class CoreCacheConfigurationParser { public CacheConfigurationBuilder parseConfiguration(CacheTemplate cacheDefinition, ClassLoader cacheClassLoader, - CacheConfigurationBuilder cacheBuilder) throws ClassNotFoundException, IllegalAccessException, InstantiationException { + CacheConfigurationBuilder cacheBuilder) throws ReflectiveOperationException { final Expiry parsedExpiry = cacheDefinition.expiry(); if (parsedExpiry != null) { cacheBuilder = cacheBuilder.withExpiry(getExpiry(cacheClassLoader, parsedExpiry)); @@ -57,8 +58,7 @@ public CacheConfigurationBuilder parseConfiguration(CacheTemplate c } @SuppressWarnings({"unchecked", "deprecation"}) - private static ExpiryPolicy getExpiry(ClassLoader cacheClassLoader, Expiry parsedExpiry) - throws ClassNotFoundException, InstantiationException, IllegalAccessException { + private static ExpiryPolicy getExpiry(ClassLoader cacheClassLoader, Expiry parsedExpiry) throws ReflectiveOperationException { if (parsedExpiry.isUserDef()) { try { return getInstanceOfName(parsedExpiry.type(), cacheClassLoader, ExpiryPolicy.class); @@ -74,12 +74,12 @@ public CacheConfigurationBuilder parseConfiguration(CacheTemplate c } } - static T getInstanceOfName(String name, ClassLoader classLoader, Class type) throws ClassNotFoundException, InstantiationException, IllegalAccessException { + static T getInstanceOfName(String name, ClassLoader classLoader, Class type) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { if (name == null) { return null; } Class klazz = getClassForName(name, classLoader); - return klazz.asSubclass(type).newInstance(); + return klazz.asSubclass(type).getDeclaredConstructor().newInstance(); } public CacheType unparseConfiguration(CacheConfiguration cacheConfiguration, CacheType cacheType) { diff --git a/ehcache-xml/src/main/java/org/ehcache/xml/XmlConfiguration.java b/ehcache-xml/src/main/java/org/ehcache/xml/XmlConfiguration.java index f44adb566d..a8563ef29c 100644 --- a/ehcache-xml/src/main/java/org/ehcache/xml/XmlConfiguration.java +++ b/ehcache-xml/src/main/java/org/ehcache/xml/XmlConfiguration.java @@ -262,14 +262,12 @@ public URL getURL() { * @throws IllegalStateException if the template does not configure resources. * @throws IllegalArgumentException if {@code keyType} or {@code valueType} don't match the declared type(s) of the template * @throws ClassNotFoundException if a {@link java.lang.Class} declared in the XML couldn't be found - * @throws InstantiationException if a user provided {@link java.lang.Class} couldn't get instantiated * @throws IllegalAccessException if a method (including constructor) couldn't be invoked on a user provided type */ - @SuppressWarnings("unchecked") public CacheConfigurationBuilder newCacheConfigurationBuilderFromTemplate(final String name, final Class keyType, final Class valueType) - throws InstantiationException, IllegalAccessException, ClassNotFoundException { + throws ReflectiveOperationException { Template template = templates.get(name); if (template == null) { return null; @@ -304,7 +302,7 @@ public CacheConfigurationBuilder newCacheConfigurationBuilderFromTe final Class keyType, final Class valueType, final ResourcePools resourcePools) - throws InstantiationException, IllegalAccessException, ClassNotFoundException { + throws ReflectiveOperationException { Template template = templates.get(name); if (template == null) { return null; @@ -339,7 +337,7 @@ public CacheConfigurationBuilder newCacheConfigurationBuilderFromTe final Class keyType, final Class valueType, final Builder resourcePoolsBuilder) - throws InstantiationException, IllegalAccessException, ClassNotFoundException { + throws ReflectiveOperationException { return newCacheConfigurationBuilderFromTemplate(name, keyType, valueType, resourcePoolsBuilder.build()); } @@ -364,7 +362,7 @@ public FluentConfigurationBuilder derive() { } public interface Template { - CacheConfigurationBuilder builderFor(ClassLoader classLoader, Class keyType, Class valueType, ResourcePools resourcePools) throws ClassNotFoundException, InstantiationException, IllegalAccessException; + CacheConfigurationBuilder builderFor(ClassLoader classLoader, Class keyType, Class valueType, ResourcePools resourcePools) throws ReflectiveOperationException; } public static Class getClassForName(String name, ClassLoader classLoader) throws ClassNotFoundException { diff --git a/ehcache-xml/src/test/java/org/ehcache/xml/IntegrationConfigurationTest.java b/ehcache-xml/src/test/java/org/ehcache/xml/IntegrationConfigurationTest.java index e77d27dbd2..e3c0c5d963 100644 --- a/ehcache-xml/src/test/java/org/ehcache/xml/IntegrationConfigurationTest.java +++ b/ehcache-xml/src/test/java/org/ehcache/xml/IntegrationConfigurationTest.java @@ -110,8 +110,7 @@ public void testCopiers() throws Exception { } @Test - public void testLoaderWriter() throws ClassNotFoundException, SAXException, InstantiationException, - IOException, IllegalAccessException { + public void testLoaderWriter() { Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/cache-integration.xml")); assertThat(configuration.getCacheConfigurations().containsKey("bar"), is(true)); final CacheManager cacheManager = CacheManagerBuilder.newCacheManager(configuration); @@ -119,7 +118,7 @@ public void testLoaderWriter() throws ClassNotFoundException, SAXException, Inst final Cache cache = cacheManager.getCache("bar", Number.class, String.class); assertThat(cache, notNullValue()); assertThat(cache.get(1), notNullValue()); - final Number key = new Long(42); + final Number key = 42L; cache.put(key, "Bye y'all!"); assertThat(TestCacheLoaderWriter.lastWrittenKey, is(key)); @@ -127,13 +126,13 @@ public void testLoaderWriter() throws ClassNotFoundException, SAXException, Inst final Cache templateCache = cacheManager.getCache("template1", Number.class, String.class); assertThat(templateCache, notNullValue()); assertThat(templateCache.get(1), notNullValue()); - final Number key1 = new Long(100); + final Number key1 = 100L; templateCache.put(key1, "Bye y'all!"); assertThat(TestCacheLoaderWriter.lastWrittenKey, is(key1)); } @Test - public void testWriteBehind() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SAXException, IOException, InterruptedException { + public void testWriteBehind() throws InterruptedException { Configuration configuration = new XmlConfiguration(this.getClass().getResource("/configs/writebehind-cache.xml")); assertThat(configuration.getCacheConfigurations().containsKey("bar"), is(true)); diff --git a/ehcache-xml/src/test/java/org/ehcache/xml/provider/CacheEventDispatcherFactoryConfigurationParserTest.java b/ehcache-xml/src/test/java/org/ehcache/xml/provider/CacheEventDispatcherFactoryConfigurationParserTest.java index eb126f095d..aa74131d49 100644 --- a/ehcache-xml/src/test/java/org/ehcache/xml/provider/CacheEventDispatcherFactoryConfigurationParserTest.java +++ b/ehcache-xml/src/test/java/org/ehcache/xml/provider/CacheEventDispatcherFactoryConfigurationParserTest.java @@ -23,19 +23,13 @@ import org.ehcache.xml.XmlConfiguration; import org.ehcache.xml.model.ConfigType; import org.junit.Test; -import org.xml.sax.SAXException; - -import java.io.IOException; - -import javax.xml.bind.JAXBException; -import javax.xml.parsers.ParserConfigurationException; import static org.assertj.core.api.Assertions.assertThat; public class CacheEventDispatcherFactoryConfigurationParserTest { @Test - public void parseServiceCreationConfiguration() throws SAXException, JAXBException, ParserConfigurationException, IOException, ClassNotFoundException { + public void parseServiceCreationConfiguration() { Configuration xmlConfig = new XmlConfiguration(getClass().getResource("/configs/ehcache-cacheEventListener.xml")); assertThat(xmlConfig.getServiceCreationConfigurations()).hasSize(1); diff --git a/ehcache-xml/src/test/java/org/ehcache/xml/provider/CacheManagerPersistenceConfigurationParserTest.java b/ehcache-xml/src/test/java/org/ehcache/xml/provider/CacheManagerPersistenceConfigurationParserTest.java index 0cc26057eb..e0d11592f3 100644 --- a/ehcache-xml/src/test/java/org/ehcache/xml/provider/CacheManagerPersistenceConfigurationParserTest.java +++ b/ehcache-xml/src/test/java/org/ehcache/xml/provider/CacheManagerPersistenceConfigurationParserTest.java @@ -22,22 +22,17 @@ import org.ehcache.xml.XmlConfiguration; import org.ehcache.xml.model.ConfigType; import org.junit.Test; -import org.xml.sax.SAXException; import java.io.File; -import java.io.IOException; import java.util.List; -import javax.xml.bind.JAXBException; -import javax.xml.parsers.ParserConfigurationException; - import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; public class CacheManagerPersistenceConfigurationParserTest { @Test - public void parseServiceCreationConfiguration() throws SAXException, JAXBException, ParserConfigurationException, IOException, ClassNotFoundException { + public void parseServiceCreationConfiguration() { Configuration xmlConfig = new XmlConfiguration(getClass().getResource("/configs/disk-persistent-cache.xml")); List serviceConfig = xmlConfig.getServiceCreationConfigurations().stream() diff --git a/ehcache-xml/src/test/java/org/ehcache/xml/provider/DefaultCopyProviderConfigurationParserTest.java b/ehcache-xml/src/test/java/org/ehcache/xml/provider/DefaultCopyProviderConfigurationParserTest.java index c950fc01a3..673cda3afd 100644 --- a/ehcache-xml/src/test/java/org/ehcache/xml/provider/DefaultCopyProviderConfigurationParserTest.java +++ b/ehcache-xml/src/test/java/org/ehcache/xml/provider/DefaultCopyProviderConfigurationParserTest.java @@ -25,26 +25,21 @@ import org.ehcache.xml.model.ConfigType; import org.ehcache.xml.model.CopierType; import org.junit.Test; -import org.xml.sax.SAXException; import com.pany.ehcache.copier.Description; import com.pany.ehcache.copier.DescriptionCopier; import com.pany.ehcache.copier.Person; import com.pany.ehcache.copier.PersonCopier; -import java.io.IOException; import java.util.List; import java.util.Map; -import javax.xml.bind.JAXBException; -import javax.xml.parsers.ParserConfigurationException; - import static org.assertj.core.api.Assertions.assertThat; public class DefaultCopyProviderConfigurationParserTest { @Test - public void parseServiceCreationConfiguration() throws SAXException, JAXBException, ParserConfigurationException, IOException, ClassNotFoundException { + public void parseServiceCreationConfiguration() { Configuration xmlConfig = new XmlConfiguration(getClass().getResource("/configs/cache-copiers.xml")); assertThat(xmlConfig.getServiceCreationConfigurations()).hasSize(1); diff --git a/ehcache-xml/src/test/java/org/ehcache/xml/provider/DefaultSerializationProviderConfigurationParserTest.java b/ehcache-xml/src/test/java/org/ehcache/xml/provider/DefaultSerializationProviderConfigurationParserTest.java index ea08c210c8..ee5a5040e6 100644 --- a/ehcache-xml/src/test/java/org/ehcache/xml/provider/DefaultSerializationProviderConfigurationParserTest.java +++ b/ehcache-xml/src/test/java/org/ehcache/xml/provider/DefaultSerializationProviderConfigurationParserTest.java @@ -25,7 +25,6 @@ import org.ehcache.xml.model.ConfigType; import org.ehcache.xml.model.SerializerType; import org.junit.Test; -import org.xml.sax.SAXException; import com.pany.ehcache.copier.Description; import com.pany.ehcache.copier.Person; @@ -34,19 +33,15 @@ import com.pany.ehcache.serializer.TestSerializer3; import com.pany.ehcache.serializer.TestSerializer4; -import java.io.IOException; import java.util.List; import java.util.Map; -import javax.xml.bind.JAXBException; -import javax.xml.parsers.ParserConfigurationException; - import static org.assertj.core.api.Assertions.assertThat; public class DefaultSerializationProviderConfigurationParserTest { @Test - public void parseServiceCreationConfiguration() throws SAXException, JAXBException, ParserConfigurationException, IOException, ClassNotFoundException { + public void parseServiceCreationConfiguration() { Configuration xmlConfig = new XmlConfiguration(getClass().getResource("/configs/default-serializer.xml")); assertThat(xmlConfig.getServiceCreationConfigurations()).hasSize(1); diff --git a/ehcache-xml/src/test/java/org/ehcache/xml/provider/DefaultSizeOfEngineProviderConfigurationParserTest.java b/ehcache-xml/src/test/java/org/ehcache/xml/provider/DefaultSizeOfEngineProviderConfigurationParserTest.java index 3ad074be31..74e6d8edf2 100644 --- a/ehcache-xml/src/test/java/org/ehcache/xml/provider/DefaultSizeOfEngineProviderConfigurationParserTest.java +++ b/ehcache-xml/src/test/java/org/ehcache/xml/provider/DefaultSizeOfEngineProviderConfigurationParserTest.java @@ -25,19 +25,13 @@ import org.ehcache.xml.model.ConfigType; import org.ehcache.xml.model.SizeofType; import org.junit.Test; -import org.xml.sax.SAXException; - -import java.io.IOException; - -import javax.xml.bind.JAXBException; -import javax.xml.parsers.ParserConfigurationException; import static org.assertj.core.api.Assertions.assertThat; public class DefaultSizeOfEngineProviderConfigurationParserTest { @Test - public void parseServiceCreationConfiguration() throws SAXException, JAXBException, ParserConfigurationException, IOException, ClassNotFoundException { + public void parseServiceCreationConfiguration() { Configuration xmlConfig = new XmlConfiguration(getClass().getResource("/configs/sizeof-engine.xml")); assertThat(xmlConfig.getServiceCreationConfigurations()).hasSize(1); diff --git a/ehcache-xml/src/test/java/org/ehcache/xml/provider/OffHeapDiskStoreProviderConfigurationParserTest.java b/ehcache-xml/src/test/java/org/ehcache/xml/provider/OffHeapDiskStoreProviderConfigurationParserTest.java index e5600e8290..62c492aec7 100644 --- a/ehcache-xml/src/test/java/org/ehcache/xml/provider/OffHeapDiskStoreProviderConfigurationParserTest.java +++ b/ehcache-xml/src/test/java/org/ehcache/xml/provider/OffHeapDiskStoreProviderConfigurationParserTest.java @@ -23,19 +23,13 @@ import org.ehcache.xml.XmlConfiguration; import org.ehcache.xml.model.ConfigType; import org.junit.Test; -import org.xml.sax.SAXException; - -import java.io.IOException; - -import javax.xml.bind.JAXBException; -import javax.xml.parsers.ParserConfigurationException; import static org.assertj.core.api.Assertions.assertThat; public class OffHeapDiskStoreProviderConfigurationParserTest { @Test - public void parseServiceCreationConfiguration() throws SAXException, JAXBException, ParserConfigurationException, IOException, ClassNotFoundException { + public void parseServiceCreationConfiguration() { Configuration xmlConfig = new XmlConfiguration(getClass().getResource("/configs/resources-caches.xml")); assertThat(xmlConfig.getServiceCreationConfigurations()).hasSize(1); diff --git a/ehcache-xml/src/test/java/org/ehcache/xml/provider/PooledExecutionServiceConfigurationParserTest.java b/ehcache-xml/src/test/java/org/ehcache/xml/provider/PooledExecutionServiceConfigurationParserTest.java index 2c55ccbd6e..2a111797bf 100644 --- a/ehcache-xml/src/test/java/org/ehcache/xml/provider/PooledExecutionServiceConfigurationParserTest.java +++ b/ehcache-xml/src/test/java/org/ehcache/xml/provider/PooledExecutionServiceConfigurationParserTest.java @@ -24,20 +24,15 @@ import org.ehcache.xml.model.ConfigType; import org.ehcache.xml.model.ThreadPoolsType; import org.junit.Test; -import org.xml.sax.SAXException; -import java.io.IOException; import java.util.List; -import javax.xml.bind.JAXBException; -import javax.xml.parsers.ParserConfigurationException; - import static org.assertj.core.api.Assertions.assertThat; public class PooledExecutionServiceConfigurationParserTest { @Test - public void parseServiceCreationConfiguration() throws SAXException, JAXBException, ParserConfigurationException, IOException, ClassNotFoundException { + public void parseServiceCreationConfiguration() { Configuration xmlConfig = new XmlConfiguration(getClass().getResource("/configs/thread-pools.xml")); assertThat(xmlConfig.getServiceCreationConfigurations()).hasSize(1); diff --git a/ehcache-xml/src/test/java/org/ehcache/xml/provider/WriteBehindProviderConfigurationParserTest.java b/ehcache-xml/src/test/java/org/ehcache/xml/provider/WriteBehindProviderConfigurationParserTest.java index fd35e5b71b..7fb9436eb5 100644 --- a/ehcache-xml/src/test/java/org/ehcache/xml/provider/WriteBehindProviderConfigurationParserTest.java +++ b/ehcache-xml/src/test/java/org/ehcache/xml/provider/WriteBehindProviderConfigurationParserTest.java @@ -23,19 +23,13 @@ import org.ehcache.xml.XmlConfiguration; import org.ehcache.xml.model.ConfigType; import org.junit.Test; -import org.xml.sax.SAXException; - -import java.io.IOException; - -import javax.xml.bind.JAXBException; -import javax.xml.parsers.ParserConfigurationException; import static org.assertj.core.api.Assertions.assertThat; public class WriteBehindProviderConfigurationParserTest { @Test - public void parseServiceCreationConfiguration() throws SAXException, JAXBException, ParserConfigurationException, IOException, ClassNotFoundException { + public void parseServiceCreationConfiguration() { Configuration xmlConfig = new XmlConfiguration(getClass().getResource("/configs/writebehind-cache.xml")); assertThat(xmlConfig.getServiceCreationConfigurations()).hasSize(1); diff --git a/ehcache/build.gradle b/ehcache/build.gradle index c2ca30018c..4e8c136020 100644 --- a/ehcache/build.gradle +++ b/ehcache/build.gradle @@ -105,7 +105,7 @@ tasks.named('jakartaJar') { instruction Constants.BUNDLE_DESCRIPTION, 'Ehcache is an open-source caching library, compliant with the JSR-107 standard.' instruction Constants.BUNDLE_ACTIVATOR, 'org.ehcache.core.osgi.EhcacheActivator' instruction Constants.EXPORT_PACKAGE, '!org.ehcache.jsr107.tck, !org.ehcache.*.internal.*, org.ehcache.*' - instruction Constants.IMPORT_PACKAGE, 'javax.cache.*;resolution:=optional, !javax.annotation, !sun.misc, jakarta.xml.bind*;version="[3,4)", *' + instruction Constants.IMPORT_PACKAGE, 'javax.cache.*;resolution:=optional, jdk.internal.vm.annotation;resolution:=optional, !javax.annotation, !sun.misc, jakarta.xml.bind*;version="[3,4)", *' } } @@ -116,7 +116,7 @@ tasks.named('jar') { instruction Constants.BUNDLE_DESCRIPTION, 'Ehcache is an open-source caching library, compliant with the JSR-107 standard.' instruction Constants.BUNDLE_ACTIVATOR, 'org.ehcache.core.osgi.EhcacheActivator' instruction Constants.EXPORT_PACKAGE, '!org.ehcache.jsr107.tck, !org.ehcache.*.internal.*, org.ehcache.*' - instruction Constants.IMPORT_PACKAGE, 'javax.cache.*;resolution:=optional, !javax.annotation, !sun.misc, javax.xml.bind*;version="[2.2,3)", *' + instruction Constants.IMPORT_PACKAGE, 'javax.cache.*;resolution:=optional, jdk.internal.vm.annotation;resolution:=optional, !javax.annotation, !sun.misc, javax.xml.bind*;version="[2.2,3)", *' } } diff --git a/gradle.properties b/gradle.properties index 4fa2259dcb..88649ff19a 100644 --- a/gradle.properties +++ b/gradle.properties @@ -19,7 +19,7 @@ terracottaUtilitiesVersion = 0.0.9 junitVersion = 4.13.1 assertjVersion = 3.9.0 hamcrestVersion = 1.3 -mockitoVersion = 2.23.4 +mockitoVersion = 3.12.4 jacksonVersion = 2.12.4 jcacheTckVersion = 1.1.0 diff --git a/integration-test/src/test/java/org/ehcache/integration/LoaderWriterSimpleEhcacheTest.java b/integration-test/src/test/java/org/ehcache/integration/LoaderWriterSimpleEhcacheTest.java index 6e942ec5b1..d05723b61c 100644 --- a/integration-test/src/test/java/org/ehcache/integration/LoaderWriterSimpleEhcacheTest.java +++ b/integration-test/src/test/java/org/ehcache/integration/LoaderWriterSimpleEhcacheTest.java @@ -38,8 +38,8 @@ import static org.mockito.Mockito.reset; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.verifyNoMoreInteractions; -import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; /** @@ -104,7 +104,7 @@ public void testSimplePutIfAbsentWithLoaderAndWriter_existsInStore() throws Exce assertThat(testCache.putIfAbsent(1, "one"), Matchers.equalTo("un")); assertThat(testCache.get(1), Matchers.equalTo("un")); - verifyZeroInteractions(cacheLoaderWriter); + verifyNoInteractions(cacheLoaderWriter); } @Test @@ -200,7 +200,7 @@ public void testSimpleReplace3ArgsWithLoaderAndWriter_existsInStore_notEquals() assertThat(testCache.replace(1, "uno", "one"), is(false)); assertThat(testCache.get(1), Matchers.equalTo("un")); - verifyZeroInteractions(cacheLoaderWriter); + verifyNoInteractions(cacheLoaderWriter); } @Test @@ -256,7 +256,7 @@ public void testSimpleRemove2ArgsWithLoaderAndWriter_existsInStore_notEquals() t assertThat(testCache.remove(1, "one"), is(false)); - verifyZeroInteractions(cacheLoaderWriter); + verifyNoInteractions(cacheLoaderWriter); } } diff --git a/integration-test/src/test/java/org/ehcache/integration/OverSizeMappingTest.java b/integration-test/src/test/java/org/ehcache/integration/OverSizeMappingTest.java index efe5d90a5f..7efa3da887 100644 --- a/integration-test/src/test/java/org/ehcache/integration/OverSizeMappingTest.java +++ b/integration-test/src/test/java/org/ehcache/integration/OverSizeMappingTest.java @@ -108,6 +108,7 @@ private static class ObjectSizeGreaterThanN implements Serializable { private final Integer[] arr; + @SuppressWarnings("deprecation") private ObjectSizeGreaterThanN(int n) { arr = new Integer[n]; for (int i = 0; i < arr.length; i++) {