repo
stringlengths
1
191
file
stringlengths
23
351
code
stringlengths
0
5.32M
file_length
int64
0
5.32M
avg_line_length
float64
0
2.9k
max_line_length
int64
0
288k
extension_type
stringclasses
1 value
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/TestsModule.java
package org.infinispan.spring.remote; import org.infinispan.factories.annotations.InfinispanModule; /** * {@code InfinispanModule} annotation is required for component annotation processing */ @InfinispanModule(name = "spring6-remote-tests") public class TestsModule implements org.infinispan.lifecycle.ModuleLifecycle { }
327
28.818182
86
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/AssertionUtils.java
package org.infinispan.spring.remote; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertTrue; import java.util.Properties; public class AssertionUtils { public static void assertPropertiesSubset(String message, Properties expected, Properties actual) { for (String key : expected.stringPropertyNames()) { assertTrue(String.format("%s Key %s missing from %s", message, key, actual), actual.containsKey(key)); assertEquals(String.format("%s Key %s's expected value was \"%s\" but actual was \"%s\"", message, key, expected.getProperty(key), actual.getProperty(key)), expected.getProperty(key), actual.getProperty(key)); } } }
707
43.25
218
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/ConfigurationPropertiesOverridesTest.java
package org.infinispan.spring.remote; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.ASYNC_EXECUTOR_FACTORY; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.FORCE_RETURN_VALUES; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.KEY_SIZE_ESTIMATE; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.MARSHALLER; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.REQUEST_BALANCING_STRATEGY; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.SERVER_LIST; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TCP_KEEP_ALIVE; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TCP_NO_DELAY; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.VALUE_SIZE_ESTIMATE; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.Properties; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.testng.annotations.Test; /** * <p> * Test {@link ConfigurationPropertiesOverrides}. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * */ @Test(groups = "unit", testName = "spring.ConfigurationPropertiesOverridesTest") public class ConfigurationPropertiesOverridesTest { private final Properties defaultConfigurationProperties = new ConfigurationProperties() .getProperties(); @Test public final void testIfIsEmptyRecognizesThatConfigurationPropertiesOverridesAreEmpty() { final ConfigurationPropertiesOverrides objectUnderTest = new ConfigurationPropertiesOverrides(); assertTrue( "isEmpty() should have noticed that the ConfigurationPropertiesOverrides instance is indeed empty. However, it didn't.", objectUnderTest.isEmpty()); } @Test public final void testIfIsEmptyShouldRecognizesThatConfigurationPropertiesOverridesAreNotEmpty() { final ConfigurationPropertiesOverrides objectUnderTest = new ConfigurationPropertiesOverrides(); objectUnderTest.setMarshaller("test.Marshaller"); assertFalse( "isEmpty() should have noticed that the ConfigurationPropertiesOverrides instance is not empty. However, it didn't.", objectUnderTest.isEmpty()); } @Test public final void testIfSetMarshallerOverridesDefaultMarshaller() { final String expectedMarshaller = "test.Marshaller"; final ConfigurationPropertiesOverrides objectUnderTest = new ConfigurationPropertiesOverrides(); objectUnderTest.setMarshaller(expectedMarshaller); final Properties overriddenConfigurationProperties = objectUnderTest .override(this.defaultConfigurationProperties); assertEquals("override(" + this.defaultConfigurationProperties + ") should have overridden property 'transportFactory'. However, it didn't.", expectedMarshaller, overriddenConfigurationProperties.getProperty(MARSHALLER)); } @Test public final void testIfSetServerListOverridesDefaultServerList() { final Collection<InetSocketAddress> expectedServerList = new ArrayList<InetSocketAddress>(1); expectedServerList.add(new InetSocketAddress("testhost", 4632)); final ConfigurationPropertiesOverrides objectUnderTest = new ConfigurationPropertiesOverrides(); final String expectedServerListString = "testhost:4632"; objectUnderTest.setServerList(expectedServerList); final Properties overriddenConfigurationProperties = objectUnderTest .override(this.defaultConfigurationProperties); assertEquals("override(" + this.defaultConfigurationProperties + ") should have overridden property 'transportFactory'. However, it didn't.", expectedServerListString, overriddenConfigurationProperties.getProperty(SERVER_LIST)); } @Test public final void testIfSetAsyncExecutorFactoryOverridesDefaultAsyncExecutorFactory() { final String expectedAsyncExecutorFactory = "test.AsyncExecutorFactor"; final ConfigurationPropertiesOverrides objectUnderTest = new ConfigurationPropertiesOverrides(); objectUnderTest.setAsyncExecutorFactory(expectedAsyncExecutorFactory); final Properties overriddenConfigurationProperties = objectUnderTest .override(this.defaultConfigurationProperties); assertEquals("override(" + this.defaultConfigurationProperties + ") should have overridden property 'transportFactory'. However, it didn't.", expectedAsyncExecutorFactory, overriddenConfigurationProperties.getProperty(ASYNC_EXECUTOR_FACTORY)); } @Test public final void testIfSetTcpNoDelayOverridesDefaultTcpNoDelay() { final boolean expectedTcpNoDelay = true; final ConfigurationPropertiesOverrides objectUnderTest = new ConfigurationPropertiesOverrides(); objectUnderTest.setTcpNoDelay(expectedTcpNoDelay); final Properties overriddenConfigurationProperties = objectUnderTest .override(this.defaultConfigurationProperties); assertEquals("override(" + this.defaultConfigurationProperties + ") should have overridden property 'transportFactory'. However, it didn't.", String.valueOf(expectedTcpNoDelay), overriddenConfigurationProperties.getProperty(TCP_NO_DELAY)); } @Test public final void testIfSetTcpKeepAliveOverridesDefaultTcpKeepAive() { final boolean expectedTcpKeepAlive = false; final ConfigurationPropertiesOverrides objectUnderTest = new ConfigurationPropertiesOverrides(); objectUnderTest.setTcpKeepAlive(expectedTcpKeepAlive); final Properties overriddenConfigurationProperties = objectUnderTest .override(this.defaultConfigurationProperties); assertEquals("override(" + this.defaultConfigurationProperties + ") should have overridden property 'transportFactory'. However, it didn't.", String.valueOf(expectedTcpKeepAlive), overriddenConfigurationProperties.getProperty(TCP_KEEP_ALIVE)); } @Test public final void testIfSetRequestBalancingStrategyOverridesDefaultRequestBalancingStrategy() { final String expectedRequestBalancingStrategy = "test.RequestBalancingStrategy"; final ConfigurationPropertiesOverrides objectUnderTest = new ConfigurationPropertiesOverrides(); objectUnderTest.setRequestBalancingStrategy(expectedRequestBalancingStrategy); final Properties overriddenConfigurationProperties = objectUnderTest .override(this.defaultConfigurationProperties); assertEquals("override(" + this.defaultConfigurationProperties + ") should have overridden property 'transportFactory'. However, it didn't.", expectedRequestBalancingStrategy, overriddenConfigurationProperties.getProperty(REQUEST_BALANCING_STRATEGY)); } @Test public final void testIfSetKeySizeEstimateOverridesDefaultKeySizeEstimate() { final int expectedKeySizeEstimate = -123456; final ConfigurationPropertiesOverrides objectUnderTest = new ConfigurationPropertiesOverrides(); objectUnderTest.setKeySizeEstimate(expectedKeySizeEstimate); final Properties overriddenConfigurationProperties = objectUnderTest .override(this.defaultConfigurationProperties); assertEquals("override(" + this.defaultConfigurationProperties + ") should have overridden property 'transportFactory'. However, it didn't.", String.valueOf(expectedKeySizeEstimate), overriddenConfigurationProperties.getProperty(KEY_SIZE_ESTIMATE)); } @Test public final void testIfValueSizeEstimateOverridesDefaultValueSizeEstimate() { final int expectedValueSizeEstimate = -3456789; final ConfigurationPropertiesOverrides objectUnderTest = new ConfigurationPropertiesOverrides(); objectUnderTest.setValueSizeEstimate(expectedValueSizeEstimate); final Properties overriddenConfigurationProperties = objectUnderTest .override(this.defaultConfigurationProperties); assertEquals("override(" + this.defaultConfigurationProperties + ") should have overridden property 'transportFactory'. However, it didn't.", String.valueOf(expectedValueSizeEstimate), overriddenConfigurationProperties.getProperty(VALUE_SIZE_ESTIMATE)); } @Test public final void testIfForceReturnValuesOverridesDefaultForceReturnValues() { final boolean expectedForceReturnValues = true; final ConfigurationPropertiesOverrides objectUnderTest = new ConfigurationPropertiesOverrides(); objectUnderTest.setForceReturnValues(expectedForceReturnValues); final Properties overriddenConfigurationProperties = objectUnderTest .override(this.defaultConfigurationProperties); assertEquals("override(" + this.defaultConfigurationProperties + ") should have overridden property 'transportFactory'. However, it didn't.", String.valueOf(expectedForceReturnValues), overriddenConfigurationProperties.getProperty(FORCE_RETURN_VALUES)); } }
9,601
49.010417
132
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/config/InfinispanRemoteCacheManagerDefinitionTest.java
package org.infinispan.spring.remote.config; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.cache.CacheManager; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.Assert; import org.testng.annotations.Test; /** * @author Marius Bogoevici */ @Test(groups = {"functional", "smoke"}, testName = "spring.config.InfinispanRemoteCacheManagerDefinitionTest") @ContextConfiguration @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class InfinispanRemoteCacheManagerDefinitionTest extends AbstractTestNGSpringContextTests { @Autowired @Qualifier("cacheManager") private CacheManager remoteCacheManager; @Autowired @Qualifier("withConfigFile") private CacheManager remoteCacheManagerWithConfigFile; @Test public void testRemoteCacheManagerExists() { Assert.assertNotNull(remoteCacheManager); Assert.assertNotNull(remoteCacheManagerWithConfigFile); } }
1,461
36.487179
138
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/session/InfinispanRemoteSessionRepositoryTest.java
package org.infinispan.spring.remote.session; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.test.HotRodTestingUtil; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.spring.common.session.AbstractInfinispanSessionRepository; import org.infinispan.spring.common.session.InfinispanSessionRepositoryTCK; import org.infinispan.spring.remote.provider.BasicConfiguration; import org.infinispan.spring.remote.provider.SpringRemoteCacheManager; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test(testName = "spring.session.InfinispanRemoteSessionRepositoryTest", groups = "functional") @ContextConfiguration(classes = BasicConfiguration.class) @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class InfinispanRemoteSessionRepositoryTest extends InfinispanSessionRepositoryTCK { private EmbeddedCacheManager embeddedCacheManager; private HotRodServer hotrodServer; private RemoteCacheManager remoteCacheManager; private SpringRemoteCacheManager springRemoteCacheManager; @Factory public Object[] factory() { return new Object[]{ new InfinispanRemoteSessionRepositoryTest().mediaType(MediaType.APPLICATION_SERIALIZED_OBJECT), }; } @BeforeClass public void beforeClass() { org.infinispan.configuration.cache.ConfigurationBuilder cacheConfiguration = hotRodCacheConfiguration(mediaType); embeddedCacheManager = TestCacheManagerFactory.createCacheManager(cacheConfiguration); hotrodServer = HotRodTestingUtil.startHotRodServer(embeddedCacheManager, 19723); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host("localhost").port(hotrodServer.getPort()); if (mediaType.equals(MediaType.APPLICATION_SERIALIZED_OBJECT)) { builder.marshaller(JavaSerializationMarshaller.class); } else { builder.marshaller(ProtoStreamMarshaller.class); } remoteCacheManager = new RemoteCacheManager(builder.build()); springRemoteCacheManager = new SpringRemoteCacheManager(remoteCacheManager); } @AfterMethod public void afterMethod() { remoteCacheManager.getCache().clear(); } @AfterClass public void afterClass() { springRemoteCacheManager.stop(); hotrodServer.stop(); embeddedCacheManager.stop(); } @BeforeMethod public void beforeMethod() throws Exception { super.init(); } @Override protected SpringCache createSpringCache() { return springRemoteCacheManager.getCache(""); } @Override protected AbstractInfinispanSessionRepository createRepository(SpringCache springCache) { InfinispanRemoteSessionRepository sessionRepository = new InfinispanRemoteSessionRepository(springCache); sessionRepository.afterPropertiesSet(); return sessionRepository; } @Test(expectedExceptions = NullPointerException.class) @Override public void testThrowingExceptionOnNullSpringCache() throws Exception { super.testThrowingExceptionOnNullSpringCache(); } @Override public void testCreatingSession() throws Exception { super.testCreatingSession(); } @Override public void testSavingNewSession() throws Exception { super.testSavingNewSession(); } @Override public void testDeletingSession() throws Exception { super.testDeletingSession(); } @Override public void testEvictingSession() throws Exception { super.testEvictingSession(); } @Override public void testUpdatingTTLOnAccessingData() throws Exception { super.testUpdatingTTLOnAccessingData(); } }
4,659
36.886179
138
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/session/RemoteApplicationPublishedBridgeTest.java
package org.infinispan.spring.remote.session; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_SERIALIZED_OBJECT; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.infinispan.spring.remote.AbstractRemoteCacheManagerFactory.SPRING_JAVA_SERIAL_ALLOWLIST; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.event.ClientCacheEntryCustomEvent; import org.infinispan.commons.io.UnsignedNumeric; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.test.HotRodTestingUtil; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.spring.common.session.AbstractInfinispanSessionRepository; import org.infinispan.spring.common.session.InfinispanApplicationPublishedBridgeTCK; import org.infinispan.spring.remote.provider.BasicConfiguration; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.infinispan.util.KeyValuePair; import org.springframework.session.MapSession; import org.springframework.session.Session; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(testName = "spring.session.RemoteApplicationPublishedBridgeTest", groups = "unit") @ContextConfiguration(classes = BasicConfiguration.class) @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class RemoteApplicationPublishedBridgeTest extends InfinispanApplicationPublishedBridgeTCK { private EmbeddedCacheManager embeddedCacheManager; private HotRodServer hotrodServer; private RemoteCacheManager remoteCacheManager; @BeforeClass public void beforeClass() { embeddedCacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration(APPLICATION_SERIALIZED_OBJECT)); hotrodServer = HotRodTestingUtil.startHotRodServer(embeddedCacheManager, 19723); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host("localhost").port(hotrodServer.getPort()) .marshaller(new JavaSerializationMarshaller()) .addJavaSerialAllowList(SPRING_JAVA_SERIAL_ALLOWLIST.split(",")); remoteCacheManager = new RemoteCacheManager(builder.build()); } @AfterMethod public void afterMethod() { remoteCacheManager.getCache().clear(); } @AfterClass public void afterClass() { embeddedCacheManager.stop(); remoteCacheManager.stop(); hotrodServer.stop(); } @BeforeMethod public void beforeMethod() throws Exception { super.init(); } @Override protected SpringCache createSpringCache() { return new SpringCache(remoteCacheManager.getCache()); } @Override protected void callEviction() { embeddedCacheManager.getCache().getAdvancedCache().getExpirationManager().processExpiration(); } @Override protected AbstractInfinispanSessionRepository createRepository(SpringCache springCache) { InfinispanRemoteSessionRepository sessionRepository = new InfinispanRemoteSessionRepository(springCache); sessionRepository.afterPropertiesSet(); return sessionRepository; } @Override public void testEventBridge() throws Exception { super.testEventBridge(); } @Override public void testUnregistration() throws Exception { super.testUnregistration(); } public void testReadEventWithoutValue() { RemoteApplicationPublishedBridge remoteApplicationPublishedBridge = new RemoteApplicationPublishedBridge(createSpringCache()); String id = "1234"; ClientCacheEntryCustomEvent<byte[]> event = new TestEvent(id); KeyValuePair<String, Session> keyValuePair = remoteApplicationPublishedBridge.readEvent(event); assertEquals(id, keyValuePair.getKey()); assertNotNull(keyValuePair.getValue()); MapSession value = (MapSession) keyValuePair.getValue(); assertEquals(id, value.getId()); } @Override public void testEventBridgeWithSessionIdChange() throws Exception { super.testEventBridgeWithSessionIdChange(); } class TestEvent implements ClientCacheEntryCustomEvent<byte[]> { private String sessionId; public TestEvent(String sessionId) { this.sessionId = sessionId; } @Override public byte[] getEventData() { RemoteCache cache = remoteCacheManager.getCache(); int keySizeEstimate = cache.getRemoteCacheManager().getConfiguration().keySizeEstimate(); int valueSizeEstimate = cache.getRemoteCacheManager().getConfiguration().valueSizeEstimate(); byte[] key = cache.getDataFormat().keyToBytes(sessionId, keySizeEstimate, valueSizeEstimate); int capacity = UnsignedNumeric.sizeUnsignedInt(key.length) + key.length; byte[] out = new byte[capacity]; int offset = UnsignedNumeric.writeUnsignedInt(out, 0, key.length); System.arraycopy(key, 0, out, offset, key.length); return out; } @Override public boolean isCommandRetried() { return false; } @Override public Type getType() { return null; } } }
5,915
38.704698
138
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/session/InfinispanRemoteProtostreamSessionRepositoryTest.java
package org.infinispan.spring.remote.session; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.test.HotRodTestingUtil; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.spring.common.session.AbstractInfinispanSessionRepository; import org.infinispan.spring.common.session.InfinispanSessionRepositoryTCK; import org.infinispan.spring.remote.provider.BasicConfiguration; import org.infinispan.spring.remote.provider.SpringRemoteCacheManager; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Factory; import org.testng.annotations.Test; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; @Test(testName = "spring.session.InfinispanRemoteProtostreamSessionRepositoryTest", groups = "functional") @ContextConfiguration(classes = BasicConfiguration.class) @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class InfinispanRemoteProtostreamSessionRepositoryTest extends InfinispanSessionRepositoryTCK { private EmbeddedCacheManager embeddedCacheManager; private HotRodServer hotrodServer; private RemoteCacheManager remoteCacheManager; private SpringRemoteCacheManager springRemoteCacheManager; @Factory public Object[] factory() { return new Object[]{ new InfinispanRemoteProtostreamSessionRepositoryTest().mediaType(MediaType.APPLICATION_PROTOSTREAM), }; } @BeforeClass public void beforeClass() { org.infinispan.configuration.cache.ConfigurationBuilder cacheConfiguration = hotRodCacheConfiguration(mediaType); embeddedCacheManager = TestCacheManagerFactory.createCacheManager(cacheConfiguration); hotrodServer = HotRodTestingUtil.startHotRodServer(embeddedCacheManager, 19723); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host("localhost").port(hotrodServer.getPort()); if (mediaType.equals(MediaType.APPLICATION_SERIALIZED_OBJECT)) { builder.marshaller(JavaSerializationMarshaller.class); } else { builder.marshaller(ProtoStreamMarshaller.class); } remoteCacheManager = new RemoteCacheManager(builder.build()); springRemoteCacheManager = new SpringRemoteCacheManager(remoteCacheManager); } @AfterMethod public void afterMethod() { remoteCacheManager.getCache().clear(); } @AfterClass public void afterClass() { springRemoteCacheManager.stop(); hotrodServer.stop(); embeddedCacheManager.stop(); } @BeforeMethod public void beforeMethod() throws Exception { super.init(); } @Override protected SpringCache createSpringCache() { return springRemoteCacheManager.getCache(""); } @Override protected AbstractInfinispanSessionRepository createRepository(SpringCache springCache) { InfinispanRemoteSessionRepository sessionRepository = new InfinispanRemoteSessionRepository(springCache); sessionRepository.afterPropertiesSet(); return sessionRepository; } @Test(expectedExceptions = NullPointerException.class) @Override public void testThrowingExceptionOnNullSpringCache() throws Exception { super.testThrowingExceptionOnNullSpringCache(); } @Override public void testCreatingSession() throws Exception { super.testCreatingSession(); } @Override public void testSavingNewSession() throws Exception { super.testSavingNewSession(); } @Override public void testDeletingSession() throws Exception { super.testDeletingSession(); } @Override public void testEvictingSession() throws Exception { super.testEvictingSession(); } @Override public void testUpdatingTTLOnAccessingData() throws Exception { super.testUpdatingTTLOnAccessingData(); } }
4,686
37.105691
138
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/support/InfinispanRemoteCacheManagerFactoryBeanTest.java
package org.infinispan.spring.remote.support; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.ASYNC_EXECUTOR_FACTORY; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.FORCE_RETURN_VALUES; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.JAVA_SERIAL_ALLOWLIST; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.KEY_SIZE_ESTIMATE; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.MARSHALLER; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.NEAR_CACHE_MODE; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.REQUEST_BALANCING_STRATEGY; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.SERVER_LIST; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TCP_KEEP_ALIVE; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TCP_NO_DELAY; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.VALUE_SIZE_ESTIMATE; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.Properties; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.SomeRequestBalancingStrategy; import org.infinispan.client.hotrod.configuration.NearCacheMode; import org.infinispan.commons.executors.ExecutorFactory; import org.infinispan.commons.marshall.IdentityMarshaller; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.spring.remote.AbstractRemoteCacheManagerFactory; import org.infinispan.spring.remote.AssertionUtils; import org.infinispan.test.AbstractInfinispanTest; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.testng.annotations.Test; /** * <p> * Test {@link AbstractRemoteCacheManagerFactory}. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * */ @Test(testName = "spring.remote.support.InfinispanRemoteCacheManagerFactoryBeanTest", groups = "unit") public class InfinispanRemoteCacheManagerFactoryBeanTest extends AbstractInfinispanTest { private static final Resource HOTROD_CLIENT_PROPERTIES_LOCATION = new ClassPathResource( "hotrod-client.properties", InfinispanRemoteCacheManagerFactoryBeanTest.class); /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanRemoteCacheManagerFactoryBean#afterPropertiesSet()} * . * * @throws Exception */ @Test(expectedExceptions = IllegalStateException.class) public final void shouldThrowAnIllegalStateExceptionIfBothConfigurationPropertiesAndConfigurationPropertiesFileLocationAreSet() throws Exception { final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); objectUnderTest.setConfigurationProperties(new Properties()); objectUnderTest.setConfigurationPropertiesFileLocation(new ClassPathResource("dummy", getClass())); objectUnderTest.afterPropertiesSet(); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanRemoteCacheManagerFactoryBean#afterPropertiesSet()} * . * * @throws Exception */ @Test(expectedExceptions = IllegalStateException.class) public final void shouldThrowAnIllegalStateExceptionIfConfigurationPropertiesAsWellAsSettersAreUsedToConfigureTheRemoteCacheManager() throws Exception { final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); objectUnderTest.setConfigurationProperties(new Properties()); objectUnderTest.setMarshaller("test.Marshaller"); objectUnderTest.afterPropertiesSet(); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanRemoteCacheManagerFactoryBean#getObjectType()} * . * * @throws Exception */ @Test public final void infinispanRemoteCacheFactoryBeanShouldReportTheMostDerivedObjectType() throws Exception { final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); objectUnderTest.afterPropertiesSet(); assertEquals( "getObjectType() should have returned the most derived class of the actual RemoteCache " + "implementation returned from getObject(). However, it didn't.", objectUnderTest.getObject().getClass(), objectUnderTest.getObjectType()); objectUnderTest.destroy(); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanRemoteCacheManagerFactoryBean#getObject()} * . * * @throws Exception */ @Test public final void shouldProduceARemoteCacheManagerConfiguredUsingDefaultSettingsIfNeitherConfigurationPropertiesNorConfigurationPropertiesFileLocationHasBeenSet() throws Exception { final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); objectUnderTest.afterPropertiesSet(); final RemoteCacheManager springRemoteCacheManager = objectUnderTest.getObject(); RemoteCacheManager defaultRemoteCacheManager = new RemoteCacheManager(); // Explicitly set the expected properties on the client defaults, as otherwise the ProtoStream marshaller is expected Properties clientDefaultProps = defaultRemoteCacheManager.getConfiguration().properties(); clientDefaultProps.setProperty(MARSHALLER, JavaSerializationMarshaller.class.getName()); clientDefaultProps.setProperty(JAVA_SERIAL_ALLOWLIST, InfinispanRemoteCacheManagerFactoryBean.SPRING_JAVA_SERIAL_ALLOWLIST); AssertionUtils.assertPropertiesSubset( "The configuration properties used by the RemoteCacheManager returned by getObject() should be equal " + "to RemoteCacheManager's default settings since neither property 'configurationProperties' " + "nor property 'configurationPropertiesFileLocation' has been set. However, those two are not equal.", clientDefaultProps, springRemoteCacheManager.getConfiguration().properties()); objectUnderTest.destroy(); defaultRemoteCacheManager.stop(); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanRemoteCacheManagerFactoryBean#isSingleton()} * . */ @Test public final void isSingletonShouldAlwaysReturnTrue() { final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); assertTrue( "isSingleton() should always return true since each AbstractRemoteCacheManagerFactory will always produce " + "the same RemoteCacheManager instance. However,it returned false.", objectUnderTest.isSingleton()); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanRemoteCacheManagerFactoryBean#destroy()} * . * * @throws Exception */ @Test public final void destroyShouldStopTheProducedCache() throws Exception { final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); objectUnderTest.afterPropertiesSet(); final RemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); objectUnderTest.destroy(); assertFalse( "destroy() should have stopped the RemoteCacheManager instance previously produced by " + "AbstractRemoteCacheManagerFactory. However, the produced RemoteCacheManager is still running. ", remoteCacheManager.isStarted()); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanRemoteCacheManagerFactoryBean#setConfigurationProperties(Properties)} * . * * @throws Exception */ @Test public final void shouldProduceACacheConfiguredUsingTheSuppliedConfigurationProperties() throws Exception { final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); final Properties configurationProperties = loadConfigurationProperties(HOTROD_CLIENT_PROPERTIES_LOCATION); objectUnderTest.setConfigurationProperties(configurationProperties); objectUnderTest.afterPropertiesSet(); final RemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); AssertionUtils.assertPropertiesSubset( "The configuration properties used by the RemoteCacheManager returned by getObject() should be equal " + "to those passed into InfinispanRemoteCacheMangerFactoryBean via setConfigurationProperties(props). " + "However, those two are not equal.", configurationProperties, remoteCacheManager.getConfiguration().properties()); objectUnderTest.destroy(); } private Properties loadConfigurationProperties(final Resource configurationPropertiesLocation) throws IOException { InputStream propsStream = null; try { propsStream = HOTROD_CLIENT_PROPERTIES_LOCATION.getInputStream(); final Properties configurationProperties = new Properties(); configurationProperties.load(propsStream); return configurationProperties; } finally { if (propsStream != null) { propsStream.close(); } } } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanRemoteCacheManagerFactoryBean#setConfigurationPropertiesFileLocation(Resource)} * . */ @Test public final void shouldProduceACacheConfiguredUsingPropertiesLoadedFromALocationDeclaredThroughSetConfigurationPropertiesFileLocation() throws Exception { final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); objectUnderTest.setConfigurationPropertiesFileLocation(HOTROD_CLIENT_PROPERTIES_LOCATION); objectUnderTest.afterPropertiesSet(); final RemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); AssertionUtils.assertPropertiesSubset( "The configuration properties used by the RemoteCacheManager returned by getObject() should be equal " + "to those passed into InfinispanRemoteCacheMangerFactoryBean via setConfigurationPropertiesFileLocation(propsFileLocation). " + "However, those two are not equal.", loadConfigurationProperties(HOTROD_CLIENT_PROPERTIES_LOCATION), remoteCacheManager.getConfiguration().properties()); objectUnderTest.destroy(); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanRemoteCacheManagerFactoryBean#setStartAutomatically(boolean)} * . * * @throws Exception */ @Test public final void shouldProduceAStoppedCacheIfStartAutomaticallyIsSetToFalse() throws Exception { final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); objectUnderTest.setStartAutomatically(false); objectUnderTest.afterPropertiesSet(); final RemoteCacheManager remoteCacheManagerExpectedToBeInStateStopped = objectUnderTest .getObject(); assertFalse( "AbstractRemoteCacheManagerFactory should have produced a RemoteCacheManager that is initially in state stopped " + "since property 'startAutomatically' has been set to false. However, the produced RemoteCacheManager is already started.", remoteCacheManagerExpectedToBeInStateStopped.isStarted()); objectUnderTest.destroy(); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanRemoteCacheManagerFactoryBean#setServerList(Collection)} * . * * @throws Exception */ @Test public final void setServerListShouldOverrideDefaultServerList() throws Exception { final Collection<InetSocketAddress> expectedServerList = new ArrayList<InetSocketAddress>(1); expectedServerList.add(new InetSocketAddress("testhost", 4632)); final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); final String expectedServerListString = "testhost:4632"; objectUnderTest.setServerList(expectedServerList); objectUnderTest.afterPropertiesSet(); final RemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals("setServerList(" + expectedServerList + ") should have overridden property 'serverList'. However, it didn't.", expectedServerListString, remoteCacheManager.getConfiguration().properties().get(SERVER_LIST)); objectUnderTest.destroy(); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanRemoteCacheManagerFactoryBean#setMarshaller(String)} * . * * @throws Exception */ @Test public final void setMarshallerShouldOverrideDefaultMarshaller() throws Exception { final String expectedMarshaller = IdentityMarshaller.class.getName(); final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); objectUnderTest.setMarshaller(expectedMarshaller); objectUnderTest.setStartAutomatically(false); objectUnderTest.afterPropertiesSet(); final RemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals("setMarshaller(" + expectedMarshaller + ") should have overridden property 'marshaller'. However, it didn't.", expectedMarshaller, remoteCacheManager.getConfiguration().properties().get(MARSHALLER)); objectUnderTest.destroy(); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanRemoteCacheManagerFactoryBean#setAsyncExecutorFactory(String)} * . * * @throws Exception */ @Test public final void setAsyncExecutorFactoryShouldOverrideDefaultAsyncExecutorFactory() throws Exception { final String expectedAsyncExecutorFactory = ExecutorFactory.class.getName(); final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); objectUnderTest.setAsyncExecutorFactory(expectedAsyncExecutorFactory); objectUnderTest.setStartAutomatically(false); objectUnderTest.afterPropertiesSet(); final RemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals("setAsyncExecutorFactory(" + expectedAsyncExecutorFactory + ") should have overridden property 'asyncExecutorFactory'. However, it didn't.", expectedAsyncExecutorFactory, remoteCacheManager.getConfiguration().properties().get(ASYNC_EXECUTOR_FACTORY)); objectUnderTest.destroy(); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanRemoteCacheManagerFactoryBean#setTcpNoDelay(boolean)} * . * * @throws Exception */ @Test public final void setTcpNoDelayShouldOverrideDefaultTcpNoDelay() throws Exception { final boolean expectedTcpNoDelay = true; final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); objectUnderTest.setTcpNoDelay(expectedTcpNoDelay); objectUnderTest.afterPropertiesSet(); final RemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals("setTcpNoDelay(" + expectedTcpNoDelay + ") should have overridden property 'tcpNoDelay'. However, it didn't.", String.valueOf(expectedTcpNoDelay), remoteCacheManager.getConfiguration().properties().get(TCP_NO_DELAY)); objectUnderTest.destroy(); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanRemoteCacheManagerFactoryBean#setTcpKeepAlive(boolean)}. * * @throws Exception */ @Test public final void setTcpKeepAliveShouldOverrideDefaultTcpKeepAlive() throws Exception { final boolean expectedTcpKeepAlive = false; final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); objectUnderTest.setTcpNoDelay(expectedTcpKeepAlive); objectUnderTest.afterPropertiesSet(); final RemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals("setTcpKeepAlive(" + expectedTcpKeepAlive + ") should have overridden property 'tcpNoDelay'. However, it didn't.", String.valueOf(expectedTcpKeepAlive), remoteCacheManager.getConfiguration().properties().get(TCP_KEEP_ALIVE)); objectUnderTest.destroy(); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanRemoteCacheManagerFactoryBean#setRequestBalancingStrategy(String)} * . * * @throws Exception */ @Test public final void setRequestBalancingStrategyShouldOverrideDefaultRequestBalancingStrategy() throws Exception { final String expectedRequestBalancingStrategy = SomeRequestBalancingStrategy.class.getName(); final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); objectUnderTest.setRequestBalancingStrategy(expectedRequestBalancingStrategy); objectUnderTest.setStartAutomatically(false); objectUnderTest.afterPropertiesSet(); final RemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals( "setRequestBalancingStrategy(" + expectedRequestBalancingStrategy + ") should have overridden property 'requestBalancingStrategy'. However, it didn't.", expectedRequestBalancingStrategy, remoteCacheManager.getConfiguration().properties().get(REQUEST_BALANCING_STRATEGY)); objectUnderTest.destroy(); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanRemoteCacheManagerFactoryBean#setKeySizeEstimate(int)} * . * * @throws Exception */ @Test public final void setKeySizeEstimateShouldOverrideDefaultKeySizeEstimate() throws Exception { final int expectedKeySizeEstimate = -123456; final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); objectUnderTest.setKeySizeEstimate(expectedKeySizeEstimate); objectUnderTest.afterPropertiesSet(); final RemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals("setKeySizeEstimate(" + expectedKeySizeEstimate + ") should have overridden property 'keySizeEstimate'. However, it didn't.", String.valueOf(expectedKeySizeEstimate), remoteCacheManager.getConfiguration().properties().get(KEY_SIZE_ESTIMATE)); objectUnderTest.destroy(); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanRemoteCacheManagerFactoryBean#setValueSizeEstimate(int)} * . * * @throws Exception */ @Test public final void setValueSizeEstimateShouldOverrideDefaultValueSizeEstimate() throws Exception { final int expectedValueSizeEstimate = -3456789; final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); objectUnderTest.setValueSizeEstimate(expectedValueSizeEstimate); objectUnderTest.afterPropertiesSet(); final RemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals("setValueSizeEstimate(" + expectedValueSizeEstimate + ") should have overridden property 'valueSizeEstimate'. However, it didn't.", String.valueOf(expectedValueSizeEstimate), remoteCacheManager.getConfiguration().properties().get(VALUE_SIZE_ESTIMATE)); objectUnderTest.destroy(); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanRemoteCacheManagerFactoryBean#setForceReturnValues(boolean)} * . * * @throws Exception */ @Test public final void setForceReturnValuesShouldOverrideDefaultForceReturnValues() throws Exception { final boolean expectedForceReturnValues = true; final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); objectUnderTest.setForceReturnValues(expectedForceReturnValues); objectUnderTest.afterPropertiesSet(); final RemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals("setForceReturnValue(" + expectedForceReturnValues + ") should have overridden property 'forceReturnValue'. However, it didn't.", String.valueOf(expectedForceReturnValues), remoteCacheManager.getConfiguration().properties().get(FORCE_RETURN_VALUES)); objectUnderTest.destroy(); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanRemoteCacheManagerFactoryBean#setNearCacheMode(String)} * * @throws Exception */ @Test public final void setNearCacheModeShouldOverrideDefaultNearCacheMode() throws Exception { final NearCacheMode expectedNearCacheMode = NearCacheMode.INVALIDATED; final InfinispanRemoteCacheManagerFactoryBean objectUnderTest = new InfinispanRemoteCacheManagerFactoryBean(); objectUnderTest.setNearCacheMode(expectedNearCacheMode.name()); objectUnderTest.setNearCacheMaxEntries(100); objectUnderTest.afterPropertiesSet(); final RemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals("setNearCacheMode(" + expectedNearCacheMode + ") should have overridden property 'nearCacheMode'. However, it didn't.", expectedNearCacheMode.name(), remoteCacheManager.getConfiguration().properties().get(NEAR_CACHE_MODE)); objectUnderTest.destroy(); } }
22,794
45.050505
165
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/support/InfinispanRemoteCacheManagerFactoryBeanContextTest.java
package org.infinispan.spring.remote.support; import static org.testng.AssertJUnit.assertNotNull; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.annotations.Test; /** * <p> * Test {@link InfinispanRemoteCacheManagerFactoryBean} deployed in a Spring application context. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * */ @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @ContextConfiguration("classpath:/org/infinispan/spring/remote/support/InfinispanRemoteCacheManagerFactoryBeanContextTest.xml") @Test(testName = "spring.support.remote.InfinispanRemoteCacheManagerFactoryBeanContextTest", groups = "unit") @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class InfinispanRemoteCacheManagerFactoryBeanContextTest extends AbstractTestNGSpringContextTests { private static final String INFINISPAN_REMOTE_CACHE_MANAGER_WITH_DEFAULT_CONFIGURATION_BEAN_NAME = "infinispanRemoteCacheManagerWithDefaultConfiguration"; private static final String INFINISPAN_REMOTE_CACHE_MANAGER_CONFIGURED_FROM_CONFIGURATION_PROPERTIES_FILE_BEAN_NAME = "infinispanRemoteCacheManagerConfiguredFromConfigurationPropertiesFile"; private static final String INFINISPAN_REMOTE_CACHE_MANAGER_CONFIGURED_FROM_CONFIGURATION_PROPERTIES_BEAN_NAME = "infinispanRemoteCacheManagerConfiguredFromConfigurationProperties"; private static final String INFINISPAN_REMOTE_CACHE_MANAGER_CONFIGURED_USING_SETTERS_BEAN_NAME = "infinispanRemoteCacheManagerConfiguredUsingSetters"; @Test public final void shouldCreateARemoteCacheManagerWithDefaultSettingsIfNoFurtherConfigurationGiven() { final RemoteCacheManager infinispanRemoteCacheManagerWithDefaultConfiguration = this.applicationContext .getBean(INFINISPAN_REMOTE_CACHE_MANAGER_WITH_DEFAULT_CONFIGURATION_BEAN_NAME, RemoteCacheManager.class); assertNotNull( "Spring application context should contain a RemoteCacheManager with default settings having bean name = \"" + INFINISPAN_REMOTE_CACHE_MANAGER_WITH_DEFAULT_CONFIGURATION_BEAN_NAME + "\". However, it doesn't.", infinispanRemoteCacheManagerWithDefaultConfiguration); } @Test public final void shouldCreateARemoteCacheManagerConfiguredFromConfigurationPropertiesFileIfConfigurationPropertiesFileLocationGiven() { final RemoteCacheManager infinispanRemoteCacheManagerConfiguredFromConfigurationFile = this.applicationContext .getBean(INFINISPAN_REMOTE_CACHE_MANAGER_CONFIGURED_FROM_CONFIGURATION_PROPERTIES_FILE_BEAN_NAME, RemoteCacheManager.class); assertNotNull( "Spring application context should contain a RemoteCacheManager configured from configuration properties file having bean name = \"" + INFINISPAN_REMOTE_CACHE_MANAGER_CONFIGURED_FROM_CONFIGURATION_PROPERTIES_FILE_BEAN_NAME + "\". However, it doesn't.", infinispanRemoteCacheManagerConfiguredFromConfigurationFile); } @Test public final void shouldCreateARemoteCacheManagerConfiguredFromConfigurationPropertiesIfConfigurationPropertiesGiven() { final RemoteCacheManager infinispanRemoteCacheManagerConfiguredFromConfigurationProperties = this.applicationContext .getBean(INFINISPAN_REMOTE_CACHE_MANAGER_CONFIGURED_FROM_CONFIGURATION_PROPERTIES_BEAN_NAME, RemoteCacheManager.class); assertNotNull( "Spring application context should contain a RemoteCacheManager configured from configuration properties having bean name = \"" + INFINISPAN_REMOTE_CACHE_MANAGER_CONFIGURED_FROM_CONFIGURATION_PROPERTIES_BEAN_NAME + "\". However, it doesn't.", infinispanRemoteCacheManagerConfiguredFromConfigurationProperties); } @Test public final void shouldCreateARemoteCacheManagerConfiguredUsingSettersIfPropertiesAreDefined() { final RemoteCacheManager infinispanRemoteCacheManagerConfiguredUsingSetters = this.applicationContext .getBean(INFINISPAN_REMOTE_CACHE_MANAGER_CONFIGURED_USING_SETTERS_BEAN_NAME, RemoteCacheManager.class); assertNotNull( "Spring application context should contain a SpringRemoteCacheManager configured using properties having bean name = \"" + INFINISPAN_REMOTE_CACHE_MANAGER_CONFIGURED_USING_SETTERS_BEAN_NAME + "\". However, it doesn't.", infinispanRemoteCacheManagerConfiguredUsingSetters); } }
5,099
56.954545
193
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/support/InfinispanNamedRemoteCacheFactoryBeanTest.java
package org.infinispan.spring.remote.support; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.test.HotRodTestingUtil; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * <p> * Test {@link InfinispanNamedRemoteCacheFactoryBean}. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * */ @Test(testName = "spring.support.remote.InfinispanNamedRemoteCacheFactoryBeanTest", groups = "functional") public class InfinispanNamedRemoteCacheFactoryBeanTest extends SingleCacheManagerTest { private static final String TEST_BEAN_NAME = "test.bean.Name"; private static final String TEST_CACHE_NAME = "test.cache.Name"; private RemoteCacheManager remoteCacheManager; private HotRodServer hotrodServer; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration()); cacheManager.defineConfiguration(TEST_CACHE_NAME, cacheManager.getDefaultCacheConfiguration()); cache = cacheManager.getCache(TEST_CACHE_NAME); cacheManager.defineConfiguration(TEST_BEAN_NAME, cacheManager.getDefaultCacheConfiguration()); cache = cacheManager.getCache(TEST_BEAN_NAME); return cacheManager; } @BeforeClass public void setupRemoteCacheFactory() { hotrodServer = HotRodTestingUtil.startHotRodServer(cacheManager, 19733); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host("localhost").port(hotrodServer.getPort()); remoteCacheManager = new RemoteCacheManager(builder.build()); } @AfterClass(alwaysRun = true) public void destroyRemoteCacheFactory() { remoteCacheManager.stop(); hotrodServer.stop(); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanNamedRemoteCacheFactoryBean#afterPropertiesSet()} * . * * @throws Exception */ @Test(expectedExceptions = IllegalStateException.class) public final void infinispanNamedRemoteCacheFactoryBeanShouldRecognizeThatNoCacheContainerHasBeenSet() throws Exception { final InfinispanNamedRemoteCacheFactoryBean<String, Object> objectUnderTest = new InfinispanNamedRemoteCacheFactoryBean<String, Object>(); objectUnderTest.setCacheName(TEST_CACHE_NAME); objectUnderTest.setBeanName(TEST_BEAN_NAME); objectUnderTest.afterPropertiesSet(); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanNamedRemoteCacheFactoryBean#setBeanName(String)} * . * * @throws Exception */ @Test public final void infinispanNamedRemoteCacheFactoryBeanShouldUseBeanNameAsCacheNameIfNoCacheNameHasBeenSet() throws Exception { final String beanName = TEST_BEAN_NAME; final InfinispanNamedRemoteCacheFactoryBean<String, Object> objectUnderTest = new InfinispanNamedRemoteCacheFactoryBean<String, Object>(); objectUnderTest.setInfinispanRemoteCacheManager(remoteCacheManager); objectUnderTest.setBeanName(beanName); objectUnderTest.afterPropertiesSet(); final RemoteCache<String, Object> cache = objectUnderTest.getObject(); assertEquals("InfinispanNamedRemoteCacheFactoryBean should have used its bean name [" + beanName + "] as the name of the created cache. However, it didn't.", beanName, cache.getName()); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanNamedRemoteCacheFactoryBean#setCacheName(String)} * . * * @throws Exception */ @Test public final void infinispanNamedRemoteCacheFactoryBeanShouldPreferExplicitCacheNameToBeanName() throws Exception { final InfinispanNamedRemoteCacheFactoryBean<String, Object> objectUnderTest = new InfinispanNamedRemoteCacheFactoryBean<String, Object>(); objectUnderTest.setInfinispanRemoteCacheManager(remoteCacheManager); objectUnderTest.setCacheName(TEST_CACHE_NAME); objectUnderTest.setBeanName(TEST_BEAN_NAME); objectUnderTest.afterPropertiesSet(); final RemoteCache<String, Object> cache = objectUnderTest.getObject(); assertEquals("InfinispanNamedRemoteCacheFactoryBean should have preferred its cache name [" + TEST_CACHE_NAME + "] as the name of the created cache. However, it didn't.", TEST_CACHE_NAME, cache.getName()); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanNamedRemoteCacheFactoryBean#getObjectType()}. * * @throws Exception */ @Test public final void infinispanNamedRemoteCacheFactoryBeanShouldReportTheMostDerivedObjectType() throws Exception { final InfinispanNamedRemoteCacheFactoryBean<Object, Object> objectUnderTest = new InfinispanNamedRemoteCacheFactoryBean<Object, Object>(); objectUnderTest.setInfinispanRemoteCacheManager(remoteCacheManager); objectUnderTest.setBeanName(TEST_BEAN_NAME); objectUnderTest.afterPropertiesSet(); assertEquals( "getObjectType() should have returned the most derived class of the actual Cache " + "implementation returned from getObject(). However, it didn't.", objectUnderTest.getObject().getClass(), objectUnderTest.getObjectType()); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanNamedRemoteCacheFactoryBean#getObject()}. * * @throws Exception */ @Test public final void infinispanNamedRemoteCacheFactoryBeanShouldProduceANonNullInfinispanCache() throws Exception { final InfinispanNamedRemoteCacheFactoryBean<String, Object> objectUnderTest = new InfinispanNamedRemoteCacheFactoryBean<String, Object>(); objectUnderTest.setInfinispanRemoteCacheManager(remoteCacheManager); objectUnderTest.setCacheName(TEST_CACHE_NAME); objectUnderTest.setBeanName(TEST_BEAN_NAME); objectUnderTest.afterPropertiesSet(); final RemoteCache<String, Object> cache = objectUnderTest.getObject(); assertNotNull( "InfinispanNamedRemoteCacheFactoryBean should have produced a proper Infinispan cache. " + "However, it produced a null Infinispan cache.", cache); } /** * Test method for * {@link org.infinispan.spring.remote.support.InfinispanNamedRemoteCacheFactoryBean#isSingleton()}. */ @Test public final void infinispanNamedRemoteCacheFactoryBeanShouldDeclareItselfToBeSingleton() { final InfinispanNamedRemoteCacheFactoryBean<String, Object> objectUnderTest = new InfinispanNamedRemoteCacheFactoryBean<String, Object>(); assertTrue( "InfinispanNamedRemoteCacheFactoryBean should declare itself to produce a singleton. However, it didn't.", objectUnderTest.isSingleton()); } }
7,622
40.884615
144
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/support/HotrodServerLifecycleBean.java
package org.infinispan.spring.remote.support; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; /** * HotrodServerLifecycleBean. * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @since 5.1 */ public class HotrodServerLifecycleBean implements InitializingBean, DisposableBean { private EmbeddedCacheManager cacheManager; private RemoteCacheManager remoteCacheManager; private HotRodServer hotrodServer; private String remoteCacheName; public void setRemoteCacheName(String remoteCacheName) { this.remoteCacheName = remoteCacheName; } @Override public void afterPropertiesSet() throws Exception { cacheManager = TestCacheManagerFactory.createCacheManager(false); hotrodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host("localhost").port(hotrodServer.getPort()); remoteCacheManager = new RemoteCacheManager(builder.build()); } @Override public void destroy() throws Exception { remoteCacheManager.stop(); hotrodServer.stop(); cacheManager.stop(); } }
1,600
32.354167
84
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/support/InfinispanNamedRemoteCacheFactoryBeanContextTest.java
package org.infinispan.spring.remote.support; import org.infinispan.Cache; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import static org.testng.AssertJUnit.assertNotNull; /** * <p> * Test {@link InfinispanNamedRemoteCacheFactoryBean} deployed in a Spring application context. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * */ @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @ContextConfiguration("classpath:/org/infinispan/spring/remote/support/InfinispanNamedRemoteCacheFactoryBeanContextTest.xml") //@Test(testName = "spring.support.remote.InfinispanNamedRemoteCacheFactoryBeanContextTest", groups = "functional") @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class InfinispanNamedRemoteCacheFactoryBeanContextTest extends AbstractTestNGSpringContextTests { private static final String INFINISPAN_NAMED_REMOTE_CACHE_WITHOUT_FURTHER_CONFIGURATION_BEAN_NAME = "infinispanNamedRemoteCacheWithoutFurtherConfiguration"; // @Test public final void shouldCreateARemoteCacheWithDefaultSettingsIfNoFurtherConfigurationGiven() { final Cache<Object, Object> infinispanNamedRemoteCacheWithoutFurtherConfiguration = this.applicationContext .getBean(INFINISPAN_NAMED_REMOTE_CACHE_WITHOUT_FURTHER_CONFIGURATION_BEAN_NAME, Cache.class); assertNotNull( "Spring application context should contain a named Infinispan cache having bean name = \"" + INFINISPAN_NAMED_REMOTE_CACHE_WITHOUT_FURTHER_CONFIGURATION_BEAN_NAME + "\". However, it doesn't.", infinispanNamedRemoteCacheWithoutFurtherConfiguration); } }
2,122
49.547619
159
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/provider/SpringRemoteCacheManagerFactoryBeanTest.java
package org.infinispan.spring.remote.provider; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.ASYNC_EXECUTOR_FACTORY; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.FORCE_RETURN_VALUES; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.JAVA_SERIAL_ALLOWLIST; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.KEY_SIZE_ESTIMATE; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.MARSHALLER; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.REQUEST_BALANCING_STRATEGY; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.SERVER_LIST; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TCP_KEEP_ALIVE; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TCP_NO_DELAY; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.VALUE_SIZE_ESTIMATE; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertTrue; import java.io.IOException; import java.io.InputStream; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.Properties; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.SomeRequestBalancingStrategy; import org.infinispan.commons.executors.ExecutorFactory; import org.infinispan.commons.marshall.IdentityMarshaller; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.spring.remote.AssertionUtils; import org.infinispan.test.AbstractInfinispanTest; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * <p> * Test {@link SpringRemoteCacheManagerFactoryBean}. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * */ @Test(testName = "spring.remote.provider.SpringRemoteCacheManagerFactoryBeanTest", groups = "unit") public class SpringRemoteCacheManagerFactoryBeanTest extends AbstractInfinispanTest { private static final Resource HOTROD_CLIENT_PROPERTIES_LOCATION = new ClassPathResource( "hotrod-client.properties", SpringRemoteCacheManagerFactoryBeanTest.class); private SpringRemoteCacheManagerFactoryBean objectUnderTest; @AfterMethod(alwaysRun = true) public void afterMethod() throws Exception { if (objectUnderTest != null) { objectUnderTest.destroy(); } } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean#afterPropertiesSet()} * . * * @throws Exception */ @Test(expectedExceptions = IllegalStateException.class) public final void shouldThrowAnIllegalStateExceptionIfBothConfigurationPropertiesAndConfifurationPropertiesFileLocationAreSet() throws Exception { objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); objectUnderTest.setConfigurationProperties(new Properties()); objectUnderTest.setConfigurationPropertiesFileLocation(new ClassPathResource("dummy", getClass())); objectUnderTest.afterPropertiesSet(); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean#afterPropertiesSet()} * . * * @throws Exception */ @Test(expectedExceptions = IllegalStateException.class) public final void shouldThrowAnIllegalStateExceptionIfConfigurationPropertiesAsWellAsSettersAreUsedToConfigureTheRemoteCacheManager() throws Exception { objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); objectUnderTest.setConfigurationProperties(new Properties()); objectUnderTest.setMarshaller("test.Marshaller"); objectUnderTest.afterPropertiesSet(); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean#getObjectType()}. * * @throws Exception */ @Test public final void infinispanRemoteCacheFactoryBeanShouldReportTheMostDerivedObjectType() throws Exception { objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); objectUnderTest.afterPropertiesSet(); assertEquals( "getObjectType() should have returned the most derived class of the actual RemoteCache " + "implementation returned from getObject(). However, it didn't.", objectUnderTest.getObject().getClass(), objectUnderTest.getObjectType()); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean#getObject()}. * * @throws Exception */ @Test public final void shouldProduceARemoteCacheManagerConfiguredUsingDefaultSettingsIfNeitherConfigurationPropertiesNorConfigurationPropertiesFileLocationHasBeenSet() throws Exception { objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); objectUnderTest.afterPropertiesSet(); final SpringRemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); RemoteCacheManager defaultRemoteCacheManager = new RemoteCacheManager(); // Explicitly set the expected properties on the client defaults, as otherwise the ProtoStream marshaller is expected Properties clientDefaultProps = defaultRemoteCacheManager.getConfiguration().properties(); clientDefaultProps.setProperty(MARSHALLER, JavaSerializationMarshaller.class.getName()); clientDefaultProps.setProperty(JAVA_SERIAL_ALLOWLIST, SpringRemoteCacheManagerFactoryBean.SPRING_JAVA_SERIAL_ALLOWLIST); try { AssertionUtils.assertPropertiesSubset( "The configuration properties used by the SpringRemoteCacheManager returned von getObject() should be equal " + "to SpringRemoteCacheManager's default settings since neither property 'configurationProperties' " + "nor property 'configurationPropertiesFileLocation' has been set. However, those two are not equal.", clientDefaultProps, remoteCacheManager.getNativeCacheManager().getConfiguration().properties()); } finally { defaultRemoteCacheManager.stop(); } } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean#isSingleton()}. */ @Test public final void isSingletonShouldAlwaysReturnTrue() { objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); assertTrue( "isSingleton() should always return true since each SpringRemoteCacheManagerFactoryBean will always produce " + "the same SpringRemoteCacheManager instance. However,it returned false.", objectUnderTest.isSingleton()); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean#destroy()}. * * @throws Exception */ @Test public final void destroyShouldStopTheProducedCache() throws Exception { objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); objectUnderTest.afterPropertiesSet(); final SpringRemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); objectUnderTest.destroy(); assertFalse( "destroy() should have stopped the SpringRemoteCacheManager instance previously produced by " + "SpringRemoteCacheManagerFactoryBean. However, the produced SpringRemoteCacheManager is still running. ", remoteCacheManager.getNativeCacheManager().isStarted()); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean#setConfigurationProperties(Properties)} * . * * @throws Exception */ @Test public final void shouldProduceACacheConfiguredUsingTheSuppliedConfigurationProperties() throws Exception { objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); final Properties configurationProperties = loadConfigurationProperties(HOTROD_CLIENT_PROPERTIES_LOCATION); objectUnderTest.setConfigurationProperties(configurationProperties); objectUnderTest.afterPropertiesSet(); final SpringRemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); AssertionUtils.assertPropertiesSubset( "The configuration properties used by the SpringRemoteCacheManager returned von getObject() should be equal " + "to those passed into SpringRemoteCacheManagerFactoryBean via setConfigurationProperties(props). " + "However, those two are not equal.", configurationProperties, remoteCacheManager.getNativeCacheManager().getConfiguration().properties()); } private Properties loadConfigurationProperties(final Resource configurationPropertiesLocation) throws IOException { InputStream propsStream = null; try { propsStream = HOTROD_CLIENT_PROPERTIES_LOCATION.getInputStream(); final Properties configurationProperties = new Properties(); configurationProperties.load(propsStream); return configurationProperties; } finally { if (propsStream != null) { propsStream.close(); } } } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean#setConfigurationPropertiesFileLocation(Resource)} * . */ @Test public final void shouldProduceACacheConfiguredUsingPropertiesLoadedFromALocationDeclaredThroughSetConfigurationPropertiesFileLocation() throws Exception { objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); objectUnderTest.setConfigurationPropertiesFileLocation(HOTROD_CLIENT_PROPERTIES_LOCATION); objectUnderTest.afterPropertiesSet(); final SpringRemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); AssertionUtils.assertPropertiesSubset( "The configuration properties used by the SpringRemoteCacheManager returned von getObject() should be equal " + "to those passed into SpringRemoteCacheManagerFactoryBean via setConfigurationPropertiesFileLocation(propsFileLocation). " + "However, those two are not equal.", loadConfigurationProperties(HOTROD_CLIENT_PROPERTIES_LOCATION), remoteCacheManager .getNativeCacheManager().getConfiguration().properties()); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean#setStartAutomatically(boolean)} * . * * @throws Exception */ @Test public final void shouldProduceAStoppedCacheIfStartAutomaticallyIsSetToFalse() throws Exception { objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); objectUnderTest.setStartAutomatically(false); objectUnderTest.afterPropertiesSet(); final SpringRemoteCacheManager remoteCacheManagerExpectedToBeInStateStopped = objectUnderTest .getObject(); assertFalse( "SpringRemoteCacheManagerFactoryBean should have produced a SpringRemoteCacheManager that is initially in state stopped " + "since property 'startAutomatically' has been set to false. However, the produced SpringRemoteCacheManager is already started.", remoteCacheManagerExpectedToBeInStateStopped.getNativeCacheManager().isStarted()); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean#setServerList(Collection)} * . * * @throws Exception */ @Test public final void setServerListShouldOverrideDefaultServerList() throws Exception { final Collection<InetSocketAddress> expectedServerList = new ArrayList<InetSocketAddress>(1); expectedServerList.add(new InetSocketAddress("testhost", 4632)); objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); final String expectedServerListString = "testhost:4632"; objectUnderTest.setServerList(expectedServerList); objectUnderTest.afterPropertiesSet(); final SpringRemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals("setServerList(" + expectedServerList + ") should have overridden property 'serverList'. However, it didn't.", expectedServerListString, remoteCacheManager.getNativeCacheManager().getConfiguration().properties() .get(SERVER_LIST)); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean#setMarshaller(String)} * . * * @throws Exception */ @Test public final void setMarshallerShouldOverrideDefaultMarshaller() throws Exception { final String expectedMarshaller = IdentityMarshaller.class.getName(); objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); objectUnderTest.setMarshaller(expectedMarshaller); objectUnderTest.setStartAutomatically(false); objectUnderTest.afterPropertiesSet(); final SpringRemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals("setMarshaller(" + expectedMarshaller + ") should have overridden property 'marshaller'. However, it didn't.", expectedMarshaller, remoteCacheManager.getNativeCacheManager().getConfiguration().properties().get(MARSHALLER)); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean#setAsyncExecutorFactory(String)} * . * * @throws Exception */ @Test public final void setAsyncExecutorFactoryShouldOverrideDefaultAsyncExecutorFactory() throws Exception { final String expectedAsyncExecutorFactory = ExecutorFactory.class.getName(); objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); objectUnderTest.setAsyncExecutorFactory(expectedAsyncExecutorFactory); objectUnderTest.setStartAutomatically(false); objectUnderTest.afterPropertiesSet(); final SpringRemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals("setAsyncExecutorFactory(" + expectedAsyncExecutorFactory + ") should have overridden property 'asyncExecutorFactory'. However, it didn't.", expectedAsyncExecutorFactory, remoteCacheManager.getNativeCacheManager() .getConfiguration().properties().get(ASYNC_EXECUTOR_FACTORY)); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean#setTcpNoDelay(boolean)} * . * * @throws Exception */ @Test public final void setTcpNoDelayShouldOverrideDefaultTcpNoDelay() throws Exception { final boolean expectedTcpNoDelay = true; objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); objectUnderTest.setTcpNoDelay(expectedTcpNoDelay); objectUnderTest.afterPropertiesSet(); final SpringRemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals("setTcpNoDelay(" + expectedTcpNoDelay + ") should have overridden property 'tcpNoDelay'. However, it didn't.", String.valueOf(expectedTcpNoDelay), remoteCacheManager.getNativeCacheManager() .getConfiguration().properties().get(TCP_NO_DELAY)); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean#setTcpNoDelay(boolean)} * . * * @throws Exception */ @Test public final void setTcpKeepAliveOverrideDefaultTcpKeepAlive() throws Exception { final boolean expectedTcpKeepAlive = false; objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); objectUnderTest.setTcpKeepAlive(expectedTcpKeepAlive); objectUnderTest.afterPropertiesSet(); final SpringRemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals("setTcpKeepAlive(" + expectedTcpKeepAlive + ") should have overridden property 'tcpKeepAlive'. However, it didn't.", String.valueOf(expectedTcpKeepAlive), remoteCacheManager.getNativeCacheManager() .getConfiguration().properties().get(TCP_KEEP_ALIVE)); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean#setRequestBalancingStrategy(String)} * . * * @throws Exception */ @Test public final void setRequestBalancingStrategyShouldOverrideDefaultRequestBalancingStrategy() throws Exception { final String expectedRequestBalancingStrategy = SomeRequestBalancingStrategy.class.getName(); objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); objectUnderTest.setRequestBalancingStrategy(expectedRequestBalancingStrategy); objectUnderTest.setStartAutomatically(false); objectUnderTest.afterPropertiesSet(); final SpringRemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals( "setRequestBalancingStrategy(" + expectedRequestBalancingStrategy + ") should have overridden property 'requestBalancingStrategy'. However, it didn't.", expectedRequestBalancingStrategy, remoteCacheManager.getNativeCacheManager() .getConfiguration().properties().get(REQUEST_BALANCING_STRATEGY)); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean#setKeySizeEstimate(int)} * . * * @throws Exception */ @Test public final void setKeySizeEstimateShouldOverrideDefaultKeySizeEstimate() throws Exception { final int expectedKeySizeEstimate = -123456; objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); objectUnderTest.setKeySizeEstimate(expectedKeySizeEstimate); objectUnderTest.afterPropertiesSet(); final SpringRemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals("setKeySizeEstimate(" + expectedKeySizeEstimate + ") should have overridden property 'keySizeEstimate'. However, it didn't.", String.valueOf(expectedKeySizeEstimate), remoteCacheManager.getNativeCacheManager() .getConfiguration().properties().get(KEY_SIZE_ESTIMATE)); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean#setValueSizeEstimate(int)} * . * * @throws Exception */ @Test public final void setValueSizeEstimateShouldOverrideDefaultValueSizeEstimate() throws Exception { final int expectedValueSizeEstimate = -3456789; objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); objectUnderTest.setValueSizeEstimate(expectedValueSizeEstimate); objectUnderTest.afterPropertiesSet(); final SpringRemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals("setValueSizeEstimate(" + expectedValueSizeEstimate + ") should have overridden property 'valueSizeEstimate'. However, it didn't.", String.valueOf(expectedValueSizeEstimate), remoteCacheManager .getNativeCacheManager().getConfiguration().properties().get(VALUE_SIZE_ESTIMATE)); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean#setForceReturnValues(boolean)} * . * * @throws Exception */ @Test public final void setForceReturnValuesShouldOverrideDefaultForceReturnValues() throws Exception { final boolean expectedForceReturnValues = true; objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); objectUnderTest.setForceReturnValues(expectedForceReturnValues); objectUnderTest.afterPropertiesSet(); final SpringRemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals("setForceReturnValue(" + expectedForceReturnValues + ") should have overridden property 'forceReturnValue'. However, it didn't.", String.valueOf(expectedForceReturnValues), remoteCacheManager .getNativeCacheManager().getConfiguration().properties().get(FORCE_RETURN_VALUES)); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean#setForceReturnValues(boolean)} * . * * @throws Exception */ @Test public final void setReadTimeoutShouldOverrideDefaultReadTimeout() throws Exception { final long expectedReadTimeout = 500; objectUnderTest = new SpringRemoteCacheManagerFactoryBean(); objectUnderTest.setReadTimeout(expectedReadTimeout); objectUnderTest.afterPropertiesSet(); final SpringRemoteCacheManager remoteCacheManager = objectUnderTest.getObject(); assertEquals("setReadTimeout(" + expectedReadTimeout + ") should have overridden property 'readTimeout'. However, it didn't.", expectedReadTimeout, remoteCacheManager.getReadTimeout()); } }
21,670
43.498973
165
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/provider/SpringRemoteCacheManagerWithReadWriteTimeoutTest.java
package org.infinispan.spring.remote.provider; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.commands.read.GetCacheEntryCommand; import org.infinispan.commands.write.PutKeyValueCommand; import org.infinispan.commons.CacheException; import org.infinispan.context.InvocationContext; import org.infinispan.interceptors.DDAsyncInterceptor; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.core.admin.embeddedserver.EmbeddedServerAdminOperationHandler; import org.infinispan.server.core.test.ServerTestingUtil; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.infinispan.server.hotrod.test.HotRodTestingUtil; import org.infinispan.commons.test.Exceptions; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.springframework.cache.Cache; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; /** * <p> * Test {@link SpringRemoteCacheManagerWithReadWriteTimeoutTest}. * </p> * * @author Tristan Tarrant */ @Test(testName = "spring.provider.SpringRemoteCacheManagerWithReadWriteTimeoutTest", groups = {"functional", "smoke"}) public class SpringRemoteCacheManagerWithReadWriteTimeoutTest extends SingleCacheManagerTest { private static final String TEST_CACHE_NAME = "spring.remote.cache.manager.Test"; private RemoteCacheManager remoteCacheManager; private HotRodServer hotrodServer; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration()); cacheManager.defineConfiguration(TEST_CACHE_NAME, cacheManager.getDefaultCacheConfiguration()); cache = cacheManager.getCache(TEST_CACHE_NAME); return cacheManager; } @BeforeClass public void setupRemoteCacheFactory() { HotRodServerConfigurationBuilder serverBuilder = new HotRodServerConfigurationBuilder(); serverBuilder.adminOperationsHandler(new EmbeddedServerAdminOperationHandler()); hotrodServer = HotRodTestingUtil.startHotRodServer(cacheManager, ServerTestingUtil.findFreePort(), serverBuilder); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host("localhost").port(hotrodServer.getPort()); remoteCacheManager = new RemoteCacheManager(builder.build()); } @AfterClass public void destroyRemoteCacheFactory() { remoteCacheManager.stop(); hotrodServer.stop(); } /** * Test method for {@link SpringRemoteCacheManager#getCache(String)}. */ @Test public final void springRemoteCacheManagerWithTimeoutShouldThrowTimeoutExceptions() { final SpringRemoteCacheManager objectUnderTest = new SpringRemoteCacheManager( remoteCacheManager, 500, 750); final Cache defaultCache = objectUnderTest.getCache(TEST_CACHE_NAME); assertEquals("getCache(" + TEST_CACHE_NAME + ") should have returned a cache name \"" + TEST_CACHE_NAME + "\". However, the returned cache has a different name.", TEST_CACHE_NAME, defaultCache.getName()); defaultCache.put("k1", "v1"); CountDownLatch latch = new CountDownLatch(1); cacheManager.getCache(TEST_CACHE_NAME).getAdvancedCache().getAsyncInterceptorChain() .addInterceptor(new DelayingInterceptor(latch, 700, 800), 0); Exceptions.expectException(CacheException.class, TimeoutException.class, () -> defaultCache.get("k1")); Exceptions.expectException(CacheException.class, TimeoutException.class, () -> defaultCache.put("k1", "v2")); } static class DelayingInterceptor extends DDAsyncInterceptor { private final long readDelay; private final long writeDelay; private final CountDownLatch latch; private DelayingInterceptor(CountDownLatch latch, long readDelay, long writeDelay) { this.latch = latch; this.readDelay = readDelay; this.writeDelay = writeDelay; } @Override public Object visitGetCacheEntryCommand(InvocationContext ctx, GetCacheEntryCommand command) throws Throwable { latch.await(readDelay, TimeUnit.MILLISECONDS); return super.visitGetCacheEntryCommand(ctx, command); } public Object visitPutKeyValueCommand(InvocationContext ctx, PutKeyValueCommand command) throws Throwable { latch.await(writeDelay, TimeUnit.MILLISECONDS); return super.visitPutKeyValueCommand(ctx, command); } } }
5,022
41.210084
120
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/provider/SpringRemoteCacheManagerFactoryBeanContextTest.java
package org.infinispan.spring.remote.provider; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.annotations.Test; /** * <p> * Test {@link SpringRemoteCacheManagerFactoryBean} deployed in a Spring application context. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * */ @Test(testName = "spring.provider.SpringRemoteCacheManagerFactoryBeanContextTest", groups = "unit") @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @ContextConfiguration("classpath:/org/infinispan/spring/remote/provider/SpringRemoteCacheManagerFactoryBeanContextTest.xml") @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class SpringRemoteCacheManagerFactoryBeanContextTest extends AbstractTestNGSpringContextTests { private static final String SPRING_REMOTE_CACHE_MANAGER_WITH_DEFAULT_CONFIGURATION_BEAN_NAME = "springRemoteCacheManagerWithDefaultConfiguration"; private static final String SPRING_REMOTE_CACHE_MANAGER_CONFIGURED_FROM_CONFIGURATION_PROPERTIES_FILE_BEAN_NAME = "springRemoteCacheManagerConfiguredFromConfigurationPropertiesFile"; private static final String SPRING_REMOTE_CACHE_MANAGER_CONFIGURED_USING_CONFIGURATION_PROPERTIES_BEAN_NAME = "springRemoteCacheManagerConfiguredUsingConfigurationProperties"; private static final String SPRING_REMOTE_CACHE_MANAGER_CONFIGURED_USING_SETTERS_BEAN_NAME = "springRemoteCacheManagerConfiguredUsingSetters"; @Test public final void shouldCreateARemoteCacheManagerWithDefaultSettingsIfNoFurtherConfigurationGiven() { final SpringRemoteCacheManager springRemoteCacheManagerWithDefaultConfiguration = this.applicationContext .getBean(SPRING_REMOTE_CACHE_MANAGER_WITH_DEFAULT_CONFIGURATION_BEAN_NAME, SpringRemoteCacheManager.class); assertNotNull( "Spring application context should contain a SpringRemoteCacheManager with default settings having bean name = \"" + SPRING_REMOTE_CACHE_MANAGER_WITH_DEFAULT_CONFIGURATION_BEAN_NAME + "\". However, it doesn't.", springRemoteCacheManagerWithDefaultConfiguration); } @Test public final void shouldCreateARemoteCacheManagerConfiguredFromConfigurationFileIfConfigurationFileLocationGiven() { final SpringRemoteCacheManager springRemoteCacheManagerConfiguredFromConfigurationFile = this.applicationContext .getBean(SPRING_REMOTE_CACHE_MANAGER_CONFIGURED_FROM_CONFIGURATION_PROPERTIES_FILE_BEAN_NAME, SpringRemoteCacheManager.class); assertNotNull( "Spring application context should contain a SpringRemoteCacheManager configured from configuration file having bean name = \"" + SPRING_REMOTE_CACHE_MANAGER_CONFIGURED_FROM_CONFIGURATION_PROPERTIES_FILE_BEAN_NAME + "\". However, it doesn't.", springRemoteCacheManagerConfiguredFromConfigurationFile); } @Test public final void shouldCreateARemoteCacheManagerConfiguredUsingConfigurationPropertiesSetInApplicationContext() { final SpringRemoteCacheManager springRemoteCacheManagerConfiguredUsingConfigurationProperties = this.applicationContext .getBean(SPRING_REMOTE_CACHE_MANAGER_CONFIGURED_USING_CONFIGURATION_PROPERTIES_BEAN_NAME, SpringRemoteCacheManager.class); assertNotNull( "Spring application context should contain a SpringRemoteCacheManager configured using configuration properties set in application context having bean name = \"" + SPRING_REMOTE_CACHE_MANAGER_CONFIGURED_USING_CONFIGURATION_PROPERTIES_BEAN_NAME + "\". However, it doesn't.", springRemoteCacheManagerConfiguredUsingConfigurationProperties); assertEquals(500, springRemoteCacheManagerConfiguredUsingConfigurationProperties.getReadTimeout()); assertEquals(700, springRemoteCacheManagerConfiguredUsingConfigurationProperties.getWriteTimeout()); } @Test public final void shouldCreateARemoteCacheManagerConfiguredUsingSettersIfPropertiesAreDefined() { final SpringRemoteCacheManager springRemoteCacheManagerConfiguredUsingSetters = this.applicationContext .getBean(SPRING_REMOTE_CACHE_MANAGER_CONFIGURED_USING_SETTERS_BEAN_NAME, SpringRemoteCacheManager.class); assertNotNull( "Spring application context should contain a SpringRemoteCacheManager configured using properties having bean name = \"" + SPRING_REMOTE_CACHE_MANAGER_CONFIGURED_USING_SETTERS_BEAN_NAME + "\". However, it doesn't.", springRemoteCacheManagerConfiguredUsingSetters); } }
5,254
57.388889
185
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/provider/BasicConfiguration.java
package org.infinispan.spring.remote.provider; import org.springframework.context.annotation.Configuration; @Configuration public class BasicConfiguration { }
161
19.25
60
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/provider/SpringRemoteCacheTest.java
package org.infinispan.spring.remote.provider; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.commons.marshall.UTF8StringMarshaller; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.test.HotRodTestingUtil; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.springframework.cache.Cache; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @Test(testName = "spring.provider.SpringRemoteCacheTest", groups = "functional") public class SpringRemoteCacheTest extends SingleCacheManagerTest { private static final String TEST_CACHE_NAME = "SerializationCache"; private static final String TEST_CACHE_NAME_PROTO = "ProtoStreamCache"; private RemoteCacheManager remoteCacheManager; private HotRodServer hotrodServer; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration()); cacheManager.defineConfiguration(TEST_CACHE_NAME, hotRodCacheConfiguration(MediaType.APPLICATION_SERIALIZED_OBJECT).build()); cacheManager.defineConfiguration(TEST_CACHE_NAME_PROTO, hotRodCacheConfiguration(MediaType.APPLICATION_PROTOSTREAM).build()); cache = cacheManager.getCache(TEST_CACHE_NAME); return cacheManager; } @BeforeClass public void setupRemoteCacheFactory() { hotrodServer = HotRodTestingUtil.startHotRodServer(cacheManager, 0); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host("localhost").port(hotrodServer.getPort()); builder.remoteCache(TEST_CACHE_NAME).marshaller(JavaSerializationMarshaller.class); builder.remoteCache(TEST_CACHE_NAME_PROTO).marshaller(ProtoStreamMarshaller.class); remoteCacheManager = new RemoteCacheManager(builder.build()); } @AfterClass public void destroyRemoteCacheFactory() { remoteCacheManager.stop(); hotrodServer.stop(); } /* * In this test Thread 1 should exclusively block Cache#get method so that Thread 2 won't be able to * insert "thread2" string into the cache. * * The test check this part of the Spring spec: * Return the value to which this cache maps the specified key, obtaining that value from valueLoader if necessary. * This method provides a simple substitute for the conventional "if cached, return; otherwise create, cache and return" pattern. * @see http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/cache/Cache.html#get-java.lang.Object-java.util.concurrent.Callable- */ @Test(timeOut = 30_000) public void testValueLoaderWithLocking() throws Exception { //given final SpringRemoteCacheManager springRemoteCacheManager = new SpringRemoteCacheManager(remoteCacheManager); final SpringCache cache = springRemoteCacheManager.getCache(TEST_CACHE_NAME); CountDownLatch waitUntilThread1LocksValueGetter = new CountDownLatch(1); //when Future<String> thread1 = fork(() -> cache.get("test", () -> { waitUntilThread1LocksValueGetter.countDown(); // /TimeUnit.MILLISECONDS.sleep(10); return "thread1"; })); Future<String> thread2 = fork(() -> { waitUntilThread1LocksValueGetter.await(); return cache.get("test", () -> "thread2"); }); String valueObtainedByThread1 = thread1.get(); String valueObtainedByThread2 = thread2.get(); Cache.ValueWrapper valueAfterGetterIsDone = cache.get("test"); //then assertNotNull(valueAfterGetterIsDone); assertEquals("thread1", valueAfterGetterIsDone.get()); assertEquals("thread1", valueObtainedByThread1); assertEquals("thread1", valueObtainedByThread2); } @DataProvider(name = "caches") public Object[][] caches() { return new Object[][] { {TEST_CACHE_NAME}, {TEST_CACHE_NAME_PROTO}, }; } @Test(dataProvider = "caches") public void testNullValues(String cacheName) { //given final SpringRemoteCacheManager springRemoteCacheManager = new SpringRemoteCacheManager(remoteCacheManager); final SpringCache cache = springRemoteCacheManager.getCache(cacheName); // when cache.put("key", null); // then Cache.ValueWrapper valueWrapper = cache.get("key"); assertNotNull(valueWrapper); assertNull(valueWrapper.get()); if (cacheName.equals(TEST_CACHE_NAME_PROTO)) { // The server should be able to convert application/x-protostream to application/json RemoteCache<?, ?> nativeCache = (RemoteCache<?, ?>) cache.getNativeCache(); RemoteCache<Object, Object> jsonCache = nativeCache.withDataFormat(DataFormat.builder() .valueType(MediaType.APPLICATION_JSON) .valueMarshaller(new UTF8StringMarshaller()) .build()); Object jsonValue = jsonCache.get("key"); assertEquals("{\"_type\":\"org.infinispan.commons.NullValue\"}", jsonValue); } } }
6,235
42.305556
153
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/provider/SpringRemoteCacheManagerTest.java
package org.infinispan.spring.remote.provider; import static org.infinispan.server.hotrod.test.HotRodTestingUtil.hotRodCacheConfiguration; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertFalse; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNotSame; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertSame; import static org.testng.AssertJUnit.assertTrue; import java.io.IOException; import java.util.Collection; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.configuration.ConfigurationBuilder; import org.infinispan.commons.api.CacheContainerAdmin; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.core.admin.embeddedserver.EmbeddedServerAdminOperationHandler; import org.infinispan.server.core.test.ServerTestingUtil; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.infinispan.server.hotrod.test.HotRodTestingUtil; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.springframework.cache.Cache; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; /** * <p> * Test {@link SpringRemoteCacheManager}. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @author Marius Bogoevici * */ @Test(testName = "spring.provider.SpringRemoteCacheManagerTest", groups = {"functional", "smoke"}) public class SpringRemoteCacheManagerTest extends SingleCacheManagerTest { private static final String TEST_CACHE_NAME = "spring.remote.cache.manager.Test"; private static final String OTHER_TEST_CACHE_NAME = "spring.remote.cache.manager.OtherTest"; private RemoteCacheManager remoteCacheManager; private HotRodServer hotrodServer; private SpringRemoteCacheManager objectUnderTest; @Override protected EmbeddedCacheManager createCacheManager() throws Exception { cacheManager = TestCacheManagerFactory.createCacheManager(hotRodCacheConfiguration()); cacheManager.defineConfiguration(OTHER_TEST_CACHE_NAME, cacheManager.getDefaultCacheConfiguration()); return cacheManager; } @BeforeMethod public void createCache(){ if(objectUnderTest != null) { objectUnderTest.start(); } cacheManager.administration().removeCache(TEST_CACHE_NAME); cacheManager.undefineConfiguration(TEST_CACHE_NAME); cacheManager.defineConfiguration(TEST_CACHE_NAME, cacheManager.getDefaultCacheConfiguration()); cache = cacheManager.administration().withFlags(CacheContainerAdmin.AdminFlag.VOLATILE).getOrCreateCache(TEST_CACHE_NAME, TEST_CACHE_NAME); objectUnderTest = new SpringRemoteCacheManager(remoteCacheManager); } @AfterMethod(alwaysRun = true) public void afterMethod() { if (objectUnderTest != null) { objectUnderTest.stop(); } } @BeforeClass public void setupRemoteCacheFactory() { HotRodServerConfigurationBuilder serverBuilder = new HotRodServerConfigurationBuilder(); serverBuilder.adminOperationsHandler(new EmbeddedServerAdminOperationHandler()); hotrodServer = HotRodTestingUtil.startHotRodServer(cacheManager, ServerTestingUtil.findFreePort(), serverBuilder); ConfigurationBuilder builder = new ConfigurationBuilder(); builder.addServer().host("localhost").port(hotrodServer.getPort()); remoteCacheManager = new RemoteCacheManager(builder.build()); } @AfterClass(alwaysRun = true) public void destroyRemoteCacheFactory() { remoteCacheManager.stop(); hotrodServer.stop(); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManager#SpringRemoteCacheManager(RemoteCacheManager)} * . */ @Test(expectedExceptions = IllegalArgumentException.class) public final void springRemoteCacheManagerConstructorShouldRejectNullRemoteCacheManager() { new SpringRemoteCacheManager(null); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManager#getCache(String)}. */ @Test public final void springRemoteCacheManagerShouldProperlyCreateCache() { final Cache defaultCache = objectUnderTest.getCache(TEST_CACHE_NAME); assertNotNull("getCache(" + TEST_CACHE_NAME + ") should have returned a default cache. However, it returned null.", defaultCache); assertEquals("getCache(" + TEST_CACHE_NAME + ") should have returned a cache name \"" + TEST_CACHE_NAME + "\". However, the returned cache has a different name.", TEST_CACHE_NAME, defaultCache.getName()); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManager#getCacheNames()}. */ @Test public final void getCacheNamesShouldReturnAllCachesDefinedInConfigurationFile() { final Collection<String> cacheNames = objectUnderTest.getCacheNames(); assertTrue("SpringRemoteCacheManager should load all named caches found in the " + "native cache manager. However, it does not know about the cache named " + TEST_CACHE_NAME + " defined in said cache manager.", cacheNames.contains(TEST_CACHE_NAME)); } /** * Test method for {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManager#start()}. * * @throws IOException */ @Test public final void startShouldStartTheNativeRemoteCacheManager() throws IOException { objectUnderTest.start(); assertTrue("Calling start() on SpringRemoteCacheManager should start the enclosed " + "Infinispan RemoteCacheManager. However, it is still not running.", remoteCacheManager.isStarted()); } /** * Test method for {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManager#stop()}. * * @throws IOException */ @Test public final void stopShouldStopTheNativeRemoteCacheManager() throws IOException { objectUnderTest.stop(); assertFalse("Calling stop() on SpringRemoteCacheManager should stop the enclosed " + "Infinispan RemoteCacheManager. However, it is still running.", remoteCacheManager.isStarted()); } /** * Test method for * {@link org.infinispan.spring.remote.provider.SpringRemoteCacheManager#getNativeCacheManager()}. * */ @Test public final void getNativeCacheShouldReturnTheRemoteCacheManagerSuppliedAtConstructionTime() { final RemoteCacheManager nativeCacheManagerReturned = objectUnderTest.getNativeCacheManager(); assertSame( "getNativeCacheManager() should have returned the RemoteCacheManager supplied at construction time. However, it retuned a different one.", remoteCacheManager, nativeCacheManagerReturned); } @Test public final void getCacheShouldReturnSameInstanceForSameName() { // When final SpringCache firstObtainedSpringCache = objectUnderTest.getCache(TEST_CACHE_NAME); final SpringCache secondObtainedSpringCache = objectUnderTest.getCache(TEST_CACHE_NAME); // Then assertSame( "getCache() should have returned the same SpringCache instance for the same name", firstObtainedSpringCache, secondObtainedSpringCache); } @Test public final void getCacheShouldReturnDifferentInstancesForDifferentNames() { // When final SpringCache firstObtainedSpringCache = objectUnderTest.getCache(TEST_CACHE_NAME); final SpringCache secondObtainedSpringCache = objectUnderTest.getCache(OTHER_TEST_CACHE_NAME); // Then assertNotSame( "getCache() should have returned different SpringCache instances for different names", firstObtainedSpringCache, secondObtainedSpringCache); } @Test public final void getCacheReturnsDifferentInstanceForSameNameAfterLifecycleStop() { final SpringCache firstObtainedSpringCache = objectUnderTest.getCache(TEST_CACHE_NAME); // When objectUnderTest.stop(); final SpringCache secondObtainedSpringCache = objectUnderTest.getCache(TEST_CACHE_NAME); // Then assertNotSame( "getCache() should have returned different SpringCache instances for the sam name after a Lifecycle#stop()", firstObtainedSpringCache, secondObtainedSpringCache); } @Test public final void getCacheShouldReturnNullItWasChangedByRemoteCacheManager() { // When objectUnderTest.getCache(TEST_CACHE_NAME); remoteCacheManager.administration().removeCache(TEST_CACHE_NAME); // Then assertNull(objectUnderTest.getCache(TEST_CACHE_NAME)); } }
9,170
39.223684
150
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/provider/sample/AbstractTestTemplate.java
package org.infinispan.spring.remote.provider.sample; import java.lang.invoke.MethodHandles; import java.util.Random; import org.infinispan.commons.api.BasicCache; import org.infinispan.spring.remote.provider.sample.entity.Book; import org.infinispan.spring.remote.provider.sample.service.CachedBookService; import org.infinispan.spring.remote.provider.sample.service.CachedBookServiceImpl; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.springframework.cache.CacheManager; import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Abstract template for running a set of tests under different configurations, in order to illustrate how Spring handles * the caching aspects we added to {@link CachedBookServiceImpl <code>CachedBookServiceImpl</code>}. * It calls each method defined in the class and verifies that book instances are indeed cached and removed from the * cache as specified. * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @author Marius Bogoevici * @author Matej Cimbora (mcimbora@redhat.com) */ @Test(groups = "functional") public abstract class AbstractTestTemplate extends AbstractTransactionalTestNGSpringContextTests { protected static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); @AfterMethod public void clearBookCache() { booksCache().clear(); backupCache().clear(); } /** * Demonstrates that loading a {@link Book <code>book</code>} via * {@link CachedBookServiceImpl#findBook(Integer)} does indeed cache * the returned book instance under the supplied bookId. */ @Test public void demonstrateCachingLoadedBooks() { final Integer bookToCacheId = Integer.valueOf(5); assert !booksCache().containsKey(bookToCacheId) : "Cache should not initially contain the book with id " + bookToCacheId; final Book cachedBook = getBookService().findBook(bookToCacheId); this.log.infof("Book [%s] cached", cachedBook); assert cachedBook.equals(booksCache().get(bookToCacheId)) : "findBook(" + bookToCacheId + ") should have cached book"; } /** * Demonstrate that removing a {@link Book <code>book</code>} from database via * {@link CachedBookServiceImpl#deleteBook(Integer)} does indeed remove * it from cache also. */ @Test public void demonstrateRemovingBookFromCache() { final Integer bookToDeleteId = Integer.valueOf(new Random().nextInt(10) + 1); assert !booksCache().containsKey(bookToDeleteId) : "Cache should not initially contain the book with id " + bookToDeleteId; final Book bookToDelete = getBookService().findBook(bookToDeleteId); this.log.infof("Book [%s] cached", bookToDelete); assert booksCache().get(bookToDeleteId).equals(bookToDelete) : "findBook(" + bookToDeleteId + ") should have cached book"; this.log.infof("Deleting book [%s] ...", bookToDelete); getBookService().deleteBook(bookToDeleteId); this.log.infof("Book [%s] deleted", bookToDelete); assert !booksCache().containsKey(bookToDeleteId) : "deleteBook(" + bookToDelete + ") should have evicted book from cache."; } /** * Demonstrates that updating a {@link Book <code>book</code>} that has already been persisted to * database via {@link CachedBookServiceImpl (Book)} does indeed evict * that book from cache. */ @Test public void demonstrateCacheEvictionUponUpdate() { final Integer bookToUpdateId = Integer.valueOf(2); assert !booksCache().containsKey(bookToUpdateId): "Cache should not initially contain the book with id " + bookToUpdateId; this.log.infof("Caching book [ID = %d]", bookToUpdateId); final Book bookToUpdate = getBookService().findBook(bookToUpdateId); assert booksCache().get(bookToUpdateId).equals(bookToUpdate) : "findBook(" + bookToUpdateId + ") should have cached book"; this.log.infof("Updating book [%s] ...", bookToUpdate); bookToUpdate.setTitle("Work in Progress"); getBookService().updateBook(bookToUpdate); this.log.infof("Book [%s] updated", bookToUpdate); assert !booksCache().containsKey(bookToUpdateId) : "updateBook(" + bookToUpdate + ") should have removed updated book from cache"; } /** * Demonstrates that creating a new {@link Book <code>book</code>} via * {@link CachedBookServiceImpl#createBook(Book)} * does indeed cache returned book under its generated id. */ @Test public void demonstrateCachePutOnCreate() { final Book bookToCreate = new Book("112-358-132", "Random Author", "Path to Infinispan Enlightenment"); this.log.infof("Creating book [%s] ...", bookToCreate); getBookService().createBook(bookToCreate); this.log.infof("Book [%s] created", bookToCreate); assert booksCache().get(bookToCreate.getId()).equals(bookToCreate) : "createBook(" + bookToCreate + ") should have inserted created book into cache"; } @Test public void testFindCustomCacheResolver() { final Integer bookToCacheId = Integer.valueOf(5); assert !getCache("custom").containsKey(bookToCacheId): "Cache should not initially contain the book with id " + bookToCacheId; final Book cachedBook = getBookService().findBookCustomCacheResolver(bookToCacheId); this.log.infof("Book [%s] cached", cachedBook); assert cachedBook.equals(getCache("custom").get(bookToCacheId)) : "findBook(" + bookToCacheId + ") should have cached book"; } @Test public void testFindCustomKeyGenerator() { final Integer bookToCacheId = Integer.valueOf(5); assert !booksCache().containsKey(bookToCacheId): "Cache should not initially contain the book with id " + bookToCacheId; final Book cachedBook = getBookService().findBookCustomKeyGenerator(bookToCacheId); this.log.infof("Book [%s] cached", cachedBook); assert cachedBook.equals(booksCache().get(bookToCacheId)) : "findBook(" + bookToCacheId + ") should have cached book"; } @Test public void testFindConditionMet() { final Integer bookToCacheId = Integer.valueOf(5); assert !booksCache().containsKey(bookToCacheId): "Cache should not initially contain the book with id " + bookToCacheId; final Book cachedBook = getBookService().findBookCondition(bookToCacheId); this.log.infof("Book [%s] cached", cachedBook); assert cachedBook.equals(booksCache().get(bookToCacheId)) : "findBook(" + bookToCacheId + ") should have cached book"; } @Test public void testFindConditionNotMet() { final Integer bookToCacheId = Integer.valueOf(1); assert !booksCache().containsKey(bookToCacheId): "Cache should not initially contain the book with id " + bookToCacheId; final Book cachedBook = getBookService().findBookCondition(bookToCacheId); this.log.infof("Book [%s] cached", cachedBook); assert !booksCache().containsKey(bookToCacheId) : "findBook(" + bookToCacheId + ") should not have cached book"; } @Test public void testFindUnlessMet() { final Integer bookToCacheId = Integer.valueOf(1); assert !booksCache().containsKey(bookToCacheId): "Cache should not initially contain the book with id " + bookToCacheId; final Book cachedBook = getBookService().findBookUnless(bookToCacheId); this.log.infof("Book [%s] cached", cachedBook); assert cachedBook.equals(booksCache().get(bookToCacheId)) : "findBook(" + bookToCacheId + ") should have cached book"; } @Test public void testFindUnlessNotMet() { final Integer bookToCacheId = Integer.valueOf(5); assert !booksCache().containsKey(bookToCacheId): "Cache should not initially contain the book with id " + bookToCacheId; final Book cachedBook = getBookService().findBookUnless(bookToCacheId); this.log.infof("Book [%s] cached", cachedBook); assert !booksCache().containsKey(bookToCacheId) : "findBook(" + bookToCacheId + ") should not have cached book"; } @Test public void testFindCustomCacheManager() { final Integer bookToCacheId = Integer.valueOf(5); assert !booksCache().containsKey(bookToCacheId): "Cache should not initially contain the book with id " + bookToCacheId; final Book cachedBook = getBookService().findBookCustomCacheManager(bookToCacheId); this.log.infof("Book [%s] cached", cachedBook); assert cachedBook.equals(booksCache().get(bookToCacheId)) : "findBook(" + bookToCacheId + ") should have cached book"; } @Test public void testCreateCustomCacheManager() { final Book bookToCreate = new Book("112-358-132", "Random Author", "Path to Infinispan Enlightenment"); this.log.infof("Creating book [%s] ...", bookToCreate); getBookService().createBookCustomCacheManager(bookToCreate); this.log.infof("Book [%s] created", bookToCreate); assert bookToCreate.equals(booksCache().get(bookToCreate.getId())) : "createBook(" + bookToCreate + ") should have inserted created book into cache"; } @Test public void testCreateCustomCacheResolver() { final Book bookToCreate = new Book("112-358-132", "Random Author", "Path to Infinispan Enlightenment"); this.log.infof("Creating book [%s] ...", bookToCreate); getBookService().createBookCustomCacheResolver(bookToCreate); this.log.infof("Book [%s] created", bookToCreate); assert bookToCreate.equals(getCache("custom").get(bookToCreate.getId())) : "createBook(" + bookToCreate + ") should have inserted created book into cache"; } @Test public void testCreateCustomKeyGenerator() { final Book bookToCreate = new Book("112-358-132", "Random Author", "Path to Infinispan Enlightenment"); this.log.infof("Creating book [%s] ...", bookToCreate); getBookService().createBookCustomKeyGenerator(bookToCreate); this.log.infof("Book [%s] created", bookToCreate); assert booksCache().containsKey(bookToCreate) : "createBook(" + bookToCreate + ") should have inserted created book into cache"; } @Test public void testCreateConditionMet() { final Book bookToCreate = new Book("112-358-132", "Random Author", "Path to Infinispan Enlightenment"); this.log.infof("Creating book [%s] ...", bookToCreate); Book result = getBookService().createBookCondition(bookToCreate); this.log.infof("Book [%s] created", bookToCreate); assert bookToCreate.equals(booksCache().get(result.getId())) : "createBook(" + bookToCreate + ") should have inserted created book into cache"; } @Test public void testCreateConditionNotMet() { final Book bookToCreate = new Book("112-358-132", "Random Author", "Wrong Path to Infinispan Enlightenment"); this.log.infof("Creating book [%s] ...", bookToCreate); getBookService().createBookCondition(bookToCreate); this.log.infof("Book [%s] created", bookToCreate); assert bookToCreate.getId() != null : "Book.id should have been set."; assert !booksCache().containsKey(bookToCreate.getId()) : "createBook(" + bookToCreate + ") should not have inserted created book into cache"; } @Test public void testCreateUnlessMet() { final Book bookToCreate = new Book("99-999-999", "Random Author", "Path to Infinispan Enlightenment"); this.log.infof("Creating book [%s] ...", bookToCreate); getBookService().createBookUnless(bookToCreate); this.log.infof("Book [%s] created", bookToCreate); assert bookToCreate.equals(booksCache().get(bookToCreate.getId())) : "createBook(" + bookToCreate + ") should have inserted created book into cache"; } @Test public void testCreateUnlessNotMet() { final Book bookToCreate = new Book("112-358-132", "Random Author", "Path to Infinispan Enlightenment"); this.log.infof("Creating book [%s] ...", bookToCreate); getBookService().createBookUnless(bookToCreate); this.log.infof("Book [%s] created", bookToCreate); assert !booksCache().containsKey(bookToCreate.getId()) : "createBook(" + bookToCreate + ") should not have inserted created book into cache"; } @Test public void testDeleteCustomCacheResolver() { final Integer bookToDeleteId = Integer.valueOf(new Random().nextInt(10) + 1); assert !getCache("custom").containsKey(bookToDeleteId): "Cache should not initially contain the book with id " + bookToDeleteId; final Book bookToDelete = getBookService().findBookCustomCacheResolver(bookToDeleteId); this.log.infof("Book [%s] cached", bookToDelete); assert bookToDelete.getId() != null : "Book.id should have been set."; assert bookToDelete.equals(getCache("custom").get(bookToDelete.getId())) : "findBook(" + bookToDeleteId + ") should have cached book"; this.log.infof("Deleting book [%s] ...", bookToDelete); getBookService().deleteBookCustomCacheResolver(bookToDeleteId); this.log.infof("Book [%s] deleted", bookToDelete); assert !getCache("custom").containsKey(bookToDelete.getId()) : "deleteBook(" + bookToDelete + ") should have evicted book from cache."; } @Test public void testDeleteCustomKeyGenerator() { final Integer bookToDeleteId = Integer.valueOf(new Random().nextInt(10) + 1); assert !booksCache().containsKey(bookToDeleteId): "Cache should not initially contain the book with id " + bookToDeleteId; final Book bookToDelete = getBookService().findBook(bookToDeleteId); this.log.infof("Book [%s] cached", bookToDelete); assert bookToDelete.equals(booksCache().get(bookToDeleteId)) : "findBook(" + bookToDeleteId + ") should have cached book"; this.log.infof("Deleting book [%s] ...", bookToDelete); getBookService().deleteBookCustomKeyGenerator(bookToDeleteId); this.log.infof("Book [%s] deleted", bookToDelete); assert !booksCache().containsKey(bookToDelete.getId()) : "deleteBook(" + bookToDelete + ") should have evicted book from cache."; } @Test public void testDeleteConditionMet() { final Integer bookToDeleteId = Integer.valueOf(2); assert !booksCache().containsKey(bookToDeleteId): "Cache should not initially contain the book with id " + bookToDeleteId; final Book bookToDelete = getBookService().findBook(bookToDeleteId); this.log.infof("Book [%s] cached", bookToDelete); assert bookToDelete.equals(booksCache().get(bookToDeleteId)) : "findBook(" + bookToDeleteId + ") should have cached book"; this.log.infof("Deleting book [%s] ...", bookToDelete); getBookService().deleteBookCondition(bookToDeleteId); this.log.infof("Book [%s] deleted", bookToDelete); assert !booksCache().containsKey(bookToDelete.getId()) : "deleteBook(" + bookToDelete + ") should have evicted book from cache."; } @Test public void testDeleteConditionNotMet() { final Integer bookToDeleteId = Integer.valueOf(1); assert !booksCache().containsKey(bookToDeleteId): "Cache should not initially contain the book with id " + bookToDeleteId; final Book bookToDelete = getBookService().findBook(bookToDeleteId); this.log.infof("Book [%s] cached", bookToDelete); assert bookToDelete.equals(booksCache().get(bookToDeleteId)) : "findBook(" + bookToDeleteId + ") should have cached book"; this.log.infof("Deleting book [%s] ...", bookToDelete); getBookService().deleteBookCondition(bookToDeleteId); this.log.infof("Book [%s] deleted", bookToDelete); assert bookToDelete.equals(booksCache().get(bookToDeleteId)) : "deleteBook(" + bookToDelete + ") should have evicted book from cache."; } @Test public void testDeleteAllEntries() { final Integer bookToDeleteId1 = Integer.valueOf(5); final Integer bookToDeleteId2 = Integer.valueOf(6); assert !booksCache().containsKey(bookToDeleteId1): "Cache should not initially contain the book with id " + bookToDeleteId1; assert !booksCache().containsKey(bookToDeleteId2): "Cache should not initially contain the book with id " + bookToDeleteId2; final Book bookToDelete1 = getBookService().findBook(bookToDeleteId1); this.log.infof("Book [%s] cached", bookToDelete1); assert bookToDelete1.equals(booksCache().get(bookToDeleteId1)) : "findBook(" + bookToDeleteId1 + ") should have cached book"; final Book bookToDelete2 = getBookService().findBook(bookToDeleteId2); this.log.infof("Book [%s] cached", bookToDelete2); assert bookToDelete2.equals(booksCache().get(bookToDeleteId2)) : "findBook(" + bookToDeleteId2 + ") should have cached book"; this.log.infof("Deleting book [%s] ...", bookToDelete1); getBookService().deleteBookAllEntries(bookToDeleteId1); this.log.infof("Book [%s] deleted", bookToDelete1); assert !booksCache().containsKey(bookToDelete1.getId()) : "deleteBook(" + bookToDelete1 + ") should have evicted book from cache."; assert !booksCache().containsKey(bookToDelete2.getId()) : "deleteBook(" + bookToDelete2 + ") should have evicted book from cache."; } @Test public void testDeleteCustomCacheManager() { final Integer bookToDeleteId = Integer.valueOf(new Random().nextInt(10) + 1); assert !booksCache().containsKey(bookToDeleteId): "Cache should not initially contain the book with id " + bookToDeleteId; final Book bookToDelete = getBookService().findBookCustomCacheManager(bookToDeleteId); this.log.infof("Book [%s] cached", bookToDelete); assert bookToDelete.getId() != null : "Book.id should have been set."; assert bookToDelete.equals(booksCache().get(bookToDelete.getId())) : "findBook(" + bookToDeleteId + ") should have cached book"; this.log.infof("Deleting book [%s] ...", bookToDelete); getBookService().deleteBookCustomCacheManager(bookToDeleteId); this.log.infof("Book [%s] deleted", bookToDelete); assert !booksCache().containsKey(bookToDelete.getId()) : "deleteBook(" + bookToDelete + ") should have evicted book from cache."; } @Test public void testDeleteBookBeforeInvocation() { final Integer bookToDeleteId = Integer.valueOf(new Random().nextInt(10) + 1); assert !booksCache().containsKey(bookToDeleteId): "Cache should not initially contain the book with id " + bookToDeleteId; final Book bookToDelete = getBookService().findBook(bookToDeleteId); this.log.infof("Book [%s] cached", bookToDelete); assert bookToDelete.equals(booksCache().get(bookToDelete.getId())) : "findBook(" + bookToDeleteId + ") should have cached book"; this.log.infof("Deleting book [%s] ...", bookToDelete); try { getBookService().deleteBookBeforeInvocation(bookToDeleteId); } catch (IllegalStateException e) { // ok, expected } this.log.infof("Book [%s] deleted", bookToDelete); assert !booksCache().containsKey(bookToDelete.getId()) : "deleteBook(" + bookToDelete + ") should have evicted book from cache."; } @Test public void testCachingCreate() { Book bookToCreate = new Book("112-358-132", "Random Author", "Path to Infinispan Enlightenment"); this.log.infof("Creating book [%s] ...", bookToCreate); getBookService().createBookCachingBackup(bookToCreate); this.log.infof("Book [%s] created", bookToCreate); assert bookToCreate.equals(booksCache().get(bookToCreate.getId())) : "createBook(" + bookToCreate + ") should have inserted created book into cache"; assert bookToCreate.equals(backupCache().get(bookToCreate.getId())) : "createBook(" + bookToCreate + ") should have inserted created book into cache"; } @Test public void testCachingFind() { final Integer bookToCacheId = Integer.valueOf(5); assert !booksCache().containsKey(bookToCacheId) : "Cache should not initially contain the book with id " + bookToCacheId; assert !backupCache().containsKey(bookToCacheId) : "Cache should not initially contain the book with id " + bookToCacheId; final Book cachedBook = getBookService().findBookCachingBackup(bookToCacheId); this.log.infof("Book [%s] cached", cachedBook); assert cachedBook.equals(booksCache().get(cachedBook.getId())) : "findBook(" + bookToCacheId + ") should have cached book"; assert cachedBook.equals(backupCache().get(cachedBook.getId())) : "findBook(" + bookToCacheId + ") should have cached book"; } @Test public void testCachingDelete() { final Integer bookToDeleteId = Integer.valueOf(new Random().nextInt(10) + 1); assert !booksCache().containsKey(bookToDeleteId) : "Cache should not initially contain the book with id " + bookToDeleteId; assert !backupCache().containsKey(bookToDeleteId) : "Cache should not initially contain the book with id " + bookToDeleteId; final Book bookToDelete1 = getBookService().findBook(bookToDeleteId); this.log.infof("Book [%s] cached", bookToDelete1); final Book bookToDelete2 = getBookService().findBookBackup(bookToDeleteId); this.log.infof("Book [%s] cached", bookToDelete2); assert bookToDelete1.equals(booksCache().get(bookToDeleteId)) : "findBook(" + bookToDeleteId + ") should have cached book"; assert bookToDelete1.equals(backupCache().get(bookToDeleteId)) : "findBook(" + bookToDeleteId + ") should have cached book"; this.log.infof("Deleting book [%s] ...", bookToDelete1); getBookService().deleteBookCachingBackup(bookToDeleteId); this.log.infof("Book [%s] deleted", bookToDelete1); assert !booksCache().containsKey(bookToDelete1.getId()) : "deleteBook(" + bookToDelete1 + ") should have evicted book from cache."; assert !backupCache().containsKey(bookToDelete1.getId()) : "deleteBook(" + bookToDelete2 + ") should have evicted book from cache."; } protected BasicCache<Object, Object> booksCache() { return (BasicCache<Object, Object>) getCacheManager().getCache("books").getNativeCache(); } protected BasicCache<Object, Object> backupCache() { return (BasicCache<Object, Object>) getCacheManager().getCache("backup").getNativeCache(); } protected BasicCache<Object, Object> getCache(String name) { return (BasicCache<Object, Object>) getCacheManager().getCache(name).getNativeCache(); } public abstract CachedBookService getBookService(); public abstract CacheManager getCacheManager(); }
23,081
42.63327
134
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/provider/sample/DataSourceResolver.java
package org.infinispan.spring.remote.provider.sample; import javax.sql.XADataSource; import org.h2.jdbcx.JdbcDataSource; import com.arjuna.ats.internal.jdbc.DynamicClass; /** * Required by JBoss Transactions for DataSource resolving. * * @author Matej Cimbora (mcimbora@redhat.com) */ public class DataSourceResolver implements DynamicClass { @Override public XADataSource getDataSource(String url) { JdbcDataSource dataSource = new JdbcDataSource(); dataSource.setURL(String.format("jdbc:%s;DB_CLOSE_DELAY=-1", url)); dataSource.setUser("sa"); dataSource.setPassword(""); return dataSource; } }
644
24.8
73
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/provider/sample/SampleHotrodServerLifecycleBean.java
package org.infinispan.spring.remote.provider.sample; import static org.infinispan.commons.dataconversion.MediaType.APPLICATION_SERIALIZED_OBJECT; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.infinispan.server.hotrod.test.HotRodTestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; /** * Starts test HotRod server instance with pre-defined set of caches. * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @author Matej Cimbora (mcimbora@redhat.com) */ public class SampleHotrodServerLifecycleBean implements InitializingBean, DisposableBean { private EmbeddedCacheManager cacheManager; private HotRodServer hotrodServer; private String remoteCacheName; private String remoteBackupCacheName; private String customCacheName; public void setRemoteCacheName(String remoteCacheName) { this.remoteCacheName = remoteCacheName; } public void setRemoteBackupCacheName(String remoteBackupCacheName) { this.remoteBackupCacheName = remoteBackupCacheName; } public void setCustomCacheName(String customCacheName) { this.customCacheName = customCacheName; } @Override public void afterPropertiesSet() throws Exception { ConfigurationBuilder builder = HotRodTestingUtil.hotRodCacheConfiguration(APPLICATION_SERIALIZED_OBJECT); cacheManager = TestCacheManagerFactory.createCacheManager(builder); Configuration configuration = builder.build(); cacheManager.defineConfiguration(remoteCacheName, configuration); cacheManager.defineConfiguration(remoteBackupCacheName, configuration); cacheManager.defineConfiguration(customCacheName, configuration); HotRodServerConfigurationBuilder hcb = new HotRodServerConfigurationBuilder(); hotrodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager, 15233, hcb); } @Override public void destroy() { cacheManager.stop(); hotrodServer.stop(); } }
2,422
36.859375
111
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/provider/sample/dao/BaseBookDao.java
package org.infinispan.spring.remote.provider.sample.dao; import org.infinispan.spring.remote.provider.sample.entity.Book; /** * <p> * A simple, woefully incomplete {@code DAO} for storing, retrieving and removing {@link Book * <code>Books</code>}. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @since 5.1 */ public interface BaseBookDao { /** * <p> * Look up and return the {@code Book} identified by the supplied {@code bookId}, or {@code null} * if no such book exists. * </p> * * @param bookId * @return The {@code Book} identified by the supplied {@code bookId}, or {@code null} */ Book findBook(Integer bookId); /** * <p> * Remove the {@code Book} identified by the supplied {@code bookId} from this store. * </p> * * @param bookId */ void deleteBook(Integer bookId); /** * <p> * Update provided {@code book} and return its updated version. * </p> * * @param book * The book to update * @return Updated book */ Book updateBook(Book book); /** * <p> * Create new book and return it. If the book already exists, throw exception. * </p> * * @param book The book to create * @return Created book. */ Book createBook(Book book); }
1,336
22.45614
100
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/provider/sample/dao/JdbcBookDao.java
package org.infinispan.spring.remote.provider.sample.dao; import java.lang.invoke.MethodHandles; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import javax.sql.DataSource; import org.infinispan.spring.remote.provider.sample.entity.Book; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; /** * <p> * {@link BaseBookDao <code>BookDao</code>} implementation that fronts a relational database, using * {@code JDBC} to store and retrieve {@link Book <code>books</code>}. Serves as an example of how * to use <a href="http://www.springframework.org">Spring</a>'s * {@link org.springframework.cache.annotation.Cacheable <code>@Cacheable</code>} and * {@link org.springframework.cache.annotation.CacheEvict <code>@CacheEvict</code>}. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @since 5.1 */ @Repository(value = "jdbcBookDao") public class JdbcBookDao implements BaseBookDao { private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); private NamedParameterJdbcTemplate jdbcTemplate; private SimpleJdbcInsert bookInsert; @Autowired(required = true) public void initialize(final DataSource dataSource) { this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource); this.bookInsert = new SimpleJdbcInsert(dataSource).withTableName("books") .usingGeneratedKeyColumns("id"); } public Book findBook(Integer bookId) { try { this.log.infof("Loading book [ID = %d]", bookId); return this.jdbcTemplate.queryForObject("SELECT * FROM books WHERE id = :id", new MapSqlParameterSource("id", bookId), new BookRowMapper()); } catch (EmptyResultDataAccessException e) { return null; } } private static final class BookRowMapper implements RowMapper<Book> { @Override public Book mapRow(ResultSet rs, int rowNum) throws SQLException { final Book mappedBook = new Book(); mappedBook.setId(rs.getInt("id")); mappedBook.setIsbn(rs.getString("isbn")); mappedBook.setAuthor(rs.getString("author")); mappedBook.setTitle(rs.getString("title")); return mappedBook; } } @Override public void deleteBook(Integer bookId) { this.log.infof("Deleting book [ID = %d]", bookId); this.jdbcTemplate.update("DELETE FROM books WHERE id = :id", new MapSqlParameterSource("id", bookId)); } public Collection<Book> getBooks() { return this.jdbcTemplate.query("SELECT * FROM books", new BookRowMapper()); } @Override public Book updateBook(Book bookToUpdate) { this.log.infof("Updating book [%s]", bookToUpdate); this.jdbcTemplate.update( "UPDATE books SET isbn = :isbn, author = :author, title = :title WHERE id = :id", createParameterSourceFor(bookToUpdate)); this.log.infof("Book [%s] updated", bookToUpdate); return bookToUpdate; } @Override public Book createBook(Book bookToCreate) { final Number newBookId = this.bookInsert .executeAndReturnKey(createParameterSourceFor(bookToCreate)); bookToCreate.setId(newBookId.intValue()); this.log.infof("Book [%s] persisted for the first time", bookToCreate); return bookToCreate; } private SqlParameterSource createParameterSourceFor(final Book book) { return new MapSqlParameterSource().addValue("id", book.getId()) .addValue("isbn", book.getIsbn()).addValue("author", book.getAuthor()) .addValue("title", book.getTitle()); } }
4,166
37.229358
108
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/provider/sample/entity/Book.java
package org.infinispan.spring.remote.provider.sample.entity; import java.io.Serializable; /** * Book. * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @since 5.1 */ public class Book implements Serializable { private Integer id; private String isbn; private String author; private String title; public Book() { } public Book(String isbn, String author, String title) { this(null, isbn, author, title); } public Book(Integer id, String isbn, String author, String title) { this.id = id; this.isbn = isbn; this.author = author; this.title = title; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((author == null) ? 0 : author.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((isbn == null) ? 0 : isbn.hashCode()); result = prime * result + ((title == null) ? 0 : title.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Book other = (Book) obj; if (author == null) { if (other.author != null) return false; } else if (!author.equals(other.author)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (isbn == null) { if (other.isbn != null) return false; } else if (!isbn.equals(other.isbn)) return false; if (title == null) { if (other.title != null) return false; } else if (!title.equals(other.title)) return false; return true; } @Override public String toString() { return "Book [id=" + id + ", isbn=" + isbn + ", author=" + author + ", title=" + title + "]"; } }
2,465
22.711538
99
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/provider/sample/generators/SingleArgKeyGenerator.java
package org.infinispan.spring.remote.provider.sample.generators; import java.lang.reflect.Method; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.stereotype.Component; /** * Simple implementation of {@link KeyGenerator} interface. It returns the first * argument passed to a method. * * @author Matej Cimbora (mcimbora@redhat.com) */ @Component public class SingleArgKeyGenerator implements KeyGenerator { @Override public Object generate(Object o, Method method, Object... params) { if (params != null && params.length == 1) { return params[0]; } else { throw new IllegalArgumentException("This generator requires exactly one parameter to be specified."); } } }
755
28.076923
110
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/provider/sample/service/CachedTransactionBookService.java
package org.infinispan.spring.remote.provider.sample.service; import org.infinispan.spring.remote.provider.sample.entity.Book; /** * Service providing basic create/find operations on both transactional and non-transactional caches. * * @author Matej Cimbora (mcimbora@redhat.com) */ public interface CachedTransactionBookService { public Book createBookNonTransactionalCache(Book book); public Book createBookTransactionalCache(Book book); public Book findBookNonTransactionalCache(Integer id); public Book findBookTransactionalCache(Integer id); public Book findBookCacheDisabled(Integer id); }
622
27.318182
101
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/provider/sample/service/CachedBookService.java
package org.infinispan.spring.remote.provider.sample.service; import org.infinispan.spring.remote.provider.sample.entity.Book; /** * Service providing extension to basic CRUD operations in order to test individual caching annotations and parameters * they support. * * @author Matej Cimbora (mcimbora@redhat.com) */ public interface CachedBookService { Book findBook(Integer bookId); Book findBookCondition(Integer bookId); Book findBookUnless(Integer bookId); Book findBookCustomKeyGenerator(Integer bookId); Book findBookCustomCacheResolver(Integer bookId); Book findBookBackup(Integer bookId); Book findBookCachingBackup(Integer bookId); Book findBookCustomCacheManager(Integer bookId); Book createBook(Book book); Book createBookCondition(Book book); Book createBookUnless(Book book); Book createBookCustomKeyGenerator(Book book); Book createBookCustomCacheResolver(Book book); Book createBookCustomCacheManager(Book book); Book createBookCachingBackup(Book book); void deleteBook(Integer bookId); void deleteBookCondition(Integer bookId); void deleteBookCustomKeyGenerator(Integer bookId); void deleteBookCustomCacheResolver(Integer bookId); void deleteBookAllEntries(Integer bookId); void deleteBookCachingBackup(Integer bookId); void deleteBookCustomCacheManager(Integer bookId); void deleteBookBeforeInvocation(Integer bookId); Book updateBook(Book book); }
1,469
23.098361
118
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/provider/sample/service/CachedBookServiceImpl.java
package org.infinispan.spring.remote.provider.sample.service; import org.infinispan.spring.remote.provider.sample.dao.JdbcBookDao; import org.infinispan.spring.remote.provider.sample.entity.Book; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Caching; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @author Matej Cimbora (mcimbora@redhat.com) */ @Transactional @Service public class CachedBookServiceImpl implements CachedBookService { @Autowired private JdbcBookDao baseDao; /** * <p> * Look up and return the {@code Book} identified by the supplied {@code bookId}. By annotating * this method with {@code @Cacheable(value = "books", key = "#bookId")} we achieve the * following: * <ol> * <li> * {@code Book} instances returned from this method will be cached in a named * {@link org.springframework.cache.Cache <code>Cache</code>} &quot;books&quot;</li> * <li> * The key used to cache {@code Book} instances will be the supplied {@code bookId}.</li> * </ol> * </p> * <p> * Note that it is <strong>important</strong> that we explicitly tell Spring to use {@code bookId} * as the cache key. Otherwise, Spring would <strong>derive</strong> a cache key from the * parameters passed in (in our case only {@code bookId}), a cache key we have no control over. * This would get us into trouble when in {@link #updateBook(Book)} we need a book's cache key to * remove it from the cache. But we wouldn't know that cache key since we don't know Spring's key * generation algorithm. Therefore, we consistently use {@code key = "#bookId"} or * {@code key = "#book.id"} to tell Spring to <strong>always</strong> use a book's id as its * cache key. * </p> */ @Override @Cacheable(value = "books", key = "#bookId") public Book findBook(Integer bookId) { return baseDao.findBook(bookId); } /** * <p> * Remove the book identified by the supplied {@code bookId} from database. By annotating this * method with {@code @CacheEvict(value = "books", key = "#bookId")} we make sure that Spring * will remove the book cache under key {@code bookId} (if any) from the * {@link org.springframework.cache.Cache <code>Cache</code>} &quot;books&quot;. * </p> */ @Override @CacheEvict(value = "books", key = "#bookId") public void deleteBook(Integer bookId) { baseDao.deleteBook(bookId); } /** * <p> * Store the supplied {@code bookToStore} in database. Since it is annotated with * {@code @CacheEvict(value = "books", key = "#book.id", condition = "#book.id != null")} * this method will tell Spring to remove any book cached under the key * {@code book.getId()} from the {@link org.springframework.cache.Cache * <code>Cache</code>} &quot;books&quot;. This eviction will only be triggered if that id is not * {@code null}. * </p> */ @Override @CacheEvict(value = "books", key = "#book.id", condition = "#book.id != null") public Book updateBook(Book book) { return baseDao.updateBook(book); } @Override @CachePut(value = "books", key = "#book.id") public Book createBook(Book book) { return baseDao.createBook(book); } @Override @Cacheable(value = "books", key = "#bookId", condition = "#bookId > 1") public Book findBookCondition(Integer bookId) { return baseDao.findBook(bookId); } @Override @Cacheable(value = "books", key = "#bookId", unless = "#bookId > 1") public Book findBookUnless(Integer bookId) { return baseDao.findBook(bookId); } @Override @Cacheable(value = "books", keyGenerator = "singleArgKeyGenerator") public Book findBookCustomKeyGenerator(Integer bookId) { return baseDao.findBook(bookId); } @Override @Cacheable(value = "books", key = "#bookId", cacheResolver = "customCacheResolver") public Book findBookCustomCacheResolver(Integer bookId) { return baseDao.findBook(bookId); } @Override @Cacheable(value = "backup", key = "#bookId") public Book findBookBackup(Integer bookId) { return baseDao.findBook(bookId); } @Override @CachePut(value = "books", key = "#book.id", condition = "#book.title == 'Path to Infinispan Enlightenment'") public Book createBookCondition(Book book) { return baseDao.createBook(book); } @Override @CachePut(value = "books", key = "#book.id", unless = "#book.isbn == '112-358-132'") public Book createBookUnless(Book book) { return baseDao.createBook(book); } @Override @CachePut(value = "books", keyGenerator = "singleArgKeyGenerator") public Book createBookCustomKeyGenerator(Book book) { return baseDao.createBook(book); } @Override @CachePut(value = "books", key = "#book.id", cacheResolver = "customCacheResolver") public Book createBookCustomCacheResolver(Book book) { return baseDao.createBook(book); } @Override @CachePut(value = "books", key = "#book.id", cacheManager = "cacheManager") public Book createBookCustomCacheManager(Book book) { return baseDao.createBook(book); } @Override @CacheEvict(value = "books", key = "#bookId", condition = "#bookId > 1") public void deleteBookCondition(Integer bookId) { baseDao.deleteBook(bookId); } @Override @CacheEvict(value = "books", keyGenerator = "singleArgKeyGenerator") public void deleteBookCustomKeyGenerator(Integer bookId) { baseDao.deleteBook(bookId); } @Override @CacheEvict(value = "books", key = "#bookId", cacheResolver = "customCacheResolver") public void deleteBookCustomCacheResolver(Integer bookId) { baseDao.deleteBook(bookId); } @Override @CacheEvict(value = "books", key = "#bookId", allEntries = true) public void deleteBookAllEntries(Integer bookId) { baseDao.deleteBook(bookId); } @Override @Caching(put = {@CachePut(value = "books", key = "#book.id"), @CachePut(value = "backup", key = "#book.id")}) public Book createBookCachingBackup(Book book) { return baseDao.createBook(book); } @Override @Caching(cacheable = {@Cacheable(value = "books", key = "#bookId"), @Cacheable(value = "backup", key = "#bookId")}) public Book findBookCachingBackup(Integer bookId) { return baseDao.findBook(bookId); } @Override @Cacheable(value = "books", cacheManager = "cacheManager") public Book findBookCustomCacheManager(Integer bookId) { return baseDao.findBook(bookId); } @Override @Caching(evict = {@CacheEvict(value = "books"), @CacheEvict(value = "backup")}) public void deleteBookCachingBackup(Integer bookId) { baseDao.deleteBook(bookId); } @Override @CacheEvict(value = "books", cacheManager = "cacheManager") public void deleteBookCustomCacheManager(Integer bookId) { baseDao.deleteBook(bookId); } @Override @CacheEvict(value = "books", beforeInvocation = true) public void deleteBookBeforeInvocation(Integer bookId) { throw new IllegalStateException("This method throws exception by default."); } }
7,495
34.526066
118
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/provider/sample/service/CachedTransactionBookServiceImpl.java
package org.infinispan.spring.remote.provider.sample.service; import org.infinispan.spring.remote.provider.sample.dao.BaseBookDao; import org.infinispan.spring.remote.provider.sample.entity.Book; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * @author Matej Cimbora (mcimbora@redhat.com) */ @Transactional @Service public class CachedTransactionBookServiceImpl implements CachedTransactionBookService { @Autowired private BaseBookDao baseDao; @CachePut(value = "books", key = "#book.id") @Override public Book createBookNonTransactionalCache(Book book) { return baseDao.createBook(book); } @CachePut(value = "booksTransactional", key = "#book.id") @Override public Book createBookTransactionalCache(Book book) { return baseDao.createBook(book); } @Cacheable(value = "books") @Override public Book findBookNonTransactionalCache(Integer id) { return baseDao.findBook(id); } @Cacheable(value = "booksTransactional") @Override public Book findBookTransactionalCache(Integer id) { return baseDao.findBook(id); } @Override public Book findBookCacheDisabled(Integer id) { return baseDao.findBook(id); } }
1,443
27.88
87
java
null
infinispan-main/spring/spring6/spring6-remote/src/test/java/org/infinispan/spring/remote/provider/sample/resolvers/CustomCacheResolver.java
package org.infinispan.spring.remote.provider.sample.resolvers; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.cache.interceptor.CacheOperationInvocationContext; import org.springframework.cache.interceptor.CacheResolver; import org.springframework.stereotype.Component; /** * Simple implementation of {@link CacheResolver} interface. It returns a single * instance of {@link Cache} with name 'custom'. * * @author Matej Cimbora (mcimbora@redhat.com) */ @Component public class CustomCacheResolver implements CacheResolver { private static final String CACHE_NAME = "custom"; @Autowired(required = true) private CacheManager cacheManager; @Override public Collection<? extends Cache> resolveCaches(CacheOperationInvocationContext<?> cacheOperationInvocationContext) { return new ArrayList<Cache>(Arrays.asList(cacheManager.getCache(CACHE_NAME))); } }
1,098
32.30303
121
java
null
infinispan-main/spring/spring6/spring6-remote/src/main/java/org/infinispan/spring/remote/ConfigurationPropertiesOverrides.java
package org.infinispan.spring.remote; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.ASYNC_EXECUTOR_FACTORY; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.FORCE_RETURN_VALUES; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.JAVA_SERIAL_ALLOWLIST; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.KEY_SIZE_ESTIMATE; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.MARSHALLER; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.NEAR_CACHE_MAX_ENTRIES; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.NEAR_CACHE_MODE; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.NEAR_CACHE_NAME_PATTERN; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.REQUEST_BALANCING_STRATEGY; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.SERVER_LIST; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TCP_KEEP_ALIVE; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.TCP_NO_DELAY; import static org.infinispan.client.hotrod.impl.ConfigurationProperties.VALUE_SIZE_ESTIMATE; import java.net.InetSocketAddress; import java.util.Collection; import java.util.Map; import java.util.Properties; /** * <p> * Provides a mechanism to override selected configuration properties using explicit setters for * each configuration setting. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * */ public class ConfigurationPropertiesOverrides { public static final String OPERATION_READ_TIMEOUT = "infinispan.spring.operation.read.timeout"; public static final String OPERATION_WRITE_TIMEOUT = "infinispan.spring.operation.write.timeout"; private final Properties overridingProperties = new Properties(); /** * @return * @see java.util.Hashtable#isEmpty() */ public boolean isEmpty() { return this.overridingProperties.isEmpty(); } boolean containsProperty(String key) { String prop = overridingProperties.getProperty(key); return prop != null && !prop.isEmpty(); } /** * @param TransportFactory * @deprecated since 10.0. This method has no effect */ @Deprecated public void setTransportFactory(final String TransportFactory) { } /** * @param serverList */ public void setServerList(final Collection<InetSocketAddress> serverList) { final StringBuilder serverListStr = new StringBuilder(); for (final InetSocketAddress server : serverList) { serverListStr.append(server.getHostString()).append(":").append(server.getPort()) .append(";"); } serverListStr.deleteCharAt(serverListStr.length() - 1); this.overridingProperties.setProperty(SERVER_LIST, serverListStr.toString()); } /** * @param marshaller */ public void setMarshaller(final String marshaller) { this.overridingProperties.setProperty(MARSHALLER, marshaller); } /** * @param allowListRegex */ public void setClassAllowList(final String allowListRegex) { this.overridingProperties.setProperty(JAVA_SERIAL_ALLOWLIST, allowListRegex); } /** * @param asyncExecutorFactory */ public void setAsyncExecutorFactory(final String asyncExecutorFactory) { this.overridingProperties.setProperty(ASYNC_EXECUTOR_FACTORY, asyncExecutorFactory); } /** * @param tcpNoDelay */ public void setTcpNoDelay(final boolean tcpNoDelay) { this.overridingProperties.setProperty(TCP_NO_DELAY, Boolean.toString(tcpNoDelay)); } public void setTcpKeepAlive(final boolean tcpKeepAlive) { this.overridingProperties.setProperty(TCP_KEEP_ALIVE, Boolean.toString(tcpKeepAlive)); } /** * @param requestBalancingStrategy */ public void setRequestBalancingStrategy(final String requestBalancingStrategy) { this.overridingProperties.setProperty(REQUEST_BALANCING_STRATEGY, requestBalancingStrategy); } /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated public void setKeySizeEstimate(final int keySizeEstimate) { this.overridingProperties.setProperty(KEY_SIZE_ESTIMATE, Integer.toString(keySizeEstimate)); } /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated public void setValueSizeEstimate(final int valueSizeEstimate) { this.overridingProperties.setProperty(VALUE_SIZE_ESTIMATE, Integer.toString(valueSizeEstimate)); } /** * @param forceReturnValues */ public void setForceReturnValues(final boolean forceReturnValues) { this.overridingProperties.setProperty(FORCE_RETURN_VALUES, Boolean.toString(forceReturnValues)); } public void setReadTimeout(long readTimeout) { this.overridingProperties.setProperty(OPERATION_READ_TIMEOUT, Long.toString(readTimeout)); } public void setWriteTimeout(long writeTimeout) { this.overridingProperties.setProperty(OPERATION_WRITE_TIMEOUT, Long.toString(writeTimeout)); } public void setNearCacheMode(String mode) { this.overridingProperties.setProperty(NEAR_CACHE_MODE, mode); } public void setNearCacheMaxEntries(int maxEntries) { this.overridingProperties.setProperty(NEAR_CACHE_MAX_ENTRIES, Integer.toString(maxEntries)); } public void setNearCacheNamePattern(String pattern) { this.overridingProperties.setProperty(NEAR_CACHE_NAME_PATTERN, pattern); } /** * @param configurationPropertiesToOverride * @return */ public Properties override(final Properties configurationPropertiesToOverride) { final Properties answer = Properties.class.cast(configurationPropertiesToOverride.clone()); for (final Map.Entry<Object, Object> prop : this.overridingProperties.entrySet()) { answer.setProperty(String.class.cast(prop.getKey()), String.class.cast(prop.getValue())); } return answer; } }
6,166
35.928144
100
java
null
infinispan-main/spring/spring6/spring6-remote/src/main/java/org/infinispan/spring/remote/AbstractRemoteCacheManagerFactory.java
package org.infinispan.spring.remote; import java.io.IOException; import java.io.InputStream; import java.lang.invoke.MethodHandles; import java.net.InetSocketAddress; import java.util.Collection; import java.util.Collections; import java.util.LinkedHashSet; import java.util.Properties; import java.util.Set; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.impl.ConfigurationProperties; import org.infinispan.commons.logging.Log; import org.infinispan.commons.logging.LogFactory; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.commons.util.Util; import org.springframework.core.io.Resource; /** * <p> * An abstract base class for factories creating cache manager that are backed by an Infinispan * RemoteCacheManager. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * * @see RemoteCacheManager */ public abstract class AbstractRemoteCacheManagerFactory { protected static final Log logger = LogFactory.getLog(MethodHandles.lookup().lookupClass()); public static final String SPRING_JAVA_SERIAL_ALLOWLIST = "java.util.HashMap,java.time.*,org.springframework.*,org.infinispan.spring.remote.*"; protected boolean startAutomatically = true; private Properties configurationProperties; private Resource configurationPropertiesFileLocation; private final ConfigurationPropertiesOverrides configurationPropertiesOverrides = new ConfigurationPropertiesOverrides(); protected void assertCorrectlyConfigured() throws IllegalStateException { if ((this.configurationProperties != null) && (this.configurationPropertiesFileLocation != null)) { throw new IllegalStateException( "You may only use either \"configurationProperties\" or \"configurationPropertiesFileLocation\" " + "to configure the RemoteCacheManager, not both."); } else if ((this.configurationProperties != null) && !this.configurationPropertiesOverrides.isEmpty()) { throw new IllegalStateException( "You may only use either \"configurationProperties\" or setters on this FactoryBean " + "to configure the RemoteCacheManager, not both."); } } protected Properties configurationProperties() throws IOException { final Properties answer; if (this.configurationProperties != null) { answer = this.configurationPropertiesOverrides.override(this.configurationProperties); logger.debug("Using user-defined properties [" + this.configurationProperties + "] for configuring RemoteCacheManager"); } else if (this.configurationPropertiesFileLocation != null) { answer = loadPropertiesFromFile(this.configurationPropertiesFileLocation); logger.debug("Loading properties from file [" + this.configurationProperties + "] for configuring RemoteCacheManager"); } else if (!this.configurationPropertiesOverrides.isEmpty()) { answer = this.configurationPropertiesOverrides.override(new Properties()); logger.debug("Using explicitly set configuration settings [" + answer + "] for configuring RemoteCacheManager"); } else { logger.debug("No configuration properties. RemoteCacheManager will use default configuration."); RemoteCacheManager remoteCacheManager = new RemoteCacheManager(false); try { answer = remoteCacheManager.getConfiguration().properties(); } finally { remoteCacheManager.stop(); } } initializeMarshallingProperties(answer); return answer; } private void initializeMarshallingProperties(Properties properties) { // If the property has already been overridden, we don't apply any default behaviour if (!configurationPropertiesOverrides.containsProperty(ConfigurationProperties.MARSHALLER)) { String marshaller = JavaSerializationMarshaller.class.getName(); String configuredMarshaller = properties.getProperty(ConfigurationProperties.MARSHALLER); if (configuredMarshaller != null && configuredMarshaller.equals(Util.GENERIC_JBOSS_MARSHALLING_CLASS)) { // If the marshaller is equal to the legacy jboss-marshaller, and infinispan-jboss-marshalling is on the cp, allow if (Util.getJBossMarshaller(Thread.currentThread().getContextClassLoader(), null) != null) marshaller = configuredMarshaller; } properties.setProperty(ConfigurationProperties.MARSHALLER, marshaller); } if (!configurationPropertiesOverrides.containsProperty(ConfigurationProperties.JAVA_SERIAL_WHITELIST) && !configurationPropertiesOverrides.containsProperty(ConfigurationProperties.JAVA_SERIAL_ALLOWLIST)) { Set<String> userRegexSet = new LinkedHashSet<>(); Collections.addAll(userRegexSet, SPRING_JAVA_SERIAL_ALLOWLIST.split(",")); String userAllowList = properties.getProperty(ConfigurationProperties.JAVA_SERIAL_ALLOWLIST); if (userAllowList != null && !userAllowList.isEmpty()) { Collections.addAll(userRegexSet, userAllowList.split(",")); } String userWhiteList = properties.getProperty(ConfigurationProperties.JAVA_SERIAL_WHITELIST); if (userWhiteList != null && !userWhiteList.isEmpty()) { Collections.addAll(userRegexSet, userWhiteList.split(",")); } String allowList = String.join(",", userRegexSet); properties.setProperty(ConfigurationProperties.JAVA_SERIAL_ALLOWLIST, allowList); } } private Properties loadPropertiesFromFile(final Resource propertiesFileLocation) throws IOException { InputStream propsStream = null; try { propsStream = propertiesFileLocation.getInputStream(); final Properties answer = new Properties(); answer.load(propsStream); return answer; } finally { if (propsStream != null) { try { propsStream.close(); } catch (final IOException e) { logger.warn( "Failed to close InputStream used to load configuration properties: " + e.getMessage(), e); } } } } // ------------------------------------------------------------------------ // Setters for configuring RemoteCacheManager // ------------------------------------------------------------------------ /** * @param configurationProperties * the configurationProperties to set */ public void setConfigurationProperties(final Properties configurationProperties) { this.configurationProperties = configurationProperties; } /** * @param configurationPropertiesFileLocation * the configurationPropertiesFileLocation to set */ public void setConfigurationPropertiesFileLocation( final Resource configurationPropertiesFileLocation) { this.configurationPropertiesFileLocation = configurationPropertiesFileLocation; } /** * @param startAutomatically * the startAutomatically to set */ public void setStartAutomatically(final boolean startAutomatically) { this.startAutomatically = startAutomatically; } /** * @param transportFactory * @see ConfigurationPropertiesOverrides#setTransportFactory(String) */ @Deprecated public void setTransportFactory(final String transportFactory) { } /** * @param serverList * @see ConfigurationPropertiesOverrides#setServerList(Collection) */ public void setServerList(final Collection<InetSocketAddress> serverList) { this.configurationPropertiesOverrides.setServerList(serverList); } /** * @param marshaller * @see ConfigurationPropertiesOverrides#setMarshaller(String) */ public void setMarshaller(final String marshaller) { this.configurationPropertiesOverrides.setMarshaller(marshaller); } /** * @param allowListRegex * @see ConfigurationPropertiesOverrides#setClassAllowList(String) */ public void setClassAllowList(final String allowListRegex) { this.configurationPropertiesOverrides.setClassAllowList(allowListRegex); } /** * @param allowListRegex * @see ConfigurationPropertiesOverrides#setClassAllowList(String) * @deprecated Use {@link #setClassAllowList(String)} instead. Will be removed in 14.0. */ @Deprecated public void setClassWhiteList(final String allowListRegex) { setClassAllowList(allowListRegex); } /** * @param asyncExecutorFactory * @see ConfigurationPropertiesOverrides#setAsyncExecutorFactory(String) */ public void setAsyncExecutorFactory(final String asyncExecutorFactory) { this.configurationPropertiesOverrides.setAsyncExecutorFactory(asyncExecutorFactory); } /** * @param tcpNoDelay * @see ConfigurationPropertiesOverrides#setTcpNoDelay(boolean) */ public void setTcpNoDelay(final boolean tcpNoDelay) { this.configurationPropertiesOverrides.setTcpNoDelay(tcpNoDelay); } /** * @see ConfigurationPropertiesOverrides#setTcpNoDelay(boolean) */ public void setTcpKeepAlive(final boolean tcpKeepAlive) { this.configurationPropertiesOverrides.setTcpKeepAlive(tcpKeepAlive); } /** * @param requestBalancingStrategy * @see ConfigurationPropertiesOverrides#setRequestBalancingStrategy(String) */ public void setRequestBalancingStrategy(final String requestBalancingStrategy) { this.configurationPropertiesOverrides.setRequestBalancingStrategy(requestBalancingStrategy); } /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated public void setKeySizeEstimate(final int keySizeEstimate) { this.configurationPropertiesOverrides.setKeySizeEstimate(keySizeEstimate); } /** * @deprecated Since 12.0, does nothing and will be removed in 15.0 */ @Deprecated public void setValueSizeEstimate(final int valueSizeEstimate) { this.configurationPropertiesOverrides.setValueSizeEstimate(valueSizeEstimate); } /** * @param forceReturnValues * @see ConfigurationPropertiesOverrides#setForceReturnValues(boolean) */ public void setForceReturnValues(final boolean forceReturnValues) { this.configurationPropertiesOverrides.setForceReturnValues(forceReturnValues); } /** * @param readTimeout * @see ConfigurationPropertiesOverrides#setReadTimeout(long) */ public void setReadTimeout(final long readTimeout) { this.configurationPropertiesOverrides.setReadTimeout(readTimeout); } /** * @param writeTimeout * @see ConfigurationPropertiesOverrides#setWriteTimeout(long) */ public void setWriteTimeout(final long writeTimeout) { this.configurationPropertiesOverrides.setWriteTimeout(writeTimeout); } /** * @param mode * @see ConfigurationPropertiesOverrides#setNearCacheMode(String) */ public void setNearCacheMode(String mode) { this.configurationPropertiesOverrides.setNearCacheMode(mode); } /** * @param maxEntries * @see ConfigurationPropertiesOverrides#setNearCacheMaxEntries(int) */ public void setNearCacheMaxEntries(int maxEntries) { this.configurationPropertiesOverrides.setNearCacheMaxEntries(maxEntries); } /** * @param pattern * @see ConfigurationPropertiesOverrides#setNearCacheNamePattern(String) */ public void setNearCacheNamePattern(String pattern) { this.configurationPropertiesOverrides.setNearCacheNamePattern(pattern); } }
11,836
37.9375
146
java
null
infinispan-main/spring/spring6/spring6-remote/src/main/java/org/infinispan/spring/remote/session/RemoteApplicationPublishedBridge.java
package org.infinispan.spring.remote.session; import java.nio.ByteBuffer; import java.util.Collections; import org.infinispan.client.hotrod.DataFormat; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.annotation.ClientCacheEntryCreated; import org.infinispan.client.hotrod.annotation.ClientCacheEntryExpired; import org.infinispan.client.hotrod.annotation.ClientCacheEntryRemoved; import org.infinispan.client.hotrod.annotation.ClientListener; import org.infinispan.client.hotrod.event.ClientCacheEntryCustomEvent; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.io.UnsignedNumeric; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.spring.common.session.AbstractApplicationPublisherBridge; import org.infinispan.util.KeyValuePair; import org.springframework.session.MapSession; import org.springframework.session.Session; /** * A bridge between Infinispan Remote events and Spring. * * @author Sebastian Łaskawiec * @author Katia Aresti, karesti@redhat.com * @since 9.0 */ @ClientListener(converterFactoryName = "___eager-key-value-version-converter", useRawData = true) public class RemoteApplicationPublishedBridge extends AbstractApplicationPublisherBridge { private final DataFormat dataFormat; private final ClassAllowList allowList = new ClassAllowList(Collections.singletonList(".*")); public RemoteApplicationPublishedBridge(SpringCache eventSource) { super(eventSource); this.dataFormat = ((RemoteCache) eventSource.getNativeCache()).getDataFormat(); } @Override protected void registerListener() { ((RemoteCache<?, ?>) eventSource.getNativeCache()).addClientListener(this, null, new Object[]{Boolean.TRUE}); } @Override public void unregisterListener() { ((RemoteCache<?, ?>) eventSource.getNativeCache()).removeClientListener(this); } @ClientCacheEntryCreated public void processCacheEntryCreated(ClientCacheEntryCustomEvent<byte[]> event) { emitSessionCreatedEvent(readEvent(event).getValue()); } @ClientCacheEntryExpired public void processCacheEntryExpired(ClientCacheEntryCustomEvent<byte[]> event) { emitSessionExpiredEvent(readEvent(event).getValue()); } @ClientCacheEntryRemoved public void processCacheEntryDestroyed(ClientCacheEntryCustomEvent<byte[]> event) { emitSessionDestroyedEvent(readEvent(event).getValue()); } protected KeyValuePair<String, Session> readEvent(ClientCacheEntryCustomEvent<byte[]> event) { byte[] eventData = event.getEventData(); ByteBuffer rawData = ByteBuffer.wrap(eventData); byte[] rawKey = readElement(rawData); byte[] rawValue = readElement(rawData); String key = dataFormat.keyToObj(rawKey, allowList); KeyValuePair keyValuePair; if (rawValue == null) { // This events will hold either an old or a new value almost every time. But there are some corner cases // during rebalance where neither a new or an old value will be present. This if handles this case keyValuePair = new KeyValuePair<>(key, new MapSession(key)); } else { keyValuePair = new KeyValuePair<>(key, dataFormat.valueToObj(rawValue, allowList)); } return keyValuePair; } private byte[] readElement(ByteBuffer buffer) { if (buffer.remaining() == 0) return null; int length = UnsignedNumeric.readUnsignedInt(buffer); byte[] element = new byte[length]; buffer.get(element); return element; } }
3,584
37.967391
115
java
null
infinispan-main/spring/spring6/spring6-remote/src/main/java/org/infinispan/spring/remote/session/InfinispanRemoteSessionRepository.java
package org.infinispan.spring.remote.session; import java.util.Collections; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; import org.infinispan.client.hotrod.Flag; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.commons.CacheException; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.spring.common.session.AbstractInfinispanSessionRepository; import org.infinispan.spring.common.session.PrincipalNameResolver; import org.springframework.session.MapSession; /** * Session Repository for Infinispan in client/server mode. * * @author Sebastian Łaskawiec * @since 9.0 */ public class InfinispanRemoteSessionRepository extends AbstractInfinispanSessionRepository { /** * Creates new repository based on {@link SpringCache} * * @param cache Cache which shall be used for session repository. */ public InfinispanRemoteSessionRepository(SpringCache cache) { super(cache, new RemoteApplicationPublishedBridge(cache)); } @Override protected void removeFromCacheWithoutNotifications(String originalId) { RemoteCache remoteCache = (RemoteCache) nativeCache; if (cache.getWriteTimeout() > 0) { try { remoteCache.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).removeAsync(originalId).get(cache.getWriteTimeout(), TimeUnit.MILLISECONDS); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new CacheException(e); } catch (ExecutionException | TimeoutException e) { throw new CacheException(e); } } else { remoteCache.withFlags(Flag.SKIP_LISTENER_NOTIFICATION).remove(originalId); } } @Override public Map<String, InfinispanSession> findByIndexNameAndIndexValue(String indexName, String indexValue) { if (!PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) { return Collections.emptyMap(); } return nativeCache.values().stream() .filter(session -> indexValue.equals(PrincipalNameResolver.getInstance().resolvePrincipal(session))) .collect(Collectors.toMap(MapSession::getId, session -> new InfinispanSession(session, false))); } }
2,358
37.048387
143
java
null
infinispan-main/spring/spring6/spring6-remote/src/main/java/org/infinispan/spring/remote/session/configuration/InfinispanRemoteHttpSessionConfiguration.java
package org.infinispan.spring.remote.session.configuration; import java.time.Duration; import java.util.Map; import java.util.Objects; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.spring.remote.provider.SpringRemoteCacheManager; import org.infinispan.spring.remote.session.InfinispanRemoteSessionRepository; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportAware; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.AnnotationMetadata; import org.springframework.session.config.annotation.web.http.SpringHttpSessionConfiguration; @Configuration public class InfinispanRemoteHttpSessionConfiguration extends SpringHttpSessionConfiguration implements ImportAware { private String cacheName; private int maxInactiveIntervalInSeconds; @Bean public InfinispanRemoteSessionRepository sessionRepository(SpringRemoteCacheManager cacheManager, ApplicationEventPublisher eventPublisher) { Objects.requireNonNull(cacheName, "Cache name can not be null"); Objects.requireNonNull(cacheManager, "Cache Manager can not be null"); Objects.requireNonNull(eventPublisher, "Event Publisher can not be null"); SpringCache cacheForSessions = cacheManager.getCache(cacheName); InfinispanRemoteSessionRepository sessionRepository = new InfinispanRemoteSessionRepository(cacheForSessions); sessionRepository.setDefaultMaxInactiveInterval(Duration.ofSeconds(maxInactiveIntervalInSeconds)); sessionRepository.setApplicationEventPublisher(eventPublisher); return sessionRepository; } @Override public void setImportMetadata(AnnotationMetadata importMetadata) { Map<String, Object> enableAttrMap = importMetadata .getAnnotationAttributes(EnableInfinispanRemoteHttpSession.class.getName()); AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(enableAttrMap); cacheName = annotationAttributes.getString("cacheName"); maxInactiveIntervalInSeconds = annotationAttributes.getNumber("maxInactiveIntervalInSeconds").intValue(); } }
2,360
47.183673
117
java
null
infinispan-main/spring/spring6/spring6-remote/src/main/java/org/infinispan/spring/remote/session/configuration/EnableInfinispanRemoteHttpSession.java
package org.infinispan.spring.remote.session.configuration; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.session.MapSession; import org.springframework.session.config.annotation.web.http.EnableSpringHttpSession; /** * Add this annotation to a {@code @Configuration} class to expose the SessionRepositoryFilter as a bean named * "springSessionRepositoryFilter" and backed on Infinispan. * <p> * The configuration requires creating a {@link org.infinispan.spring.common.provider.SpringCache} (for either remote or * embedded configuration). Here's an example: * <pre> <code> * {@literal @Configuration} * {@literal @EnableInfinispanRemoteHttpSession} * public class InfinispanConfiguration { * * {@literal @Bean} * public SpringRemoteCacheManagerFactoryBean springCache() { * return new SpringRemoteCacheManagerFactoryBean(); * } * } * </code> </pre> * * Configuring advanced features requires putting everything together manually or extending * {@link InfinispanRemoteHttpSessionConfiguration}. * * @author Sebastian Łaskawiec * @see EnableSpringHttpSession * @since 9.0 */ @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({java.lang.annotation.ElementType.TYPE}) @Documented @Import(InfinispanRemoteHttpSessionConfiguration.class) @Configuration public @interface EnableInfinispanRemoteHttpSession { String DEFAULT_CACHE_NAME = "sessions"; /** * This is the session timeout in seconds. By default, it is set to 1800 seconds (30 minutes). This should be a * non-negative integer. * * @return the seconds a session can be inactive before expiring */ int maxInactiveIntervalInSeconds() default MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS; /** * Cache name used for storing session data. * * @return the cache name for storing data. */ String cacheName() default DEFAULT_CACHE_NAME; }
2,116
33.145161
120
java
null
infinispan-main/spring/spring6/spring6-remote/src/main/java/org/infinispan/spring/remote/support/InfinispanRemoteCacheManagerFactoryBean.java
package org.infinispan.spring.remote.support; import java.util.Properties; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.spring.remote.AbstractRemoteCacheManagerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; /** * <p> * A {@link FactoryBean <code>FactoryBean</code>} for creating an * {@link RemoteCacheManager * <code>Infinispan RemoteCacheManager</code>} instance. * </p> * <strong>Configuration</strong><br/> * <p> * A <code>RemoteCacheManager</code> is configured through a {@link Properties * <code>Properties</code>} object. For an exhaustive list of valid properties to be used see * <code>RemoteCacheManager</code>'s {@link RemoteCacheManager * javadocs}. This <code>FactoryBean</code> provides means to either * {@link #setConfigurationProperties(Properties) inject} a user-defined <code>Properties</code> * instance or to * {@link #setConfigurationPropertiesFileLocation(org.springframework.core.io.Resource) set} the * location of a properties file to load those properties from. Note that it is <em>illegal</em> to * use both mechanisms simultaneously. * </p> * <p> * Alternatively or in combination with * {@link #setConfigurationPropertiesFileLocation(org.springframework.core.io.Resource) setting} the * location of a <code>Properties</code> file to load the configuration from, this * <code>FactoryBean</code> provides (typed) setters for all configuration settings. Settings thus * defined take precedence over those defined in the injected <code>Properties</code> instance. This * flexibility enables users to use e.g. a company-wide <code>Properties</code> file containing * default settings while simultaneously overriding select settings whenever special requirements * warrant this.<br/> * Note that it is illegal to use setters in conjunction with * {@link #setConfigurationProperties(Properties) injecting} a <code>Properties</code> instance. * </p> * <p> * In addition to creating a <code>RemoteCacheManager</code> this <code>FactoryBean</code> does also * control that <code>RemoteCacheManagers</code>'s lifecycle by shutting it down when the enclosing * Spring application context is closed. It is therefore advisable to <em>always</em> use this * <code>FactoryBean</code> when creating a <code>RemoteCacheManager</code>. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * * @see RemoteCacheManager * @see #destroy() */ public class InfinispanRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<RemoteCacheManager>, InitializingBean, DisposableBean { private RemoteCacheManager nativeRemoteCacheManager; // ------------------------------------------------------------------------ // org.springframework.beans.factory.InitializingBean // ------------------------------------------------------------------------ /** * @see InitializingBean#afterPropertiesSet() */ @Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); this.nativeRemoteCacheManager = new RemoteCacheManager(clientBuilder.build(), this.startAutomatically); this.logger.info("Finished creating new instance of RemoteCacheManager"); } // ------------------------------------------------------------------------ // org.springframework.beans.factory.FactoryBean // ------------------------------------------------------------------------ /** * @see FactoryBean#getObject() */ @Override public RemoteCacheManager getObject() throws Exception { return this.nativeRemoteCacheManager; } /** * @see FactoryBean#getObjectType() */ @Override public Class<? extends RemoteCacheManager> getObjectType() { return this.nativeRemoteCacheManager != null ? this.nativeRemoteCacheManager.getClass() : RemoteCacheManager.class; } /** * Always return <code>true</code>. * * @see FactoryBean#isSingleton() */ @Override public boolean isSingleton() { return true; } // ------------------------------------------------------------------------ // org.springframework.beans.factory.DisposableBean // ------------------------------------------------------------------------ /** * {@link RemoteCacheManager#stop() <code>stop</code>} the * <code>RemoteCacheManager</code> created by this factory. * * @see DisposableBean#destroy() */ @Override public void destroy() throws Exception { // Being paranoid if (this.nativeRemoteCacheManager != null) { this.nativeRemoteCacheManager.stop(); } } }
5,268
40.488189
100
java
null
infinispan-main/spring/spring6/spring6-remote/src/main/java/org/infinispan/spring/remote/support/InfinispanNamedRemoteCacheFactoryBean.java
package org.infinispan.spring.remote.support; import java.lang.invoke.MethodHandles; import java.util.concurrent.ConcurrentMap; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.commons.logging.Log; import org.infinispan.commons.logging.LogFactory; import org.springframework.beans.factory.BeanNameAware; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.StringUtils; /** * <p> * A {@link FactoryBean <code>FactoryBean</code>} for creating a * native {@link #setCacheName(String) named} Infinispan {@link org.infinispan.Cache * <code>org.infinispan.Cache</code>}, delegating to a * {@link #setInfinispanRemoteCacheManager(RemoteCacheManager) <code>configurable</code>} * {@link RemoteCacheManager * <code>oorg.infinispan.client.hotrod.RemoteCacheManagerr</code>}. If no cache name is explicitly * set, this <code>FactoryBean</code>'s {@link #setBeanName(String) <code>beanName</code>} will be * used instead. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * */ public class InfinispanNamedRemoteCacheFactoryBean<K, V> implements FactoryBean<RemoteCache<K, V>>, BeanNameAware, InitializingBean { private static final Log logger = LogFactory.getLog(MethodHandles.lookup().lookupClass()); private RemoteCacheManager infinispanRemoteCacheManager; private String cacheName; private String beanName; private RemoteCache<K, V> infinispanCache; // ------------------------------------------------------------------------ // org.springframework.beans.factory.InitializingBean // ------------------------------------------------------------------------ /** * @see InitializingBean#afterPropertiesSet() */ @Override public void afterPropertiesSet() throws Exception { if (this.infinispanRemoteCacheManager == null) { throw new IllegalStateException("No Infinispan RemoteCacheManager has been set"); } this.logger.info("Initializing named Infinispan remote cache ..."); final String effectiveCacheName = obtainEffectiveCacheName(); this.infinispanCache = this.infinispanRemoteCacheManager.getCache(effectiveCacheName); this.logger.info("New Infinispan remote cache [" + this.infinispanCache + "] initialized"); } private String obtainEffectiveCacheName() { if (StringUtils.hasText(this.cacheName)) { if (this.logger.isDebugEnabled()) { this.logger.debug("Using custom cache name [" + this.cacheName + "]"); } return this.cacheName; } else { if (this.logger.isDebugEnabled()) { this.logger.debug("Using bean name [" + this.beanName + "] as cache name"); } return this.beanName; } } // ------------------------------------------------------------------------ // org.springframework.beans.factory.BeanNameAware // ------------------------------------------------------------------------ /** * @see BeanNameAware#setBeanName(String) */ @Override public void setBeanName(final String name) { this.beanName = name; } // ------------------------------------------------------------------------ // org.springframework.beans.factory.FactoryBean // ------------------------------------------------------------------------ /** * @see FactoryBean#getObject() */ @Override public RemoteCache<K, V> getObject() { return this.infinispanCache; } /** * @see FactoryBean#getObjectType() */ @Override public Class<? extends ConcurrentMap> getObjectType() { return this.infinispanCache != null ? this.infinispanCache.getClass() : RemoteCache.class; } /** * Always return true. * * @see FactoryBean#isSingleton() */ @Override public boolean isSingleton() { return true; } // ------------------------------------------------------------------------ // Properties // ------------------------------------------------------------------------ /** * <p> * Sets the {@link org.infinispan.Cache#getName() name} of the {@link org.infinispan.Cache * <code>org.infinispan.Cache</code>} to be created. If no explicit <code>cacheName</code> is * set, this <code>FactoryBean</code> will use its {@link #setBeanName(String) * <code>beanName</code>} as the <code>cacheName</code>. * </p> * * @param cacheName * The {@link org.infinispan.Cache#getName() name} of the {@link org.infinispan.Cache * <code>org.infinispan.Cache</code>} to be created */ public void setCacheName(final String cacheName) { this.cacheName = cacheName; } /** * <p> * Sets the {@link RemoteCacheManager * <code>org.infinispan.client.hotrod.RemoteCacheManager</code>} to be used for creating our * {@link org.infinispan.Cache <code>Cache</code>} instance. Note that this is a * <strong>mandatory</strong> property. * </p> * * @param infinispanRemoteCacheManager * The {@link RemoteCacheManager * <code>org.infinispan.client.hotrod.RemoteCacheManager</code>} to be used for * creating our {@link org.infinispan.Cache <code>Cache</code>} instance */ public void setInfinispanRemoteCacheManager(final RemoteCacheManager infinispanRemoteCacheManager) { this.infinispanRemoteCacheManager = infinispanRemoteCacheManager; } }
5,655
35.727273
103
java
null
infinispan-main/spring/spring6/spring6-remote/src/main/java/org/infinispan/spring/remote/provider/SpringRemoteCacheManagerFactoryBean.java
package org.infinispan.spring.remote.provider; import java.util.Properties; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.spring.remote.AbstractRemoteCacheManagerFactory; import org.infinispan.spring.remote.ConfigurationPropertiesOverrides; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; /** * <p> * A {@link FactoryBean <code>FactoryBean</code>} for creating an * {@link SpringRemoteCacheManager * <code>SpringRemoteCacheManager</code>} instance. * </p> * <strong>Configuration</strong><br/> * <p> * A <code>SpringRemoteCacheManager</code> is configured through a {@link Properties * <code>Properties</code>} object. For an exhaustive list of valid properties to be used see * <code>RemoteCacheManager</code>'s {@link RemoteCacheManager * javadocs}. This <code>FactoryBean</code> provides means to either * {@link #setConfigurationProperties(Properties) inject} a user-defined <code>Properties</code> * instance or to * {@link #setConfigurationPropertiesFileLocation(org.springframework.core.io.Resource) set} the * location of a properties file to load those properties from. Note that it is <em>illegal</em> to * use both mechanisms simultaneously. * </p> * <p> * Alternatively or in combination with * {@link #setConfigurationPropertiesFileLocation(org.springframework.core.io.Resource) setting} the * location of a <code>Properties</code> file to load the configuration from, this * <code>FactoryBean</code> provides (typed) setters for all configuration settings. Settings thus * defined take precedence over those defined in the injected <code>Properties</code> instance. This * flexibility enables users to use e.g. a company-wide <code>Properties</code> file containing * default settings while simultaneously overriding select settings whenever special requirements * warrant this.<br/> * Note that it is illegal to use setters in conjunction with * {@link #setConfigurationProperties(Properties) injecting} a <code>Properties</code> instance. * </p> * <p> * In addition to creating a <code>SpringRemoteCacheManager</code> this <code>FactoryBean</code> * does also control that <code>SpringRemoteCacheManager</code>'s lifecycle by shutting it down when * the enclosing Spring application context is closed. It is therefore advisable to <em>always</em> * use this <code>FactoryBean</code> when creating an <code>SpringRemoteCacheManager</code>. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * * @see RemoteCacheManager * @see #destroy() */ public class SpringRemoteCacheManagerFactoryBean extends AbstractRemoteCacheManagerFactory implements FactoryBean<SpringRemoteCacheManager>, InitializingBean, DisposableBean { private SpringRemoteCacheManager springRemoteCacheManager; // ------------------------------------------------------------------------ // org.springframework.beans.factory.InitializingBean // ------------------------------------------------------------------------ /** * @see InitializingBean#afterPropertiesSet() */ @Override public void afterPropertiesSet() throws Exception { assertCorrectlyConfigured(); this.logger.info("Creating new instance of RemoteCacheManager ..."); final Properties configurationPropertiesToUse = configurationProperties(); org.infinispan.client.hotrod.configuration.ConfigurationBuilder clientBuilder = new org.infinispan.client.hotrod.configuration.ConfigurationBuilder(); clientBuilder.withProperties(configurationPropertiesToUse); long readTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)) readTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_READ_TIMEOUT)); else readTimeout = 0; long writeTimeout; if (configurationPropertiesToUse.containsKey(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)) writeTimeout = Long.parseLong(configurationPropertiesToUse.getProperty(ConfigurationPropertiesOverrides.OPERATION_WRITE_TIMEOUT)); else writeTimeout = 0; final RemoteCacheManager nativeRemoteCacheManager = new RemoteCacheManager( clientBuilder.build(), this.startAutomatically); this.springRemoteCacheManager = new SpringRemoteCacheManager(nativeRemoteCacheManager, readTimeout, writeTimeout); this.logger.info("Finished creating new instance of RemoteCacheManager"); } // ------------------------------------------------------------------------ // org.springframework.beans.factory.FactoryBean // ------------------------------------------------------------------------ /** * @see FactoryBean#getObject() */ @Override public SpringRemoteCacheManager getObject() throws Exception { return this.springRemoteCacheManager; } /** * @see FactoryBean#getObjectType() */ @Override public Class<? extends SpringRemoteCacheManager> getObjectType() { return this.springRemoteCacheManager != null ? this.springRemoteCacheManager.getClass() : SpringRemoteCacheManager.class; } /** * Always return <code>true</code>. * * @see FactoryBean#isSingleton() */ @Override public boolean isSingleton() { return true; } // ------------------------------------------------------------------------ // org.springframework.beans.factory.DisposableBean // ------------------------------------------------------------------------ /** * {@link RemoteCacheManager#stop() <code>stop</code>} the * <code>RemoteCacheManager</code> created by this factory. * * @see DisposableBean#destroy() */ @Override public void destroy() throws Exception { // Being paranoid if (this.springRemoteCacheManager != null) { this.springRemoteCacheManager.stop(); } } }
6,104
42.920863
139
java
null
infinispan-main/spring/spring6/spring6-remote/src/main/java/org/infinispan/spring/remote/provider/ContainerRemoteCacheManagerFactoryBean.java
package org.infinispan.spring.remote.provider; import org.infinispan.client.hotrod.RemoteCacheManager; import org.springframework.beans.factory.FactoryBean; import org.springframework.cache.CacheManager; import org.springframework.util.Assert; /** * {@link FactoryBean} for creating a {@link CacheManager} for a pre-defined {@link org.infinispan.manager.CacheContainer}. * <p/> * Useful when the cache container is defined outside the application (e.g. provided by the application server) * * @author Marius Bogoevici */ public class ContainerRemoteCacheManagerFactoryBean implements FactoryBean<CacheManager> { private RemoteCacheManager cacheContainer; public ContainerRemoteCacheManagerFactoryBean(RemoteCacheManager cacheContainer) { Assert.notNull(cacheContainer, "CacheContainer cannot be null"); this.cacheContainer = cacheContainer; } @Override public CacheManager getObject() throws Exception { return new SpringRemoteCacheManager((RemoteCacheManager) this.cacheContainer); } @Override public Class<?> getObjectType() { return CacheManager.class; } @Override public boolean isSingleton() { return true; } }
1,196
28.925
123
java
null
infinispan-main/spring/spring6/spring6-remote/src/main/java/org/infinispan/spring/remote/provider/SpringRemoteCacheManager.java
package org.infinispan.spring.remote.provider; import java.util.Collection; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.infinispan.client.hotrod.RemoteCache; import org.infinispan.client.hotrod.RemoteCacheManager; import org.infinispan.client.hotrod.impl.MarshallerRegistry; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.logging.Log; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.commons.marshall.ProtoStreamMarshaller; import org.infinispan.commons.util.NullValue; import org.infinispan.protostream.BaseMarshaller; import org.infinispan.protostream.SerializationContext; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.spring.common.session.MapSessionProtoAdapter; import org.springframework.session.MapSession; import org.springframework.util.Assert; /** * <p> * A {@link org.springframework.cache.CacheManager <code>CacheManager</code>} implementation that is * backed by an {@link RemoteCacheManager * <code>Infinispan RemoteCacheManager</code>} instance. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @author Marius Bogoevici * */ public class SpringRemoteCacheManager implements org.springframework.cache.CacheManager { private final RemoteCacheManager nativeCacheManager; private final ConcurrentMap<String, SpringCache> springCaches = new ConcurrentHashMap<>(); private volatile long readTimeout; private volatile long writeTimeout; /** * @param nativeCacheManager the underlying cache manager */ public SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager, long readTimeout, long writeTimeout) { Assert.notNull(nativeCacheManager, "A non-null instance of EmbeddedCacheManager needs to be supplied"); this.nativeCacheManager = nativeCacheManager; this.readTimeout = readTimeout; this.writeTimeout = writeTimeout; configureMarshallers(nativeCacheManager); } public SpringRemoteCacheManager(final RemoteCacheManager nativeCacheManager) { this(nativeCacheManager, 0, 0); } /** * @see org.springframework.cache.CacheManager#getCache(String) */ @Override public SpringCache getCache(final String name) { final RemoteCache<Object, Object> nativeCache = this.nativeCacheManager.getCache(name); if (nativeCache == null) { springCaches.remove(name); return null; } return springCaches.computeIfAbsent(name, n -> new SpringCache(nativeCache, readTimeout, writeTimeout)); } /** * @see org.springframework.cache.CacheManager#getCacheNames() */ @Override public Collection<String> getCacheNames() { return this.nativeCacheManager.getCacheNames(); } /** * Return the {@link RemoteCacheManager * <code>org.infinispan.client.hotrod.RemoteCacheManager</code>} that backs this * <code>SpringRemoteCacheManager</code>. * * @return The {@link RemoteCacheManager * <code>org.infinispan.client.hotrod.RemoteCacheManager</code>} that backs this * <code>SpringRemoteCacheManager</code> */ public RemoteCacheManager getNativeCacheManager() { return this.nativeCacheManager; } public long getReadTimeout() { return this.readTimeout; } public long getWriteTimeout() { return this.writeTimeout; } public void setReadTimeout(final long readTimeout) { this.readTimeout = readTimeout; } public void setWriteTimeout(final long writeTimeout) { this.writeTimeout = writeTimeout; } /** * Start the {@link RemoteCacheManager * <code>org.infinispan.client.hotrod.RemoteCacheManager</code>} that backs this * <code>SpringRemoteCacheManager</code>. */ public void start() { this.nativeCacheManager.start(); } /** * Stop the {@link RemoteCacheManager * <code>org.infinispan.client.hotrod.RemoteCacheManager</code>} that backs this * <code>SpringRemoteCacheManager</code>. */ public void stop() { this.nativeCacheManager.stop(); this.springCaches.clear(); } private void configureMarshallers(RemoteCacheManager nativeCacheManager) { MarshallerRegistry marshallerRegistry = nativeCacheManager.getMarshallerRegistry(); // Java serialization support JavaSerializationMarshaller serializationMarshaller = (JavaSerializationMarshaller) marshallerRegistry.getMarshaller(MediaType.APPLICATION_SERIALIZED_OBJECT); if (serializationMarshaller == null) { // Register a JavaSerializationMarshaller if it doesn't exist yet // Because some session attributes are always marshalled with Java serialization serializationMarshaller = new JavaSerializationMarshaller(); marshallerRegistry.registerMarshaller(serializationMarshaller); } // Extend deserialization allow list ClassAllowList serializationAllowList = new ClassAllowList(); serializationAllowList.addClasses(NullValue.class); serializationAllowList.addRegexps("java.util\\..*", "org.springframework\\..*"); serializationMarshaller.initialize(serializationAllowList); // Protostream support ProtoStreamMarshaller protoMarshaller = (ProtoStreamMarshaller) marshallerRegistry.getMarshaller(MediaType.APPLICATION_PROTOSTREAM); if (protoMarshaller == null) { try { protoMarshaller = new ProtoStreamMarshaller(); marshallerRegistry.registerMarshaller(protoMarshaller); // Apply the serialization context initializers in the configuration first SerializationContext ctx = protoMarshaller.getSerializationContext(); for (SerializationContextInitializer sci : nativeCacheManager.getConfiguration().getContextInitializers()) { sci.registerSchema(ctx); sci.registerMarshallers(ctx); } } catch (NoClassDefFoundError e) { // Ignore the error, the protostream dependency is missing } } if (protoMarshaller != null) { // Apply our own serialization context initializers SerializationContext ctx = protoMarshaller.getSerializationContext(); addSessionContextInitializerAndMarshaller(ctx, serializationMarshaller); } } private void addSessionContextInitializerAndMarshaller(SerializationContext ctx, JavaSerializationMarshaller serializationMarshaller) { // Skip registering the marshallers if the MapSession class is not available try { new MapSession(); } catch (NoClassDefFoundError e) { Log.CONFIG.debug("spring-session classes not found, skipping the session context initializer registration"); return; } org.infinispan.spring.common.session.PersistenceContextInitializerImpl sessionSci = new org.infinispan.spring.common.session.PersistenceContextInitializerImpl(); sessionSci.registerMarshallers(ctx); sessionSci.registerSchema(ctx); BaseMarshaller sessionAttributeMarshaller = new MapSessionProtoAdapter.SessionAttributeRawMarshaller(serializationMarshaller); ctx.registerMarshaller(sessionAttributeMarshaller); } }
7,567
38.212435
120
java
null
infinispan-main/spring/spring6/spring6-common/src/test/java/org/junit/ComparisonFailure.java
package org.junit; /** * Avoid Junit and TestNG dependency * **/ public class ComparisonFailure extends AssertionError { /** * The maximum length for expected and actual strings. If it is exceeded, the strings should be shortened. * * @see ComparisonCompactor */ private static final int MAX_CONTEXT_LENGTH = 20; private static final long serialVersionUID = 1L; /* * We have to use the f prefix until the next major release to ensure * serialization compatibility. * See https://github.com/junit-team/junit4/issues/976 */ private String fExpected; private String fActual; /** * Constructs a comparison failure. * * @param message the identifying message or null * @param expected the expected string value * @param actual the actual string value */ public ComparisonFailure(String message, String expected, String actual) { super(message); this.fExpected = expected; this.fActual = actual; } /** * Returns "..." in place of common prefix and "..." in place of common suffix between expected and actual. * * @see Throwable#getMessage() */ @Override public String getMessage() { return new ComparisonCompactor(MAX_CONTEXT_LENGTH, fExpected, fActual).compact(super.getMessage()); } /** * Returns the actual string value * * @return the actual string value */ public String getActual() { return fActual; } /** * Returns the expected string value * * @return the expected string value */ public String getExpected() { return fExpected; } private static class ComparisonCompactor { private static final String ELLIPSIS = "..."; private static final String DIFF_END = "]"; private static final String DIFF_START = "["; /** * The maximum length for <code>expected</code> and <code>actual</code> strings to show. When * <code>contextLength</code> is exceeded, the Strings are shortened. */ private final int contextLength; private final String expected; private final String actual; /** * @param contextLength the maximum length of context surrounding the difference between the compared strings. * When context length is exceeded, the prefixes and suffixes are compacted. * @param expected the expected string value * @param actual the actual string value */ public ComparisonCompactor(int contextLength, String expected, String actual) { this.contextLength = contextLength; this.expected = expected; this.actual = actual; } public String compact(String message) { if (expected == null || actual == null || expected.equals(actual)) { return format(message, expected, actual); } else { DiffExtractor extractor = new DiffExtractor(); String compactedPrefix = extractor.compactPrefix(); String compactedSuffix = extractor.compactSuffix(); return format(message, compactedPrefix + extractor.expectedDiff() + compactedSuffix, compactedPrefix + extractor.actualDiff() + compactedSuffix); } } static String format(String message, Object expected, Object actual) { String formatted = ""; if (message != null) { formatted = message + " "; } return formatted + "expected:<" + expected + "> but was:<" + actual + ">"; } private String sharedPrefix() { int end = Math.min(expected.length(), actual.length()); for (int i = 0; i < end; i++) { if (expected.charAt(i) != actual.charAt(i)) { return expected.substring(0, i); } } return expected.substring(0, end); } private String sharedSuffix(String prefix) { int suffixLength = 0; int maxSuffixLength = Math.min(expected.length() - prefix.length(), actual.length() - prefix.length()) - 1; for (; suffixLength <= maxSuffixLength; suffixLength++) { if (expected.charAt(expected.length() - 1 - suffixLength) != actual.charAt(actual.length() - 1 - suffixLength)) { break; } } return expected.substring(expected.length() - suffixLength); } private class DiffExtractor { private final String sharedPrefix; private final String sharedSuffix; /** * Can not be instantiated outside {@link ComparisonCompactor}. */ private DiffExtractor() { sharedPrefix = sharedPrefix(); sharedSuffix = sharedSuffix(sharedPrefix); } public String expectedDiff() { return extractDiff(expected); } public String actualDiff() { return extractDiff(actual); } public String compactPrefix() { if (sharedPrefix.length() <= contextLength) { return sharedPrefix; } return ELLIPSIS + sharedPrefix.substring(sharedPrefix.length() - contextLength); } public String compactSuffix() { if (sharedSuffix.length() <= contextLength) { return sharedSuffix; } return sharedSuffix.substring(0, contextLength) + ELLIPSIS; } private String extractDiff(String source) { return DIFF_START + source.substring(sharedPrefix.length(), source.length() - sharedSuffix.length()) + DIFF_END; } } } }
5,696
31.369318
116
java
null
infinispan-main/spring/spring6/spring6-common/src/test/java/org/infinispan/spring/common/InfinispanTestExecutionListener.java
package org.infinispan.spring.common; import org.infinispan.commons.test.TestResourceTracker; import org.springframework.test.context.TestContext; import org.springframework.test.context.support.AbstractTestExecutionListener; /** * Ensures that we register with {@link TestResourceTracker} within the lifecycle of Spring Context tests. This is * because Spring calls createCacheManager from the superclass BeforeClass method and we need to manipulate the tracker * beforehand. */ public class InfinispanTestExecutionListener extends AbstractTestExecutionListener { @Override public void beforeTestClass(TestContext testContext) throws Exception { TestResourceTracker.testStarted(testContext.getTestClass().getName()); } @Override public void afterTestClass(TestContext testContext) throws Exception { TestResourceTracker.testFinished(testContext.getTestClass().getName()); } }
915
37.166667
119
java
null
infinispan-main/spring/spring6/spring6-common/src/test/java/org/infinispan/spring/common/session/InfinispanApplicationPublishedBridgeTCK.java
package org.infinispan.spring.common.session; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNull; import java.time.Duration; import java.util.List; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.spring.common.session.AbstractInfinispanSessionRepository.InfinispanSession; import org.infinispan.spring.common.session.util.EventsWaiter; import org.infinispan.test.AbstractInfinispanTest; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.PayloadApplicationEvent; import org.springframework.session.events.SessionCreatedEvent; import org.springframework.session.events.SessionDeletedEvent; import org.springframework.session.events.SessionDestroyedEvent; import org.springframework.session.events.SessionExpiredEvent; import org.testng.annotations.Test; public abstract class InfinispanApplicationPublishedBridgeTCK extends AbstractInfinispanTest { protected SpringCache springCache; protected AbstractInfinispanSessionRepository sessionRepository; protected abstract SpringCache createSpringCache(); protected abstract void callEviction(); protected abstract AbstractInfinispanSessionRepository createRepository(SpringCache springCache) throws Exception; @Test public void testEventBridge() throws Exception { //given EventsCollector eventsCollector = new EventsCollector(); sessionRepository.setApplicationEventPublisher(eventsCollector); //when InfinispanSession sessionToBeDeleted = sessionRepository.createSession(); sessionToBeDeleted.setAttribute("foo", "bar"); sessionRepository.save(sessionToBeDeleted); InfinispanSession sessionToBeExpired = sessionRepository.createSession(); sessionToBeExpired.setMaxInactiveInterval(Duration.ofSeconds(1)); sessionRepository.save(sessionToBeExpired); sessionRepository.save(sessionToBeDeleted); sessionRepository.deleteById(sessionToBeDeleted.getId()); // Attempt to delete a non present session sessionRepository.deleteById("not-present"); sleepOneSecond(); callEviction(); //then assertNull(springCache.get(sessionToBeExpired.getId())); assertNull(springCache.get(sessionToBeDeleted.getId())); EventsWaiter.assertNumberOfEvents(() -> eventsCollector.getEvents(), SessionCreatedEvent.class, 2, 2, TimeUnit.SECONDS); EventsWaiter.assertNumberOfEvents(() -> eventsCollector.getEvents(), SessionDeletedEvent.class, 1, 2, TimeUnit.SECONDS); EventsWaiter.assertNumberOfEvents(() -> eventsCollector.getEvents(), SessionDestroyedEvent.class, 1, 10, TimeUnit.SECONDS); EventsWaiter.assertNumberOfEvents(() -> eventsCollector.getEvents(), SessionExpiredEvent.class, 1, 2, TimeUnit.SECONDS); EventsWaiter.assertSessionContent(() -> eventsCollector.getEvents(), SessionDeletedEvent.class, sessionToBeDeleted.getId(), "foo", "bar", 2, TimeUnit.SECONDS); } @Test public void testEventBridgeWithSessionIdChange() throws Exception { EventsCollector eventsCollector = new EventsCollector(); sessionRepository.setApplicationEventPublisher(eventsCollector); InfinispanSession session = sessionRepository.createSession(); sessionRepository.save(session); session.changeSessionId(); sessionRepository.save(session); EventsWaiter.assertNumberOfEvents(() -> eventsCollector.getEvents(), SessionCreatedEvent.class, 2, 2, TimeUnit.SECONDS); EventsWaiter.assertNumberOfEvents(() -> eventsCollector.getEvents(), SessionDeletedEvent.class, 0, 2, TimeUnit.SECONDS); EventsWaiter.assertNumberOfEvents(() -> eventsCollector.getEvents(), SessionDestroyedEvent.class, 0, 2, TimeUnit.SECONDS); EventsWaiter.assertNumberOfEvents(() -> eventsCollector.getEvents(), SessionExpiredEvent.class, 0, 2, TimeUnit.SECONDS); } protected void init() throws Exception { springCache = createSpringCache(); sessionRepository = createRepository(springCache); } private void sleepOneSecond() { long oneSecondSleep = System.currentTimeMillis() + 1000; eventually(() -> System.currentTimeMillis() > oneSecondSleep); } @Test public void testUnregistration() throws Exception { //given EventsCollector eventsCollector = new EventsCollector(); sessionRepository.setApplicationEventPublisher(eventsCollector); //when sessionRepository.destroy(); //simulate closing app context InfinispanSession sessionToBeExpired = sessionRepository.createSession(); sessionRepository.save(sessionToBeExpired); //then assertEquals(eventsCollector.getEvents().count(), 0); } static class EventsCollector implements ApplicationEventPublisher { private List<ApplicationEvent> events = new CopyOnWriteArrayList<>(); @Override public void publishEvent(ApplicationEvent event) { events.add(event); } @Override public void publishEvent(Object event) { publishEvent(new PayloadApplicationEvent<>(this, event)); } public Stream<ApplicationEvent> getEvents() { return events.stream(); } } }
5,399
39.601504
165
java
null
infinispan-main/spring/spring6/spring6-common/src/test/java/org/infinispan/spring/common/session/InfinispanSessionRepositoryTCK.java
package org.infinispan.spring.common.session; import static org.springframework.session.FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNotSame; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertTrue; import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.concurrent.TimeUnit; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.spring.common.session.AbstractInfinispanSessionRepository.InfinispanSession; import org.infinispan.test.AbstractInfinispanTest; import org.springframework.session.FindByIndexNameSessionRepository; import org.springframework.session.FlushMode; import org.springframework.session.SaveMode; import org.testng.annotations.Test; @Test(groups = "functional") public abstract class InfinispanSessionRepositoryTCK extends AbstractInfinispanTest { protected SpringCache springCache; protected AbstractInfinispanSessionRepository sessionRepository; protected MediaType mediaType; protected InfinispanSessionRepositoryTCK mediaType(MediaType mediaType) { this.mediaType = mediaType; return this; } @Override protected String parameters() { return mediaType.toString(); } protected abstract SpringCache createSpringCache(); protected abstract AbstractInfinispanSessionRepository createRepository(SpringCache springCache) throws Exception; protected void init() throws Exception { springCache = createSpringCache(); sessionRepository = createRepository(springCache); } @Test(expectedExceptions = NullPointerException.class) public void testThrowingExceptionOnNullSpringCache() throws Exception { createRepository(null); } @Test public void testCreatingSession() throws Exception { //when InfinispanSession session = sessionRepository.createSession(); //then assertNotNull(session.getId()); assertNotNull(session.getCreationTime()); assertNull(sessionRepository.findById(session.getId())); } @Test public void testSavingNewSession() throws Exception { //given InfinispanSession session = sessionRepository.createSession(); Instant lastAccessedTime = session.getLastAccessedTime(); Duration maxInactiveInterval = session.getMaxInactiveInterval(); //when sessionRepository.save(session); //then InfinispanSession savedSession = sessionRepository.findById(session.getId()); assertNotNull(savedSession); assertTrue(savedSession.getAttributeNames().isEmpty()); assertEquals( lastAccessedTime.truncatedTo(ChronoUnit.MILLIS), savedSession.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS)); assertEquals(maxInactiveInterval, savedSession.getMaxInactiveInterval()); } @Test public void testSavingUnchangedSession() throws Exception { //given InfinispanSession session = sessionRepository.createSession(); Instant lastAccessedTime = session.getLastAccessedTime(); Duration maxInactiveInterval = session.getMaxInactiveInterval(); sessionRepository.save(session); //when session = sessionRepository.findById(session.getId()); sessionRepository.save(session); //then InfinispanSession updatedSession = sessionRepository.findById(session.getId()); assertTrue(updatedSession.getAttributeNames().isEmpty()); assertEquals( lastAccessedTime.truncatedTo(ChronoUnit.MILLIS), updatedSession.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS)); assertEquals(maxInactiveInterval, updatedSession.getMaxInactiveInterval()); } @Test public void testSavingSessionWithUpdatedMaxInactiveInterval() throws Exception { //given InfinispanSession session = sessionRepository.createSession(); sessionRepository.save(session); //when session = sessionRepository.findById(session.getId()); Duration newMaxInactiveInterval = Duration.ofSeconds(123); session.setMaxInactiveInterval(newMaxInactiveInterval); sessionRepository.save(session); //then InfinispanSession savedSession = sessionRepository.findById(session.getId()); assertEquals(newMaxInactiveInterval, savedSession.getMaxInactiveInterval()); } @Test public void testSavingSessionWithUpdatedLastAccessedTime() throws Exception { //given InfinispanSession session = sessionRepository.createSession(); sessionRepository.save(session); //when session = sessionRepository.findById(session.getId()); Instant newLastAccessedTime = Instant.now().minusSeconds(300); session.setLastAccessedTime(newLastAccessedTime); sessionRepository.save(session); //then InfinispanSession savedSession = sessionRepository.findById(session.getId()); assertEquals( newLastAccessedTime.truncatedTo(ChronoUnit.MILLIS), savedSession.getLastAccessedTime().truncatedTo(ChronoUnit.MILLIS)); } @Test public void testSavingSessionWithUpdatedAttributes() throws Exception { //given InfinispanSession session = sessionRepository.createSession(); session.setAttribute("changed", "oldValue"); session.setAttribute("removed", "existingValue"); sessionRepository.save(session); //when session = sessionRepository.findById(session.getId()); session.setAttribute("added", "addedValue"); session.setAttribute("changed", "newValue"); session.removeAttribute("removed"); sessionRepository.save(session); //then InfinispanSession savedSession = sessionRepository.findById(session.getId()); assertEquals(savedSession.getAttribute("added"), "addedValue"); assertEquals(savedSession.getAttribute("changed"), "newValue"); assertNull(savedSession.getAttribute("removed")); } @Test public void testUpdatingTTLOnAccessingData() throws Exception { //when InfinispanSession session = sessionRepository.createSession(); long accessTimeBeforeSaving = session.getLastAccessedTime().toEpochMilli(); sessionRepository.save(session); long accessTimeAfterSaving = session.getLastAccessedTime().toEpochMilli(); long accessTimeAfterAccessing = sessionRepository.findById(session.getId()).getLastAccessedTime().toEpochMilli(); long now = Instant.now().toEpochMilli(); //then assertTrue(accessTimeBeforeSaving > 0); assertTrue(accessTimeBeforeSaving <= now); assertTrue(accessTimeAfterSaving > 0); assertTrue(accessTimeAfterSaving <= now); assertTrue(accessTimeAfterAccessing > 0); assertTrue(accessTimeAfterAccessing >= accessTimeAfterSaving); } @Test public void testDeletingSession() throws Exception { //when InfinispanSession session = sessionRepository.createSession(); sessionRepository.save(session); sessionRepository.deleteById(session.getId()); //then assertNull(sessionRepository.findById(session.getId())); } @Test(timeOut = 5000) public void testEvictingSession() throws Exception { //when InfinispanSession session = sessionRepository.createSession(); session.setMaxInactiveInterval(Duration.ofSeconds(1)); sessionRepository.save(session); //then while (sessionRepository.findById(session.getId()) != null) { TimeUnit.MILLISECONDS.sleep(500); } } @Test public void testExtractingPrincipalWithWrongIndexName() throws Exception { //when int sizeWithWrongIndexName = ((FindByIndexNameSessionRepository) sessionRepository).findByIndexNameAndIndexValue("wrongIndexName", "").size(); int sizeWithNullIndexName = ((FindByIndexNameSessionRepository) sessionRepository).findByIndexNameAndIndexValue(null, "").size(); //then assertEquals(0, sizeWithNullIndexName); assertEquals(0, sizeWithWrongIndexName); } @Test public void testExtractingPrincipal() throws Exception { //given addEmptySessionWithPrincipal(sessionRepository, "test1"); addEmptySessionWithPrincipal(sessionRepository, "test2"); addEmptySessionWithPrincipal(sessionRepository, "test3"); //when int numberOfTest1Users = ((FindByIndexNameSessionRepository) sessionRepository) .findByIndexNameAndIndexValue(PRINCIPAL_NAME_INDEX_NAME, "test1").size(); int numberOfNonExistingUsers = ((FindByIndexNameSessionRepository) sessionRepository) .findByIndexNameAndIndexValue(PRINCIPAL_NAME_INDEX_NAME, "notExisting").size(); //then assertEquals(1, numberOfTest1Users); assertEquals(0, numberOfNonExistingUsers); } @Test public void testChangeSessionId() throws Exception { //given InfinispanSession session = sessionRepository.createSession(); //when String originalId = session.getId(); sessionRepository.save(session); session.changeSessionId(); String newId = session.getId(); sessionRepository.save(session); //then assertNotNull(sessionRepository.findById(newId)); assertNull(sessionRepository.findById(originalId)); // Save again to test that the deletion doesn't fail when the session isn't in the repo sessionRepository.save(session ); assertNotNull(sessionRepository.findById(newId)); assertNull(sessionRepository.findById(originalId)); } @Test public void testConcurrentSessionAccess() { //given InfinispanSession session = sessionRepository.createSession(); // setLastAccessedTime will be called by Spring Session's SessionRepositoryRequestWrapper.getSession session.setLastAccessedTime(Instant.now()); session.setAttribute("testAttribute", "oldValue"); sessionRepository.save(session); //when InfinispanSession slowRequestSession = sessionRepository.findById(session.getId()); slowRequestSession.setLastAccessedTime(Instant.now()); slowRequestSession.getAttribute("testAttribute"); InfinispanSession fastRequestSession = sessionRepository.findById(session.getId()); fastRequestSession.setLastAccessedTime(Instant.now()); fastRequestSession.setAttribute("testAttribute", "fastValue"); sessionRepository.save(fastRequestSession); sessionRepository.save(slowRequestSession); //then assertNotSame(slowRequestSession, fastRequestSession); InfinispanSession updatedSession = sessionRepository.findById(session.getId()); assertEquals("fastValue", updatedSession.getAttribute("testAttribute")); } @Test public void testConcurrentSessionAccessWithSaveModeOnGetAttribute() { //given sessionRepository.setSaveMode(SaveMode.ON_GET_ATTRIBUTE); InfinispanSession session = sessionRepository.createSession(); // setLastAccessedTime will be called by Spring Session's SessionRepositoryRequestWrapper.getSession session.setLastAccessedTime(Instant.now()); session.setAttribute("testAttribute", "oldValue"); sessionRepository.save(session); //when InfinispanSession slowRequestSession = sessionRepository.findById(session.getId()); slowRequestSession.setLastAccessedTime(Instant.now()); slowRequestSession.getAttribute("testAttribute"); InfinispanSession fastRequestSession = sessionRepository.findById(session.getId()); fastRequestSession.setLastAccessedTime(Instant.now()); fastRequestSession.setAttribute("testAttribute", "fastValue"); sessionRepository.save(fastRequestSession); sessionRepository.save(slowRequestSession); //then assertNotSame(slowRequestSession, fastRequestSession); InfinispanSession updatedSession = sessionRepository.findById(session.getId()); assertEquals("oldValue", updatedSession.getAttribute("testAttribute")); } @Test public void testConcurrentSessionAccessWithSaveModeAlways() { //given sessionRepository.setSaveMode(SaveMode.ALWAYS); InfinispanSession session = sessionRepository.createSession(); // setLastAccessedTime will be called by Spring Session's SessionRepositoryRequestWrapper.getSession session.setLastAccessedTime(Instant.now()); session.setAttribute("testAttribute", "oldValue"); sessionRepository.save(session); //when InfinispanSession slowRequestSession = sessionRepository.findById(session.getId()); slowRequestSession.setLastAccessedTime(Instant.now()); InfinispanSession fastRequestSession = sessionRepository.findById(session.getId()); fastRequestSession.setLastAccessedTime(Instant.now()); fastRequestSession.setAttribute("testAttribute", "fastValue"); sessionRepository.save(fastRequestSession); sessionRepository.save(slowRequestSession); //then assertNotSame(slowRequestSession, fastRequestSession); InfinispanSession updatedSession = sessionRepository.findById(session.getId()); assertEquals("oldValue", updatedSession.getAttribute("testAttribute")); } @Test public void testFlushModeImmediate() throws Exception { //given sessionRepository.setFlushMode(FlushMode.IMMEDIATE); InfinispanSession existingSession = sessionRepository.createSession(); //when InfinispanSession newSession = sessionRepository.createSession(); existingSession.setAttribute("testAttribute", "testValue"); //then InfinispanSession savedNewSession = sessionRepository.findById(newSession.getId()); assertNotNull(savedNewSession); InfinispanSession savedExistingSession = sessionRepository.findById(existingSession.getId()); assertEquals("testValue", savedExistingSession.getAttribute("testAttribute")); } protected void addEmptySessionWithPrincipal(AbstractInfinispanSessionRepository sessionRepository, String principalName) { InfinispanSession session = sessionRepository.createSession(); session.setAttribute(PRINCIPAL_NAME_INDEX_NAME, principalName); sessionRepository.save(session); } }
14,381
38.729282
148
java
null
infinispan-main/spring/spring6/spring6-common/src/test/java/org/infinispan/spring/common/session/util/EventsWaiter.java
package org.infinispan.spring.common.session.util; import static org.testng.AssertJUnit.assertEquals; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import org.springframework.context.ApplicationEvent; import org.springframework.session.Session; import org.springframework.session.events.AbstractSessionEvent; public class EventsWaiter { public static void assertNumberOfEvents(Supplier<Stream<ApplicationEvent>> eventCollector, Class<? extends AbstractSessionEvent> eventClass, int expectedNumberOfEvents, int timeout, TimeUnit timeoutUnit) { long stopTime = System.currentTimeMillis() + timeoutUnit.toMillis(timeout); long eventsCollected = -1; while (System.currentTimeMillis() < stopTime) { eventsCollected = eventCollector.get() .filter(e -> e.getClass() == eventClass) .count(); if (expectedNumberOfEvents == eventsCollected) { return; } } throw new AssertionError("Expected " + expectedNumberOfEvents + " events of a class " + eventClass.getSimpleName() + " but found " + eventsCollected); } public static void assertSessionContent(Supplier<Stream<ApplicationEvent>> eventCollector, Class<? extends AbstractSessionEvent> eventClass, String sessionId, String attName, String attValue, int timeout, TimeUnit timeoutUnit) { long stopTime = System.currentTimeMillis() + timeoutUnit.toMillis(timeout); List<Session> sessions = null; while (System.currentTimeMillis() < stopTime) { sessions = eventCollector.get() .filter(e -> e.getClass() == eventClass) .map(e -> eventClass.cast(e)) .filter(e -> e.getSessionId().equals(sessionId)) .map(e -> (Session) e.getSession()) .collect(Collectors.toList()); if (sessions.size() > 0) { break; } } assertEquals(1, sessions.size()); assertEquals(attValue, sessions.get(0).getAttribute(attName)); } }
2,562
38.430769
156
java
null
infinispan-main/spring/spring6/spring6-common/src/main/java/org/infinispan/spring/common/package-info.java
/** * <h1>Spring Infinispan - Shared classes.</h1> * <p> * This package contains classes that are shared between the two major themes underlying <em>Spring Infinispan</em>: * <ol> * <li> * Implement a provider for <a href="http://www.springsource.com">Spring</a> Cache abstraction backed by the open-source * high-performance distributed cache <a href="http://www.jboss.org/infinispan">JBoss Infinispan</a>.<br/><br/> * See package {@link org.infinispan.spring.common.provider <code>org.infinispan.spring.provider</code>}.<br/><br/> * </li> * <li> * Provide implementations of Spring's {@link org.springframework.beans.factory.FactoryBean <code>FactoryBean</code>} * interface for easing usage of JBoss Infinispan within the Spring programming model.<br/><br/> * </li> * <li> * Provide implementations of Spring's Session * {@link org.springframework.session.SessionRepository <code>SessionRepository</code>} interface for session * management with Spring and Spring Security. * </li> * </ol> * </p> */ package org.infinispan.spring.common;
1,106
45.125
124
java
null
infinispan-main/spring/spring6/spring6-common/src/main/java/org/infinispan/spring/common/config/InfinispanRemoteCacheManagerBeanDefinitionParser.java
package org.infinispan.spring.common.config; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.util.StringUtils; import org.w3c.dom.Element; /** * @author Marius Bogoevici */ public class InfinispanRemoteCacheManagerBeanDefinitionParser extends AbstractBeanDefinitionParser { private static final String DEFAULT_CACHE_MANAGER_BEAN_NAME = "cacheManager"; private static final String CACHE_MANAGER_CLASS = "org.infinispan.spring.remote.provider.SpringRemoteCacheManagerFactoryBean"; @Override protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(CACHE_MANAGER_CLASS); String configFileLocation = element.getAttribute("configuration"); if (StringUtils.hasText(configFileLocation)) { beanDefinitionBuilder.addPropertyValue("configurationPropertiesFileLocation", configFileLocation); } return beanDefinitionBuilder.getBeanDefinition(); } @Override protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) throws BeanDefinitionStoreException { String id = element.getAttribute("id"); if (!StringUtils.hasText(id)) { id = DEFAULT_CACHE_MANAGER_BEAN_NAME; } return id; } }
1,678
40.975
148
java
null
infinispan-main/spring/spring6/spring6-common/src/main/java/org/infinispan/spring/common/config/InfinispanContainerCacheManagerBeanDefinitionParser.java
package org.infinispan.spring.common.config; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.parsing.BeanComponentDefinition; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.util.StringUtils; import org.w3c.dom.Element; /** * @author Marius Bogoevici */ public class InfinispanContainerCacheManagerBeanDefinitionParser extends AbstractBeanDefinitionParser { private static final String DEFAULT_CACHE_MANAGER_BEAN_NAME = "cacheManager"; private static final String FACTORY_BEAN_CLASS = "org.infinispan.spring.embedded.provider.ContainerEmbeddedCacheManagerFactoryBean"; @Override protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(FACTORY_BEAN_CLASS); String cacheContainerRef = element.getAttribute("cache-container-ref"); BeanComponentDefinition innerBean = InfinispanNamespaceUtils.parseInnerBeanDefinition(element, parserContext); if (innerBean != null) { parserContext.registerBeanComponent(innerBean); } if ((!StringUtils.hasText(cacheContainerRef) && innerBean == null) || (StringUtils.hasText(cacheContainerRef) && innerBean != null)) { parserContext.getReaderContext().error("Exactly one of the 'cache-container-ref' attribute " + "or an inner bean definition is required for a 'container-cache-manager' element", element); } beanDefinitionBuilder.addConstructorArgReference(innerBean != null ? innerBean.getBeanName() : cacheContainerRef); return beanDefinitionBuilder.getBeanDefinition(); } @Override protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) throws BeanDefinitionStoreException { String id = element.getAttribute("id"); if (!StringUtils.hasText(id)) { id = DEFAULT_CACHE_MANAGER_BEAN_NAME; } return id; } }
2,303
47
148
java
null
infinispan-main/spring/spring6/spring6-common/src/main/java/org/infinispan/spring/common/config/InfinispanNamespaceHandler.java
package org.infinispan.spring.common.config; import org.springframework.beans.factory.xml.NamespaceHandlerSupport; /** * {@link org.springframework.beans.factory.xml.NamespaceHandler} for Infinispan-based caches. * * @author Marius Bogoevici */ public class InfinispanNamespaceHandler extends NamespaceHandlerSupport { @Override public void init() { registerBeanDefinitionParser("embedded-cache-manager", new InfinispanEmbeddedCacheManagerBeanDefinitionParser()); registerBeanDefinitionParser("remote-cache-manager", new InfinispanRemoteCacheManagerBeanDefinitionParser()); registerBeanDefinitionParser("container-cache-manager", new InfinispanContainerCacheManagerBeanDefinitionParser()); } }
729
35.5
121
java
null
infinispan-main/spring/spring6/spring6-common/src/main/java/org/infinispan/spring/common/config/InfinispanEmbeddedCacheManagerBeanDefinitionParser.java
package org.infinispan.spring.common.config; import org.springframework.beans.factory.BeanDefinitionStoreException; import org.springframework.beans.factory.support.AbstractBeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; import org.springframework.beans.factory.xml.AbstractBeanDefinitionParser; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.util.StringUtils; import org.w3c.dom.Element; /** * @author Marius Bogoevici */ public class InfinispanEmbeddedCacheManagerBeanDefinitionParser extends AbstractBeanDefinitionParser { private static final String DEFAULT_CACHE_MANAGER_BEAN_NAME = "cacheManager"; private static final String CACHE_MANAGER_CLASS = "org.infinispan.spring.embedded.provider.SpringEmbeddedCacheManagerFactoryBean"; @Override protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.rootBeanDefinition(CACHE_MANAGER_CLASS); String configFileLocation = element.getAttribute("configuration"); if (StringUtils.hasText(configFileLocation)) { beanDefinitionBuilder.addPropertyValue("configurationFileLocation", configFileLocation); } return beanDefinitionBuilder.getBeanDefinition(); } @Override protected String resolveId(Element element, AbstractBeanDefinition definition, ParserContext parserContext) throws BeanDefinitionStoreException { String id = element.getAttribute("id"); if (!StringUtils.hasText(id)) { id = DEFAULT_CACHE_MANAGER_BEAN_NAME; } return id; } }
1,673
41.923077
148
java
null
infinispan-main/spring/spring6/spring6-common/src/main/java/org/infinispan/spring/common/config/InfinispanNamespaceUtils.java
package org.infinispan.spring.common.config; import java.util.List; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.config.BeanDefinitionHolder; import org.springframework.beans.factory.parsing.BeanComponentDefinition; import org.springframework.beans.factory.xml.BeanDefinitionParserDelegate; import org.springframework.beans.factory.xml.ParserContext; import org.springframework.util.xml.DomUtils; import org.w3c.dom.Element; /** * @author Marius Bogoevici */ public class InfinispanNamespaceUtils { public static BeanComponentDefinition parseInnerBeanDefinition(Element element, ParserContext parserContext) { List<Element> childElements = DomUtils.getChildElementsByTagName(element, "bean"); BeanComponentDefinition innerComponentDefinition = null; if (childElements != null && childElements.size() == 1) { Element beanElement = childElements.get(0); if (!"http://www.springframework.org/schema/beans".equals(beanElement.getNamespaceURI())) { throw new IllegalStateException("Illegal inner child element"); } BeanDefinitionParserDelegate delegate = parserContext.getDelegate(); BeanDefinitionHolder beanDefinitionHolder = delegate.parseBeanDefinitionElement(beanElement); beanDefinitionHolder = delegate.decorateBeanDefinitionIfRequired(beanElement, beanDefinitionHolder); BeanDefinition beanDefinition = beanDefinitionHolder.getBeanDefinition(); innerComponentDefinition = new BeanComponentDefinition(beanDefinition, beanDefinitionHolder.getBeanName()); } return innerComponentDefinition; } }
1,682
45.75
116
java
null
infinispan-main/spring/spring6/spring6-common/src/main/java/org/infinispan/spring/common/session/PrincipalNameResolver.java
package org.infinispan.spring.common.session; import static org.springframework.session.FindByIndexNameSessionRepository.PRINCIPAL_NAME_INDEX_NAME; import org.springframework.expression.Expression; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.session.Session; /** * Extracts Principal Name from Session. This needs to be done separately since Spring Session is not aware of any * authentication mechanism (it is application developer's responsibility to implement it). * * @author Sebastian Łaskawiec * @see org.springframework.session.FindByIndexNameSessionRepository * @since 9.0 */ public class PrincipalNameResolver { private static final PrincipalNameResolver INSTANCE = new PrincipalNameResolver(); private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT"; private final SpelExpressionParser parser = new SpelExpressionParser(); public static PrincipalNameResolver getInstance() { return INSTANCE; } /** * Resolves Principal Name (e.g. user name) based on session. * * @param session Session to be checked. * @return Extracted Principal Name */ public String resolvePrincipal(Session session) { String principalName = session.getAttribute(PRINCIPAL_NAME_INDEX_NAME); if (principalName != null) { return principalName; } Object authentication = session.getAttribute(SPRING_SECURITY_CONTEXT); if (authentication != null) { Expression expression = parser.parseExpression("authentication?.name"); return expression.getValue(authentication, String.class); } return null; } }
1,689
34.208333
114
java
null
infinispan-main/spring/spring6/spring6-common/src/main/java/org/infinispan/spring/common/session/PersistenceContextInitializer.java
package org.infinispan.spring.common.session; import org.infinispan.protostream.SerializationContextInitializer; import org.infinispan.protostream.annotations.AutoProtoSchemaBuilder; /** * Interface used to initialise a {@link org.infinispan.protostream.SerializationContext} using the specified Pojos, * Marshaller implementations and provided .proto schemas. * * @author Dan Berindei * @since 12.1 */ @AutoProtoSchemaBuilder( includeClasses = { MapSessionProtoAdapter.class, MapSessionProtoAdapter.SessionAttribute.class, SessionUpdateRemappingFunctionProtoAdapter.class, }, schemaFileName = "persistence.spring6.session.proto", schemaFilePath = "proto/generated", schemaPackageName = "org.infinispan.persistence.spring.session", service = false ) public interface PersistenceContextInitializer extends SerializationContextInitializer { }
921
34.461538
116
java
null
infinispan-main/spring/spring6/spring6-common/src/main/java/org/infinispan/spring/common/session/SessionUpdateRemappingFunction.java
package org.infinispan.spring.common.session; import org.springframework.session.MapSession; import java.io.Serializable; import java.time.Duration; import java.time.Instant; import java.util.Map; import java.util.function.BiFunction; public class SessionUpdateRemappingFunction implements BiFunction<String, MapSession, MapSession>, Serializable { private static final long serialVersionUID = 1L; private Instant lastAccessedTime; private Duration maxInactiveInterval; private Map<String, Object> delta; @Override public MapSession apply(final String key, final MapSession value) { if (value == null) { return null; } if (this.lastAccessedTime != null) { value.setLastAccessedTime(this.lastAccessedTime); } if (this.maxInactiveInterval != null) { value.setMaxInactiveInterval(this.maxInactiveInterval); } if (this.delta != null) { for (final Map.Entry<String, Object> attribute : this.delta.entrySet()) { if (attribute.getValue() != null) { value.setAttribute(attribute.getKey(), attribute.getValue()); } else { value.removeAttribute(attribute.getKey()); } } } return value; } Instant getLastAccessedTime() { return lastAccessedTime; } void setLastAccessedTime(final Instant lastAccessedTime) { this.lastAccessedTime = lastAccessedTime; } Duration getMaxInactiveInterval() { return maxInactiveInterval; } void setMaxInactiveInterval(final Duration maxInactiveInterval) { this.maxInactiveInterval = maxInactiveInterval; } Map<String, Object> getDelta() { return delta; } void setDelta(final Map<String, Object> delta) { this.delta = delta; } }
1,814
26.5
113
java
null
infinispan-main/spring/spring6/spring6-common/src/main/java/org/infinispan/spring/common/session/AbstractInfinispanSessionRepository.java
package org.infinispan.spring.common.session; import java.time.Duration; import java.time.Instant; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.TimeUnit; import org.infinispan.commons.api.BasicCache; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.spring.common.session.AbstractInfinispanSessionRepository.InfinispanSession; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.session.DelegatingIndexResolver; import org.springframework.session.FindByIndexNameSessionRepository; import org.springframework.session.FlushMode; import org.springframework.session.IndexResolver; import org.springframework.session.MapSession; import org.springframework.session.PrincipalNameIndexResolver; import org.springframework.session.SaveMode; import org.springframework.session.Session; import org.springframework.session.SessionRepository; import org.springframework.util.Assert; /** * Infinispan implementation for Spring Session with basic functionality. * * @author Sebastian Łaskawiec * @see <a href="http://projects.spring.io/spring-session">Spring Session Web Page</a> * @see SessionRepository * @see ApplicationEventPublisherAware * @see FindByIndexNameSessionRepository * @since 9.0 */ public abstract class AbstractInfinispanSessionRepository implements FindByIndexNameSessionRepository<InfinispanSession>, ApplicationEventPublisherAware, InitializingBean, DisposableBean { private static final String SPRING_SECURITY_CONTEXT = "SPRING_SECURITY_CONTEXT"; protected final AbstractApplicationPublisherBridge applicationEventPublisher; protected final SpringCache cache; protected final BasicCache<String, MapSession> nativeCache; protected Duration defaultMaxInactiveInterval = Duration.ofSeconds(MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS); protected FlushMode flushMode = FlushMode.ON_SAVE; protected SaveMode saveMode = SaveMode.ON_SET_ATTRIBUTE; protected IndexResolver<Session> indexResolver = new DelegatingIndexResolver<>(new PrincipalNameIndexResolver<>()); protected AbstractInfinispanSessionRepository(SpringCache cache, AbstractApplicationPublisherBridge eventsBridge) { Objects.requireNonNull(cache, "SpringCache can not be null"); Objects.requireNonNull(eventsBridge, "EventBridge can not be null"); applicationEventPublisher = eventsBridge; this.cache = cache; nativeCache = (BasicCache<String, MapSession>) cache.getNativeCache(); } @Override public void afterPropertiesSet() { applicationEventPublisher.registerListener(); } @Override public void destroy() { applicationEventPublisher.unregisterListener(); } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher.setApplicationEventPublisher(applicationEventPublisher); } /** * Set the maximum inactive interval in seconds between requests before newly created sessions * will be invalidated. A negative time indicates that the session will never time out. The * default is 30 minutes. * * @param defaultMaxInactiveInterval the default maxInactiveInterval */ public void setDefaultMaxInactiveInterval(final Duration defaultMaxInactiveInterval) { Assert.notNull(defaultMaxInactiveInterval, "defaultMaxInactiveInterval must not be null"); this.defaultMaxInactiveInterval = defaultMaxInactiveInterval; } /** * Set the {@link IndexResolver} to use. * * @param indexResolver the index resolver */ public void setIndexResolver(final IndexResolver<Session> indexResolver) { Assert.notNull(indexResolver, "indexResolver cannot be null"); this.indexResolver = indexResolver; } /** * Sets the flush mode. Default flush mode is {@link FlushMode#ON_SAVE}. * * @param flushMode the new Hazelcast flush mode */ public void setFlushMode(final FlushMode flushMode) { Assert.notNull(flushMode, "flushMode cannot be null"); this.flushMode = flushMode; } /** * Set the save mode. Default save mode is {@link SaveMode#ON_SET_ATTRIBUTE}. * * @param saveMode the save mode */ public void setSaveMode(final SaveMode saveMode) { Assert.notNull(saveMode, "saveMode must not be null"); this.saveMode = saveMode; } @Override public InfinispanSession createSession() { final MapSession cached = new MapSession(); cached.setMaxInactiveInterval(this.defaultMaxInactiveInterval); cached.setCreationTime(Instant.now()); final InfinispanSession session = new InfinispanSession(cached, true); session.flushImmediateIfNecessary(); return session; } @Override public void save(InfinispanSession session) { if (session.isNew) { nativeCache.put( session.getId(), session.getDelegate(), session.getMaxInactiveInterval().getSeconds(), TimeUnit.SECONDS); } else if (session.sessionIdChanged) { removeFromCacheWithoutNotifications(session.originalId); session.originalId = session.getId(); nativeCache.put( session.getId(), session.getDelegate(), session.getMaxInactiveInterval().getSeconds(), TimeUnit.SECONDS); } else if (session.hasChanges()) { final SessionUpdateRemappingFunction remappingFunction = new SessionUpdateRemappingFunction(); if (session.lastAccessedTimeChanged) { remappingFunction.setLastAccessedTime(session.getLastAccessedTime()); } if (session.maxInactiveIntervalChanged) { remappingFunction.setMaxInactiveInterval(session.getMaxInactiveInterval()); } if (!session.delta.isEmpty()) { remappingFunction.setDelta(new HashMap<>(session.delta)); } nativeCache.compute( session.getId(), remappingFunction, session.getMaxInactiveInterval().getSeconds(), TimeUnit.SECONDS); } session.clearChangeFlags(); } protected abstract void removeFromCacheWithoutNotifications(String originalId); @Override public InfinispanSession findById(String id) { final MapSession saved = nativeCache.get(id); if (saved == null) { return null; } if (saved.isExpired()) { deleteById(saved.getId()); return null; } return new InfinispanSession(saved, false); } @Override public void deleteById(String id) { final MapSession saved = nativeCache.get(id); if (saved != null) { applicationEventPublisher.emitSessionDeletedEvent(saved); nativeCache.remove(id); } } /** * A custom implementation of {@link Session} that uses a {@link MapSession} as the basis for its * mapping. It keeps track if changes have been made since last save. */ public final class InfinispanSession implements Session { private final MapSession delegate; private boolean isNew; private boolean sessionIdChanged; private boolean lastAccessedTimeChanged; private boolean maxInactiveIntervalChanged; private String originalId; private final Map<String, Object> delta = new HashMap<>(); public InfinispanSession(final MapSession cached, final boolean isNew) { this.delegate = isNew ? cached : new MapSession(cached); this.isNew = isNew; this.originalId = cached.getId(); if (this.isNew || (AbstractInfinispanSessionRepository.this.saveMode == SaveMode.ALWAYS)) { getAttributeNames() .forEach( (attributeName) -> this.delta.put(attributeName, cached.getAttribute(attributeName))); } } @Override public void setLastAccessedTime(final Instant lastAccessedTime) { this.delegate.setLastAccessedTime(lastAccessedTime); this.lastAccessedTimeChanged = true; flushImmediateIfNecessary(); } @Override public boolean isExpired() { return this.delegate.isExpired(); } @Override public Instant getCreationTime() { return this.delegate.getCreationTime(); } @Override public String getId() { return this.delegate.getId(); } @Override public String changeSessionId() { final String newSessionId = this.delegate.changeSessionId(); this.sessionIdChanged = true; return newSessionId; } @Override public Instant getLastAccessedTime() { return this.delegate.getLastAccessedTime(); } @Override public void setMaxInactiveInterval(final Duration interval) { this.delegate.setMaxInactiveInterval(interval); this.maxInactiveIntervalChanged = true; flushImmediateIfNecessary(); } @Override public Duration getMaxInactiveInterval() { return this.delegate.getMaxInactiveInterval(); } @Override public <T> T getAttribute(final String attributeName) { final T attributeValue = this.delegate.getAttribute(attributeName); if (attributeValue != null && AbstractInfinispanSessionRepository.this.saveMode.equals(SaveMode.ON_GET_ATTRIBUTE)) { this.delta.put(attributeName, attributeValue); } return attributeValue; } @Override public Set<String> getAttributeNames() { return this.delegate.getAttributeNames(); } @Override public void setAttribute(final String attributeName, final Object attributeValue) { this.delegate.setAttribute(attributeName, attributeValue); this.delta.put(attributeName, attributeValue); if (SPRING_SECURITY_CONTEXT.equals(attributeName)) { final Map<String, String> indexes = AbstractInfinispanSessionRepository.this.indexResolver.resolveIndexesFor(this); final String principal = (attributeValue != null) ? indexes.get(PRINCIPAL_NAME_INDEX_NAME) : null; this.delegate.setAttribute(PRINCIPAL_NAME_INDEX_NAME, principal); this.delta.put(PRINCIPAL_NAME_INDEX_NAME, principal); } flushImmediateIfNecessary(); } @Override public void removeAttribute(final String attributeName) { setAttribute(attributeName, null); } MapSession getDelegate() { return this.delegate; } boolean hasChanges() { return (this.lastAccessedTimeChanged || this.maxInactiveIntervalChanged || !this.delta.isEmpty()); } void clearChangeFlags() { this.isNew = false; this.lastAccessedTimeChanged = false; this.sessionIdChanged = false; this.maxInactiveIntervalChanged = false; this.delta.clear(); } private void flushImmediateIfNecessary() { if (AbstractInfinispanSessionRepository.this.flushMode == FlushMode.IMMEDIATE) { AbstractInfinispanSessionRepository.this.save(this); } } } }
11,606
34.713846
188
java
null
infinispan-main/spring/spring6/spring6-common/src/main/java/org/infinispan/spring/common/session/AbstractApplicationPublisherBridge.java
package org.infinispan.spring.common.session; import java.util.Objects; import java.util.Optional; import org.infinispan.commons.logging.Log; import org.infinispan.commons.logging.LogFactory; import org.infinispan.spring.common.provider.SpringCache; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; import org.springframework.session.Session; import org.springframework.session.events.SessionCreatedEvent; import org.springframework.session.events.SessionDeletedEvent; import org.springframework.session.events.SessionDestroyedEvent; import org.springframework.session.events.SessionExpiredEvent; /** * A bridge for passing events between Infinispan (both embedded and remote) and Spring. * * @author Sebastian Łaskawiec * @since 9.0 */ public abstract class AbstractApplicationPublisherBridge implements ApplicationEventPublisherAware { private static final Log logger = LogFactory.getLog(AbstractApplicationPublisherBridge.class); protected final SpringCache eventSource; protected Optional<ApplicationEventPublisher> springEventsPublisher = Optional.empty(); protected AbstractApplicationPublisherBridge(SpringCache eventSource) { Objects.requireNonNull(eventSource); this.eventSource = eventSource; } protected abstract void registerListener(); public abstract void unregisterListener(); protected void emitSessionCreatedEvent(Session session) { logger.debugf("Emitting session created %s", session.getId()); springEventsPublisher.ifPresent(p -> p.publishEvent(new SessionCreatedEvent(eventSource, session))); } protected void emitSessionExpiredEvent(Session session) { logger.debugf("Emitting session expired %s", session.getId()); springEventsPublisher.ifPresent(p -> p.publishEvent(new SessionExpiredEvent(eventSource, session))); } protected void emitSessionDestroyedEvent(Session session) { logger.debugf("Emitting session destroyed %s", session.getId()); springEventsPublisher.ifPresent(p -> p.publishEvent(new SessionDestroyedEvent(eventSource, session))); } protected void emitSessionDeletedEvent(Session session) { logger.debugf("Emitting session deleted %s", session.getId()); springEventsPublisher.ifPresent(p -> p.publishEvent(new SessionDeletedEvent(eventSource, session))); } @Override public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) { springEventsPublisher = Optional.ofNullable(applicationEventPublisher); } }
2,592
40.822581
108
java
null
infinispan-main/spring/spring6/spring6-common/src/main/java/org/infinispan/spring/common/session/SessionUpdateRemappingFunctionProtoAdapter.java
package org.infinispan.spring.common.session; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.protostream.annotations.ProtoAdapter; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; import org.infinispan.spring.common.session.MapSessionProtoAdapter.SessionAttribute; import java.time.Duration; import java.time.Instant; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; /** * Protostream adapter for {@link SessionUpdateRemappingFunction}. * * <p>Attribute values set by the application should be marshalled with Protostream, but Java Serialization * is also supported.</p> * <p>Attribute values set by spring-session internally have not been converted to use Protostream, * so they are always marshalled using Java Serialization.</p> * <p>Note: Each attribute value uses either Protostream or Java Serialization for marshalling. * Mixing Protostream and Java Serialization in the same attribute is not supported.</p> */ @ProtoAdapter(SessionUpdateRemappingFunction.class) @ProtoTypeId(ProtoStreamTypeIds.SPRING_SESSION_REMAP) public class SessionUpdateRemappingFunctionProtoAdapter { @ProtoFactory static SessionUpdateRemappingFunction createFunction(Collection<SessionAttribute> attributes, Instant lastAccessedTime, Long maxInactiveSeconds) { SessionUpdateRemappingFunction function = new SessionUpdateRemappingFunction(); function.setLastAccessedTime(lastAccessedTime); if (maxInactiveSeconds != null) { function.setMaxInactiveInterval(Duration.ofSeconds(maxInactiveSeconds)); } Map<String,Object> delta = new HashMap<>(); for (SessionAttribute attribute : attributes) { delta.put(attribute.getName(), attribute.getValue()); } function.setDelta(delta); return function; } @ProtoField(number = 1) Instant getLastAccessedTime(SessionUpdateRemappingFunction function) { return function.getLastAccessedTime(); } @ProtoField(number = 2) Long getMaxInactiveSeconds(SessionUpdateRemappingFunction function) { return function.getMaxInactiveInterval() == null ? null : function.getMaxInactiveInterval().getSeconds(); } @ProtoField(number = 3) Collection<SessionAttribute> getAttributes(SessionUpdateRemappingFunction function) { if (function.getDelta() == null) { return Collections.emptyList(); } return function.getDelta().entrySet().stream() .map(entry -> new SessionAttribute(entry.getKey(), entry.getValue())) .collect(Collectors.toList()); } }
2,784
41.19697
149
java
null
infinispan-main/spring/spring6/spring6-common/src/main/java/org/infinispan/spring/common/session/MapSessionProtoAdapter.java
package org.infinispan.spring.common.session; import java.io.IOException; import java.time.Duration; import java.time.Instant; import java.util.Collection; import java.util.Objects; import java.util.stream.Collectors; import org.infinispan.commons.CacheException; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.commons.marshall.ProtoStreamTypeIds; import org.infinispan.protostream.ProtobufTagMarshaller; import org.infinispan.protostream.TagReader; import org.infinispan.protostream.WrappedMessage; import org.infinispan.protostream.annotations.ProtoAdapter; import org.infinispan.protostream.annotations.ProtoFactory; import org.infinispan.protostream.annotations.ProtoField; import org.infinispan.protostream.annotations.ProtoTypeId; import org.infinispan.protostream.annotations.impl.GeneratedMarshallerBase; import org.infinispan.protostream.impl.SerializationContextImpl; import org.springframework.session.MapSession; /** * Protostream adapter for Spring's {@link MapSession}. * * <p>Attribute values set by the application should be marshalled with Protostream, but Java Serialization * is also supported.</p> * <p>Attribute values set by spring-session internally have not been converted to use Protostream, * so they are always marshalled using Java Serialization.</p> * <p>Note: Each attribute value uses either Protostream or Java Serialization for marshalling. * Mixing Protostream and Java Serialization in the same attribute is not supported.</p> * * @author Dan Berindei * @since 12.1 */ @ProtoAdapter(MapSession.class) @ProtoTypeId(ProtoStreamTypeIds.SPRING_SESSION) public class MapSessionProtoAdapter { @ProtoFactory static MapSession createSession(String id, String originalId, Collection<SessionAttribute> attributes, Instant creationTime, Instant lastAccessedTime, long maxInactiveSeconds) { MapSession session = new MapSession(originalId); session.setId(id); session.setCreationTime(creationTime); session.setLastAccessedTime(lastAccessedTime); session.setMaxInactiveInterval(Duration.ofSeconds(maxInactiveSeconds)); for (SessionAttribute attribute : attributes) { session.setAttribute(attribute.getName(), attribute.getValue()); } return session; } @ProtoField(number = 1) String getId(MapSession session) { return session.getId(); } @ProtoField(number = 2) String getOriginalId(MapSession session) { if (Objects.equals(session.getOriginalId(), session.getId())) return null; return session.getOriginalId(); } @ProtoField(number = 3, defaultValue = "0") Instant getCreationTime(MapSession session) { return session.getCreationTime(); } @ProtoField(number = 4, defaultValue = "0") Instant getLastAccessedTime(MapSession session) { return session.getLastAccessedTime(); } @ProtoField(number = 5, defaultValue = "-1") long getMaxInactiveSeconds(MapSession session) { return session.getMaxInactiveInterval().getSeconds(); } @ProtoField(number = 6) Collection<SessionAttribute> getAttributes(MapSession session) { return session.getAttributeNames().stream() .map(name -> new SessionAttribute(name, session.getAttribute(name))) .collect(Collectors.toList()); } @ProtoTypeId(ProtoStreamTypeIds.SPRING_SESSION_ATTRIBUTE) public static class SessionAttribute { private final String name; private final Object value; @ProtoFactory SessionAttribute(String name, WrappedMessage wrappedMessage, byte[] serializedBytes) { throw new IllegalStateException("Custom marshaller not registered!"); } public SessionAttribute(String name, Object value) { this.name = name; this.value = value; } @ProtoField(number = 1) public String getName() { return name; } public Object getValue() { return value; } @ProtoField(number = 2) public WrappedMessage getWrappedMessage() { return new WrappedMessage(value); } @ProtoField(number = 3) public byte[] getSerializedBytes() { throw new IllegalStateException("Custom marshaller not registered!"); } } /** * Generated with protostream-processor and then adapted to use {@code JavaSerializationMarshaller}. * * <p>A raw marshaller is necessary because we need a {@code JavaSerializationMarshaller} instance, * and {@link MapSessionProtoAdapter} must be stateless.</p> */ public static final class SessionAttributeRawMarshaller extends GeneratedMarshallerBase implements ProtobufTagMarshaller<SessionAttribute> { private final JavaSerializationMarshaller javaSerializationMarshaller; private org.infinispan.protostream.impl.BaseMarshallerDelegate<WrappedMessage> wrappedMessageDelegate; public SessionAttributeRawMarshaller(JavaSerializationMarshaller javaSerializationMarshaller) { this.javaSerializationMarshaller = javaSerializationMarshaller; } @Override public Class<MapSessionProtoAdapter.SessionAttribute> getJavaClass() { return MapSessionProtoAdapter.SessionAttribute.class; } @Override public String getTypeName() { return "org.infinispan.persistence.spring.SessionAttribute"; } @Override public MapSessionProtoAdapter.SessionAttribute read(ReadContext ctx) throws IOException { TagReader in = ctx.getReader(); String name = null; boolean done = false; Object value = null; while (!done) { final int tag = in.readTag(); switch (tag) { case 0: done = true; break; case 10: { name = in.readString(); break; } case 18: { if (wrappedMessageDelegate == null) { wrappedMessageDelegate = ((SerializationContextImpl) ctx.getSerializationContext()).getMarshallerDelegate(WrappedMessage.class); } int length = in.readRawVarint32(); int oldLimit = in.pushLimit(length); WrappedMessage wrappedMessage = readMessage(wrappedMessageDelegate, ctx); value = wrappedMessage.getValue(); in.checkLastTagWas(0); in.popLimit(oldLimit); break; } case 26: { byte[] serializedBytes = in.readByteArray(); value = deserializeValue(serializedBytes); break; } default: { if (!in.skipField(tag)) done = true; } } } return new MapSessionProtoAdapter.SessionAttribute(name, value); } @Override public void write(WriteContext ctx, MapSessionProtoAdapter.SessionAttribute attribute) throws IOException { final String name = attribute.getName(); if (name != null) ctx.getWriter().writeString(1, name); Object value = attribute.getValue(); if (value != null) { if (ctx.getSerializationContext().canMarshall(value.getClass())) { // The attribute value is an application class that can be marshalled with Protostream final WrappedMessage wrappedMessage = new WrappedMessage(value); if (wrappedMessageDelegate == null) { wrappedMessageDelegate = ((SerializationContextImpl) ctx.getSerializationContext()).getMarshallerDelegate(WrappedMessage.class); } writeNestedMessage(wrappedMessageDelegate, ctx, 2, wrappedMessage); } else { // The attribute value cannot be marshalled with Protostream, but Java Serialization should work // E.g. all sessions have a org.springframework.security.core.context.SecurityContext attribute byte[] serializedBytes = serializeValue(value); ctx.getWriter().writeBytes(3, serializedBytes); } } } private byte[] serializeValue(Object value) throws IOException { final byte[] serializedBytes; try { serializedBytes = javaSerializationMarshaller.objectToByteBuffer(value); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new CacheException(e); } return serializedBytes; } private Object deserializeValue(byte[] serializedBytes) { try { return javaSerializationMarshaller.objectFromByteBuffer(serializedBytes); } catch (IOException | ClassNotFoundException e) { throw new CacheException(e); } } } }
8,949
37.247863
180
java
null
infinispan-main/spring/spring6/spring6-common/src/main/java/org/infinispan/spring/common/provider/package-info.java
/** * <h1>Spring Infinispan - An implementation of Spring's Cache SPI based on JBoss Infinispan.</h1> * <p> * Spring 3.1 introduces caching capabilities a user may comfortably utilize via a set of custom annotations, thus telling * the Spring runtime which objects to cache under which circumstances.</br> * Out of the box, Spring ships with <a href="">EHCache</a> as the caching provider to delegate to. It defines, however, a * simple SPI vendors may implement for their own caching solution, thus enabling Spring users to swap out the default * EHCache for another cache of their choosing. This SPI comprises two interfaces: * <ul> * <li> * {@link org.springframework.cache.Cache <code>Cache</code>}, Spring's cache abstraction itself, and * </li> * <li> * {@link org.springframework.cache.CacheManager <code>CacheManager</code>}, a service for creating <code>Cache</code> * instances * </li> * </ul> * <em>Spring Infinispan</em> implements this SPI for JBoss Infinispan. * </p> * <p> * While <em>Spring Infinispan</em> offers only one implementation of <code>org.springframework.cache.Cache</code>, namely * {@link org.infinispan.spring.common.provider.SpringCache <code>org.infinispan.spring.common.provider.SpringCache</code>}, there are two implementations * of <code>org.springframework.cache.CacheManager</code>: * <ol> * <li> * {@link org.infinispan.spring.provider.SpringEmbeddedCacheManager <code>org.infinispan.spring.provider.SpringEmbeddedCacheManager</code>} * and * </li> * <li> * {@link org.infinispan.spring.provider.SpringRemoteCacheManager <code>org.infinispan.spring.provider.SpringRemoteCacheManager</code>}. * </li> * </ol> * These two implementations cover two distinct use cases: * <ol> * <li> * <strong>Embedded</strong>: Embed your Spring-powered application into the same JVM running an Infinispan node, i.e. every * communication between application code and Infinispan is in-process. Infinispan supports this use case via the interface * {@link org.infinispan.manager.EmbeddedCacheManager <code>org.infinispan.manager.EmbeddedCacheManager</code>} and its default * implementation {@link org.infinispan.manager.DefaultCacheManager <code>org.infinispan.manager.DefaultCacheManager</code>}. The * latter backs {@link org.infinispan.spring.provider.SpringEmbeddedCacheManager <code>SpringEmbeddedCacheManager</code>}. * </li> * <li> * <strong>Remote</strong>: Application code accesses Infinispan nodes remotely using Infinispan's own <em>hotrod</em> * protocol. Infinispan supports this use case via {@link org.infinispan.client.hotrod.RemoteCacheManager * <code>org.infinispan.client.hotrod.RemoteCacheManager</code>}. {@link org.infinispan.spring.provider.SpringRemoteCacheManager * <code>SpringRemoteCacheManager</code>} delegates to it. * </li> * </ol> * </p> * <strong>Usage</strong> * <p> * Using <em>Spring Infinispan</em> as a Spring Cache provider may be divided into two broad areas: * <ol> * <li> * Telling the Spring runtime to use <em>Spring Infinispan</em> and therefore Infinispan as its caching provider. * </li> * <li> * Using Spring's caching annotations in you application code. * </li> * </ol> * </p> * <p> * <em>Register Spring Infinispan with the Spring runtime</em> * <p> * Suppose we want to use <em>Spring Infinispan</em> running in embedded mode as our caching provider, and suppose further that * we want to create two named cache instances, &quot;cars&quot; and &quot;planes&quot;. To that end, we put * <pre> * &lt;beans xmlns="http://www.springframework.org/schema/beans" * xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" * xmlns:cache="http://www.springframework.org/schema/cache" * xmlns:p="http://www.springframework.org/schema/p" * xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd * http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"&gt; * &lt;cache:annotation-driven /&gt; * * &lt;bean id="cacheManager" class="org.infinispan.spring.SpringEmbeddedCacheManagerFactoryBean" * p:configuration-file-location="classpath:/org/infinispan/spring/embedded/example/infinispan-sample-config.xml"/&gt; * * &lt;/beans&gt; * </pre> * in our Spring application context. It is important to note that <code>classpath:/org/infinispan/spring/embedded/example/infinispan-sample-config.xml</code> * points to a configuration file in the standard Infinispan configuration format that includes sections for two named caches * &quot;cars&quot; and &quot;planes&quot;. If those sections are missing the above application context will still work, yet the * two caches &quot;cars&quot; and &quot;planes&quot; will be configured using the default settings defined in * <code>classpath:/org/infinispan/spring/embedded/example/infinispan-sample-config.xml</code>.<br/> * To further simplify our setup we may omit the reference to an Infinispan configuration file in which case the underlying * {@link org.infinispan.manager.EmbeddedCacheManager <code>org.infinispan.manager.EmbeddedCacheManager</code>} will use Infinispan's * default settings. * </p> * <p> * For more advanced ways to configure the underlying Infinispan <code>EmbeddedCacheManager</code> see * {@link org.infinispan.spring.provider.SpringEmbeddedCacheManagerFactoryBean <code>org.infinispan.spring.provider.SpringEmbeddedCacheManagerFactoryBean</code>}. * </p> * <p> * If running Infinispan in remote mode the above configuration changes to * <pre> * &lt;beans xmlns="http://www.springframework.org/schema/beans" * xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" * xmlns:cache="http://www.springframework.org/schema/cache" * xmlns:p="http://www.springframework.org/schema/p" * xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd * http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"&gt; * &lt;cache:annotation-driven /&gt; * * &lt;bean id="cacheManager" class="org.infinispan.spring.SpringEmbeddedCacheManagerFactoryBean" * p:configuration-properties-file-location="classpath:/org/infinispan/spring/remote/example/hotrod-client-sample.properties"/&gt; * * &lt;/beans&gt; * </pre> * </p> * <p> * For more advanced ways to configure the underlying Infinispan <code>RemoteCacheManager</code> see * {@link org.infinispan.spring.provider.SpringRemoteCacheManagerFactoryBean <code>org.infinispan.spring.provider.SpringRemoteCacheManagerFactoryBean</code>}. * </p> * <em>Using Spring's caching annotations in application code</em> * <p> * A detailed discussion about how to use Spring's caching annotations {@link org.springframework.cache.annotation.Cacheable <code>@Cacheable</code>} * and {@link org.springframework.cache.annotation.CacheEvict <code>@CacheEvict</code>} is beyond this documentation's scope. A simple example may * serve as a starting point: * <pre> * import org.springframework.cache.annotation.CacheEvict; * import org.springframework.cache.annotation.Cacheable; * import org.springframework.stereotype.Repository; * * &#064;Repository * public class CarRepository { * * &#064;Cacheable("cars") * public Car getCar(Long carId){ * ... * } * * &#064;CacheEvict(value="cars", key="car.id") * public void saveCar(Car car){ * ... * } * } * </pre> * In both <code>&#064;Cache("cars")</code> and <code>&#064;CacheEvict(value="cars", key="car.id")</code> &quot;cars&quot; refers to the name of the cache to either * store the returned <code>Car</code> instance in or to evict the saved/updated <code>Car</code> instance from. For a more detailed explanation of * how to use <code>&#064;Cacheable</code> and <code>&#064;CacheEvict</code> see the relevant reference documentation * <a href="http://docs.spring.io/spring/docs/3.2.9.RELEASE/spring-framework-reference/html/cache.html">chapter</a>. * </p> */ package org.infinispan.spring.common.provider;
8,321
56
164
java
null
infinispan-main/spring/spring6/spring6-common/src/main/java/org/infinispan/spring/common/provider/SpringCache.java
package org.infinispan.spring.common.provider; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.ReentrantLock; import org.infinispan.commons.CacheException; import org.infinispan.commons.api.BasicCache; import org.infinispan.commons.util.NullValue; import org.springframework.cache.Cache; import org.springframework.cache.support.SimpleValueWrapper; import org.springframework.util.Assert; /** * <p> * A {@link Cache <code>Cache</code>} implementation that delegates to a * {@link org.infinispan.Cache <code>org.infinispan.Cache</code>} instance supplied at construction * time. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @author <a href="mailto:marius.bogoevici@gmail.com">Marius Bogoevici</a> */ public class SpringCache implements Cache { public static final SimpleValueWrapper NULL_VALUE_WRAPPER = new SimpleValueWrapper(null); private final BasicCache nativeCache; private final long readTimeout; private final long writeTimeout; private final Map<Object, ReentrantLock> synchronousGetLocks = new ConcurrentHashMap<>(); /** * @param nativeCache underlying cache */ public SpringCache(BasicCache nativeCache) { this(nativeCache, 0, 0); } public SpringCache(BasicCache nativeCache, long readTimeout, long writeTimeout) { Assert.notNull(nativeCache, "A non-null Infinispan cache implementation is required"); this.nativeCache = nativeCache; this.readTimeout = readTimeout; this.writeTimeout = writeTimeout; } /** * @see Cache#getName() */ @Override public String getName() { return this.nativeCache.getName(); } /** * @see Cache#getNativeCache() */ @Override public BasicCache<?, ?> getNativeCache() { return this.nativeCache; } /** * @see Cache#get(Object) */ @Override public ValueWrapper get(final Object key) { try { if (readTimeout > 0) return encodedToValueWrapper(nativeCache.getAsync(key).get(readTimeout, TimeUnit.MILLISECONDS)); else return encodedToValueWrapper(nativeCache.get(key)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new CacheException(e); } catch (ExecutionException | TimeoutException e) { throw new CacheException(e); } } @Override public <T> T get(Object key, Class<T> type) { try { Object value; if (readTimeout > 0) value = nativeCache.getAsync(key).get(readTimeout, TimeUnit.MILLISECONDS); else value = nativeCache.get(key); value = decodeNull(value); if (value != null && type != null && !type.isInstance(value)) { throw new IllegalStateException("Cached value is not of required type [" + type.getName() + "]: " + value); } return (T) value; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new CacheException(e); } catch (ExecutionException | TimeoutException e) { throw new CacheException(e); } } @Override public <T> T get(Object key, Callable<T> valueLoader) { ReentrantLock lock; T value = (T) nativeCache.get(key); if (value == null) { lock = synchronousGetLocks.computeIfAbsent(key, k -> new ReentrantLock()); lock.lock(); try { if ((value = (T) nativeCache.get(key)) == null) { try { T newValue = valueLoader.call(); // we can't use computeIfAbsent here since in distributed embedded scenario we would // send a lambda to other nodes. This is the behavior we want to avoid. value = (T) nativeCache.putIfAbsent(key, encodeNull(newValue)); if (value == null) { value = newValue; } } catch (Exception e) { throw ValueRetrievalExceptionResolver.throwValueRetrievalException(key, valueLoader, e); } } } finally { lock.unlock(); synchronousGetLocks.remove(key); } } return decodeNull(value); } /** * @see Cache#put(Object, Object) */ @Override public void put(final Object key, final Object value) { try { if (writeTimeout > 0) this.nativeCache.putAsync(key, encodeNull(value)).get(writeTimeout, TimeUnit.MILLISECONDS); else this.nativeCache.put(key, encodeNull(value)); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new CacheException(e); } catch (ExecutionException | TimeoutException e) { throw new CacheException(e); } } /** * @see BasicCache#put(Object, Object, long, TimeUnit) */ public void put(Object key, Object value, long lifespan, TimeUnit unit) { try { if (writeTimeout > 0) this.nativeCache.putAsync(key, encodeNull(value), lifespan, unit).get(writeTimeout, TimeUnit.MILLISECONDS); else this.nativeCache.put(key, encodeNull(value), lifespan, unit); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new CacheException(e); } catch (ExecutionException | TimeoutException e) { throw new CacheException(e); } } @Override public ValueWrapper putIfAbsent(Object key, Object value) { try { if (writeTimeout > 0) return encodedToValueWrapper(this.nativeCache.putIfAbsentAsync(key, encodeNull(value)).get(writeTimeout, TimeUnit.MILLISECONDS)); else return encodedToValueWrapper(this.nativeCache.putIfAbsent(key, encodeNull(value))); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new CacheException(e); } catch (ExecutionException | TimeoutException e) { throw new CacheException(e); } } /** * @see Cache#evict(Object) */ @Override public void evict(final Object key) { try { if (writeTimeout > 0) this.nativeCache.removeAsync(key).get(writeTimeout, TimeUnit.MILLISECONDS); else this.nativeCache.remove(key); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new CacheException(e); } catch (ExecutionException | TimeoutException e) { throw new CacheException(e); } } /** * @see Cache#clear() */ @Override public void clear() { try { if (writeTimeout > 0) this.nativeCache.clearAsync().get(writeTimeout, TimeUnit.MILLISECONDS); else this.nativeCache.clear(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new CacheException(e); } catch (ExecutionException | TimeoutException e) { throw new CacheException(e); } } /** * @see Object#toString() */ @Override public String toString() { return "InfinispanCache [nativeCache = " + this.nativeCache + "]"; } private ValueWrapper encodedToValueWrapper(Object value) { if (value == null) { return null; } if (value == NullValue.NULL) { return NULL_VALUE_WRAPPER; } return new SimpleValueWrapper(value); } private Object encodeNull(Object value) { return value != null ? value : NullValue.NULL; } private <T> T decodeNull(Object value) { return value != NullValue.NULL ? (T) value : null; } //Implemented as a static holder class for backwards compatibility. //Imagine a situation where a client has new integration module and old Spring version. In that case //this exception does not exist. However we can bypass this by using separate class file (which is loaded //by the JVM when needed...) private static class ValueRetrievalExceptionResolver { static RuntimeException throwValueRetrievalException(Object key, Callable<?> loader, Throwable ex) { return new ValueRetrievalException(key, loader, ex); } } public long getWriteTimeout() { return writeTimeout; } }
8,575
31.608365
141
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/TestsModule.java
package org.infinispan.spring.embedded; import org.infinispan.factories.annotations.InfinispanModule; /** * {@code InfinispanModule} annotation is required for component annotation processing */ @InfinispanModule(name = "spring6-embedded-tests") public class TestsModule implements org.infinispan.lifecycle.ModuleLifecycle { }
331
29.181818
86
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/config/CacheLoaderNotFoundTest.java
package org.infinispan.spring.embedded.config; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.cache.CacheManager; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.testng.AssertJUnit.fail; /** * // TODO: Document this * * @author Galder Zamarreño * @since // TODO */ @Test(groups = "functional", testName = "spring.config.embedded.CacheLoaderNotFoundTest") @ContextConfiguration @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class CacheLoaderNotFoundTest extends AbstractTestNGSpringContextTests { @Autowired @Qualifier("cacheManager") private CacheManager cm; @BeforeClass @Override protected void springTestContextPrepareTestInstance() throws Exception { try { super.springTestContextPrepareTestInstance(); fail("Show have thrown an error indicating issues with the cache loader"); } catch (IllegalStateException e) { } } @Test public void testCacheManagerExists() { Assert.assertNull(cm); } }
1,660
32.897959
138
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/config/InfinispanContainerCacheManagerDefinitionTest.java
package org.infinispan.spring.embedded.config; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.cache.CacheManager; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.Assert; import org.testng.annotations.Test; /** * @author Marius Bogoevici */ @Test(groups = "functional", testName = "spring.config.embedded.InfinispanContainerCacheManagerDefinitionTest") @ContextConfiguration @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class InfinispanContainerCacheManagerDefinitionTest extends AbstractTestNGSpringContextTests { @Autowired @Qualifier("cacheManager") private CacheManager containerCacheManager; @Autowired @Qualifier("cacheManager2") private CacheManager containerCacheManager2; public void testContainerCacheManagerExists() { Assert.assertNotNull(containerCacheManager); Assert.assertNotNull(containerCacheManager2); } }
1,445
38.081081
138
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/config/InfinispanEmbeddedCacheManagerDefinitionTest.java
package org.infinispan.spring.embedded.config; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.cache.CacheManager; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.Assert; import org.testng.annotations.Test; /** * @author Marius Bogoevici */ @Test(groups = {"functional", "smoke"}, testName = "spring.config.embedded.InfinispanEmbeddedCacheManagerDefinitionTest") @ContextConfiguration @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class InfinispanEmbeddedCacheManagerDefinitionTest extends AbstractTestNGSpringContextTests { @Autowired @Qualifier("cacheManager") private CacheManager embeddedCacheManager; @Autowired @Qualifier("withConfigFile") private CacheManager embeddedCacheManagerWithConfigFile; public void testEmbeddedCacheManagerExists() { Assert.assertNotNull(embeddedCacheManager); Assert.assertNotNull(embeddedCacheManagerWithConfigFile); } }
1,477
37.894737
138
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/config/NonTransactionalCacheTest.java
package org.infinispan.spring.embedded.config; import static org.testng.AssertJUnit.assertEquals; import jakarta.annotation.Resource; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.springframework.cache.annotation.Cacheable; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.annotations.Test; /** * Non transaction cacheable test. * * @author Galder Zamarreño * @since 5.1 */ @Test(groups = {"functional", "smoke"}, testName = "spring.embedded.config.NonTransactionalCacheTest") @ContextConfiguration @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class NonTransactionalCacheTest extends AbstractTestNGSpringContextTests { public interface ICachedMock { Integer get(); } public static class CachedMock implements ICachedMock { private Integer value = 0; @Override @Cacheable(value = "cachedMock") public Integer get() { return ++this.value; } } @Resource(name = "mock") private ICachedMock mock; @Test public void testCalls() { assertEquals(Integer.valueOf(1), this.mock.get()); assertEquals(Integer.valueOf(1), this.mock.get()); } }
1,565
29.705882
138
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/config/DuplicateDomainAwareCacheManager.java
package org.infinispan.spring.embedded.config; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.factories.annotations.SurvivesRestarts; import org.infinispan.manager.DefaultCacheManager; /** * * @author gustavonalle * @since 7.0 */ @SurvivesRestarts public class DuplicateDomainAwareCacheManager extends DefaultCacheManager { public DuplicateDomainAwareCacheManager() { super(new GlobalConfigurationBuilder().build()); } }
486
24.631579
75
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/session/EmbeddedApplicationPublishedBridgeTest.java
package org.infinispan.spring.embedded.session; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.spring.common.session.AbstractInfinispanSessionRepository; import org.infinispan.spring.common.session.InfinispanApplicationPublishedBridgeTCK; import org.infinispan.spring.embedded.provider.BasicConfiguration; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; @Test(testName = "spring.embedded.session.EmbeddedApplicationPublishedBridgeTest", groups = "unit") @ContextConfiguration(classes = BasicConfiguration.class) @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class EmbeddedApplicationPublishedBridgeTest extends InfinispanApplicationPublishedBridgeTCK { private EmbeddedCacheManager embeddedCacheManager; @BeforeClass public void beforeClass() { embeddedCacheManager = TestCacheManagerFactory.createCacheManager(new ConfigurationBuilder()); } @AfterMethod public void afterMethod() { embeddedCacheManager.getCache().clear(); } @AfterClass public void afterClass() { embeddedCacheManager.stop(); } @BeforeMethod public void beforeMethod() throws Exception { super.init(); } @Override protected SpringCache createSpringCache() { return new SpringCache(embeddedCacheManager.getCache()); } @Override protected void callEviction() { embeddedCacheManager.getCache().getAdvancedCache().getExpirationManager().processExpiration(); } @Override protected AbstractInfinispanSessionRepository createRepository(SpringCache springCache) throws Exception { InfinispanEmbeddedSessionRepository sessionRepository = new InfinispanEmbeddedSessionRepository(springCache); sessionRepository.afterPropertiesSet(); return sessionRepository; } @Override public void testEventBridge() throws Exception { super.testEventBridge(); } @Override public void testUnregistration() throws Exception { super.testUnregistration(); } @Override public void testEventBridgeWithSessionIdChange() throws Exception { super.testEventBridgeWithSessionIdChange(); } }
2,760
34.397436
137
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/session/InfinispanEmbeddedProtostreamSessionRepositoryTest.java
package org.infinispan.spring.embedded.session; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.spring.common.session.AbstractInfinispanSessionRepository; import org.infinispan.spring.common.session.InfinispanSessionRepositoryTCK; import org.infinispan.spring.embedded.provider.BasicConfiguration; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test(testName = "spring.embedded.session.InfinispanEmbeddedProtostreamSessionRepositoryTest", groups = "unit") @ContextConfiguration(classes = BasicConfiguration.class) @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class InfinispanEmbeddedProtostreamSessionRepositoryTest extends InfinispanSessionRepositoryTCK { private EmbeddedCacheManager embeddedCacheManager; private EmbeddedCacheManager cacheManager2; private EmbeddedCacheManager cacheManager3; @Factory public Object[] factory() { return new Object[]{ new InfinispanEmbeddedProtostreamSessionRepositoryTest().mediaType(MediaType.APPLICATION_PROTOSTREAM), }; } @BeforeClass public void beforeClass() { ConfigurationBuilder defaultCacheBuilder = new ConfigurationBuilder(); defaultCacheBuilder.clustering().cacheMode(CacheMode.DIST_SYNC).encoding().mediaType(mediaType.getTypeSubtype()); embeddedCacheManager = TestCacheManagerFactory.createClusteredCacheManager(defaultCacheBuilder); cacheManager2 = TestCacheManagerFactory.createClusteredCacheManager(defaultCacheBuilder); cacheManager3 = TestCacheManagerFactory.createClusteredCacheManager(defaultCacheBuilder); } @AfterMethod public void afterMethod() { embeddedCacheManager.getCache().clear(); } @AfterClass public void afterClass() { embeddedCacheManager.stop(); cacheManager2.stop(); cacheManager3.stop(); } @BeforeMethod public void beforeMethod() throws Exception { super.init(); } @Override protected SpringCache createSpringCache() { return new SpringCache(embeddedCacheManager.getCache()); } @Override protected AbstractInfinispanSessionRepository createRepository(SpringCache springCache) { InfinispanEmbeddedSessionRepository sessionRepository = new InfinispanEmbeddedSessionRepository(springCache); sessionRepository.afterPropertiesSet(); return sessionRepository; } @Test(expectedExceptions = NullPointerException.class) @Override public void testThrowingExceptionOnNullSpringCache() throws Exception { super.testThrowingExceptionOnNullSpringCache(); } @Override public void testCreatingSession() throws Exception { super.testCreatingSession(); } @Override public void testSavingNewSession() throws Exception { super.testSavingNewSession(); } @Override public void testDeletingSession() throws Exception { super.testDeletingSession(); } @Override public void testEvictingSession() throws Exception { super.testEvictingSession(); } @Override public void testExtractingPrincipalWithWrongIndexName() throws Exception { super.testExtractingPrincipalWithWrongIndexName(); } @Override public void testExtractingPrincipal() throws Exception { super.testExtractingPrincipal(); } @Override public void testUpdatingTTLOnAccessingData() throws Exception { super.testUpdatingTTLOnAccessingData(); } }
4,191
34.82906
137
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/session/InfinispanEmbeddedSessionRepositoryTest.java
package org.infinispan.spring.embedded.session; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.spring.common.session.AbstractInfinispanSessionRepository; import org.infinispan.spring.common.session.InfinispanSessionRepositoryTCK; import org.infinispan.spring.embedded.provider.BasicConfiguration; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Factory; import org.testng.annotations.Test; @Test(testName = "spring.embedded.session.InfinispanEmbeddedSessionRepositoryTest", groups = "unit") @ContextConfiguration(classes = BasicConfiguration.class) @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class InfinispanEmbeddedSessionRepositoryTest extends InfinispanSessionRepositoryTCK { private EmbeddedCacheManager embeddedCacheManager; private EmbeddedCacheManager cacheManager2; private EmbeddedCacheManager cacheManager3; @Factory public Object[] factory() { return new Object[]{ new InfinispanEmbeddedSessionRepositoryTest().mediaType(MediaType.APPLICATION_SERIALIZED_OBJECT), }; } @BeforeClass public void beforeClass() { ConfigurationBuilder defaultCacheBuilder = new ConfigurationBuilder(); defaultCacheBuilder.clustering().cacheMode(CacheMode.DIST_SYNC).encoding().mediaType(mediaType.getTypeSubtype()); embeddedCacheManager = TestCacheManagerFactory.createClusteredCacheManager(defaultCacheBuilder); cacheManager2 = TestCacheManagerFactory.createClusteredCacheManager(defaultCacheBuilder); cacheManager3 = TestCacheManagerFactory.createClusteredCacheManager(defaultCacheBuilder); } @AfterMethod public void afterMethod() { embeddedCacheManager.getCache().clear(); } @AfterClass public void afterClass() { embeddedCacheManager.stop(); cacheManager2.stop(); cacheManager3.stop(); } @BeforeMethod public void beforeMethod() throws Exception { super.init(); } @Override protected SpringCache createSpringCache() { return new SpringCache(embeddedCacheManager.getCache()); } @Override protected AbstractInfinispanSessionRepository createRepository(SpringCache springCache) { InfinispanEmbeddedSessionRepository sessionRepository = new InfinispanEmbeddedSessionRepository(springCache); sessionRepository.afterPropertiesSet(); return sessionRepository; } @Test(expectedExceptions = NullPointerException.class) @Override public void testThrowingExceptionOnNullSpringCache() throws Exception { super.testThrowingExceptionOnNullSpringCache(); } @Override public void testCreatingSession() throws Exception { super.testCreatingSession(); } @Override public void testSavingNewSession() throws Exception { super.testSavingNewSession(); } @Override public void testDeletingSession() throws Exception { super.testDeletingSession(); } @Override public void testEvictingSession() throws Exception { super.testEvictingSession(); } @Override public void testExtractingPrincipalWithWrongIndexName() throws Exception { super.testExtractingPrincipalWithWrongIndexName(); } @Override public void testExtractingPrincipal() throws Exception { super.testExtractingPrincipal(); } @Override public void testUpdatingTTLOnAccessingData() throws Exception { super.testUpdatingTTLOnAccessingData(); } }
4,164
34.598291
137
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/support/InfinispanDefaultCacheFactoryBeanTest.java
package org.infinispan.spring.embedded.support; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.infinispan.spring.embedded.InfinispanDefaultCacheFactoryBean; import org.infinispan.spring.embedded.provider.BasicConfiguration; import org.infinispan.test.CacheManagerCallable; import org.infinispan.test.TestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.AssertJUnit; import org.testng.annotations.Test; import static org.testng.AssertJUnit.assertEquals; /** * <p> * Test {@link InfinispanDefaultCacheFactoryBean}. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * */ @Test(testName = "spring.embedded.support.InfinispanDefaultCacheFactoryBeanTest", groups = "unit") @ContextConfiguration(classes = BasicConfiguration.class) @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class InfinispanDefaultCacheFactoryBeanTest extends AbstractTestNGSpringContextTests { /** * Test method for * {@link org.infinispan.spring.embedded.InfinispanDefaultCacheFactoryBean#afterPropertiesSet()}. * * @throws Exception */ @Test(expectedExceptions = IllegalStateException.class) public final void afterPropertiesSetShouldThrowAnIllegalStateExceptionIfNoCacheContainerHasBeenSet() throws Exception { final InfinispanDefaultCacheFactoryBean<Object, Object> objectUnderTest = new InfinispanDefaultCacheFactoryBean<Object, Object>(); objectUnderTest.afterPropertiesSet(); } /** * Test method for * {@link org.infinispan.spring.embedded.InfinispanDefaultCacheFactoryBean#getObject()}. */ @Test public final void infinispanDefaultCacheFactoryBeanShouldProduceANonNullInfinispanCache() { final InfinispanDefaultCacheFactoryBean<Object, Object> objectUnderTest = new InfinispanDefaultCacheFactoryBean<Object, Object>(); TestingUtil.withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager(new ConfigurationBuilder())) { @Override public void call() { try { objectUnderTest.setInfinispanCacheContainer(cm); objectUnderTest.afterPropertiesSet(); final Cache<Object, Object> cache = objectUnderTest.getObject(); AssertJUnit.assertNotNull( "InfinispanDefaultCacheFactoryBean should have produced a proper Infinispan cache. " + "However, it produced a null Infinispan cache.", cache); objectUnderTest.destroy(); } catch (Exception e) { throw new RuntimeException(e); } } }); } /** * Test method for * {@link org.infinispan.spring.embedded.InfinispanDefaultCacheFactoryBean#getObjectType()}. */ @Test public final void getObjectTypeShouldReturnTheMostDerivedTypeOfTheProducedInfinispanCache() { final InfinispanDefaultCacheFactoryBean<Object, Object> objectUnderTest = new InfinispanDefaultCacheFactoryBean<Object, Object>(); TestingUtil.withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager(new ConfigurationBuilder())) { @Override public void call() { try { objectUnderTest.setInfinispanCacheContainer(cm); objectUnderTest.afterPropertiesSet(); assertEquals( "getObjectType() should have returned the produced Infinispan cache's most derived type. " + "However, it returned a more generic type.", objectUnderTest.getObject() .getClass(), objectUnderTest.getObjectType()); objectUnderTest.destroy(); } catch (Exception e) { throw new RuntimeException(e); } } }); } /** * Test method for * {@link org.infinispan.spring.embedded.InfinispanDefaultCacheFactoryBean#isSingleton()}. */ @Test public final void infinispanDefaultCacheFactoryBeanShouldDeclareItselfToBeSingleton() { final InfinispanDefaultCacheFactoryBean<Object, Object> objectUnderTest = new InfinispanDefaultCacheFactoryBean<Object, Object>(); AssertJUnit.assertTrue( "InfinispanDefaultCacheFactoryBean should declare itself to produce a singleton. However, it didn't.", objectUnderTest.isSingleton()); } /** * Test method for * {@link org.infinispan.spring.embedded.InfinispanDefaultCacheFactoryBean#destroy()}. */ @Test public final void infinispanDefaultCacheFactoryBeanShouldStopTheCreatedInfinispanCacheWhenItIsDestroyed() { final InfinispanDefaultCacheFactoryBean<Object, Object> objectUnderTest = new InfinispanDefaultCacheFactoryBean<Object, Object>(); TestingUtil.withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager(new ConfigurationBuilder())) { @Override public void call() { try { objectUnderTest.setInfinispanCacheContainer(cm); objectUnderTest.afterPropertiesSet(); final Cache<Object, Object> cache = objectUnderTest.getObject(); objectUnderTest.destroy(); AssertJUnit.assertEquals( "InfinispanDefaultCacheFactoryBean should have stopped the created Infinispan cache when being destroyed. " + "However, the created Infinispan is not yet terminated.", ComponentStatus.TERMINATED, cache.getStatus()); } catch (Exception e) { throw new RuntimeException(e); } } }); } }
6,174
42.794326
137
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/support/InfinispanNamedEmbeddedCacheFactoryBeanTest.java
package org.infinispan.spring.embedded.support; import org.infinispan.Cache; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.infinispan.spring.embedded.provider.BasicConfiguration; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.springframework.core.io.ClassPathResource; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.io.IOException; import java.io.InputStream; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; /** * <p> * Test {@link InfinispanNamedEmbeddedCacheFactoryBean}. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * */ @Test(testName = "spring.embedded.support.InfinispanNamedEmbeddedCacheFactoryBeanTest", groups = "unit") @ContextConfiguration(classes = BasicConfiguration.class) @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class InfinispanNamedEmbeddedCacheFactoryBeanTest extends AbstractTestNGSpringContextTests { private static final String CACHE_NAME_FROM_CONFIGURATION_FILE = "asyncCache"; private static final ClassPathResource NAMED_ASYNC_CACHE_CONFIG_LOCATION = new ClassPathResource( "named-async-cache.xml", InfinispanNamedEmbeddedCacheFactoryBeanTest.class); private EmbeddedCacheManager DEFAULT_CACHE_MANAGER; private EmbeddedCacheManager PRECONFIGURED_DEFAULT_CACHE_MANAGER; @BeforeClass public void startCacheManagers() { DEFAULT_CACHE_MANAGER = TestCacheManagerFactory.createCacheManager(); Configuration configuration = new ConfigurationBuilder().build(); DEFAULT_CACHE_MANAGER.defineConfiguration("test.cache.Name", configuration); DEFAULT_CACHE_MANAGER.defineConfiguration("test.bean.Name", configuration); DEFAULT_CACHE_MANAGER.start(); try (InputStream configStream = NAMED_ASYNC_CACHE_CONFIG_LOCATION.getInputStream()) { PRECONFIGURED_DEFAULT_CACHE_MANAGER = TestCacheManagerFactory.fromStream(configStream); } catch (final IOException e) { throw new ExceptionInInitializerError(e); } } @AfterClass public void stopCacheManagers() { PRECONFIGURED_DEFAULT_CACHE_MANAGER.stop(); DEFAULT_CACHE_MANAGER.stop(); } /** * Test method for * {@link InfinispanNamedEmbeddedCacheFactoryBean#afterPropertiesSet()} * . * * @throws Exception */ @Test(expectedExceptions = IllegalStateException.class) public final void infinispanNamedEmbeddedCacheFactoryBeanShouldRecognizeThatNoCacheContainerHasBeenSet() throws Exception { final InfinispanNamedEmbeddedCacheFactoryBean<Object, Object> objectUnderTest = new InfinispanNamedEmbeddedCacheFactoryBean<Object, Object>(); objectUnderTest.setCacheName("test.cache.Name"); objectUnderTest.setBeanName("test.bean.Name"); objectUnderTest.afterPropertiesSet(); } /** * Test method for * {@link InfinispanNamedEmbeddedCacheFactoryBean#setBeanName(String)} * . * * @throws Exception */ @Test public final void infinispanNamedEmbeddedCacheFactoryBeanShouldUseBeanNameAsCacheNameIfNoCacheNameHasBeenSet() throws Exception { final String beanName = "test.bean.Name"; final InfinispanNamedEmbeddedCacheFactoryBean<Object, Object> objectUnderTest = new InfinispanNamedEmbeddedCacheFactoryBean<Object, Object>(); objectUnderTest.setInfinispanEmbeddedCacheManager(DEFAULT_CACHE_MANAGER); objectUnderTest.setBeanName(beanName); objectUnderTest.afterPropertiesSet(); final Cache<Object, Object> cache = objectUnderTest.getObject(); assertEquals("InfinispanNamedEmbeddedCacheFactoryBean should have used its bean name [" + beanName + "] as the name of the created cache. However, it didn't.", beanName, cache.getName()); objectUnderTest.destroy(); } /** * Test method for * {@link InfinispanNamedEmbeddedCacheFactoryBean#setCacheName(String)} * . * * @throws Exception */ @Test public final void infinispanNamedEmbeddedCacheFactoryBeanShouldPreferExplicitCacheNameToBeanName() throws Exception { final String cacheName = "test.cache.Name"; final String beanName = "test.bean.Name"; final InfinispanNamedEmbeddedCacheFactoryBean<Object, Object> objectUnderTest = new InfinispanNamedEmbeddedCacheFactoryBean<Object, Object>(); objectUnderTest.setInfinispanEmbeddedCacheManager(DEFAULT_CACHE_MANAGER); objectUnderTest.setCacheName(cacheName); objectUnderTest.setBeanName(beanName); objectUnderTest.afterPropertiesSet(); final Cache<Object, Object> cache = objectUnderTest.getObject(); assertEquals("InfinispanNamedEmbeddedCacheFactoryBean should have preferred its cache name [" + cacheName + "] as the name of the created cache. However, it didn't.", cacheName, cache.getName()); objectUnderTest.destroy(); } /** * Test method for * {@link InfinispanNamedEmbeddedCacheFactoryBean#getObjectType()} * . * * @throws Exception */ @Test public final void infinispanNamedEmbeddedCacheFactoryBeanShouldReportTheMostDerivedObjectType() throws Exception { final InfinispanNamedEmbeddedCacheFactoryBean<Object, Object> objectUnderTest = new InfinispanNamedEmbeddedCacheFactoryBean<Object, Object>(); objectUnderTest.setInfinispanEmbeddedCacheManager(DEFAULT_CACHE_MANAGER); objectUnderTest.setBeanName("test.bean.Name"); objectUnderTest.afterPropertiesSet(); assertEquals( "getObjectType() should have returned the most derived class of the actual Cache " + "implementation returned from getObject(). However, it didn't.", objectUnderTest.getObject().getClass(), objectUnderTest.getObjectType()); objectUnderTest.destroy(); } /** * Test method for * {@link InfinispanNamedEmbeddedCacheFactoryBean#getObject()} * . * * @throws Exception */ @Test public final void infinispanNamedEmbeddedCacheFactoryBeanShouldProduceANonNullInfinispanCache() throws Exception { final String cacheName = "test.cache.Name"; final String beanName = "test.bean.Name"; final InfinispanNamedEmbeddedCacheFactoryBean<Object, Object> objectUnderTest = new InfinispanNamedEmbeddedCacheFactoryBean<Object, Object>(); objectUnderTest.setInfinispanEmbeddedCacheManager(DEFAULT_CACHE_MANAGER); objectUnderTest.setCacheName(cacheName); objectUnderTest.setBeanName(beanName); objectUnderTest.afterPropertiesSet(); final Cache<Object, Object> cache = objectUnderTest.getObject(); assertNotNull( "InfinispanNamedEmbeddedCacheFactoryBean should have produced a proper Infinispan cache. " + "However, it produced a null Infinispan cache.", cache); objectUnderTest.destroy(); } /** * Test method for * {@link InfinispanNamedEmbeddedCacheFactoryBean#isSingleton()} * . */ @Test public final void infinispanNamedEmbeddedCacheFactoryBeanShouldDeclareItselfToBeSingleton() { final InfinispanNamedEmbeddedCacheFactoryBean<Object, Object> objectUnderTest = new InfinispanNamedEmbeddedCacheFactoryBean<Object, Object>(); assertTrue( "InfinispanNamedEmbeddedCacheFactoryBean should declare itself to produce a singleton. However, it didn't.", objectUnderTest.isSingleton()); } /** * Test method for * {@link InfinispanNamedEmbeddedCacheFactoryBean#destroy()} * . * * @throws Exception */ @Test public final void infinispanNamedEmbeddedCacheFactoryBeanShouldStopTheCreatedInfinispanCacheWhenItIsDestroyed() throws Exception { final String cacheName = "test.cache.Name"; final String beanName = "test.bean.Name"; final InfinispanNamedEmbeddedCacheFactoryBean<Object, Object> objectUnderTest = new InfinispanNamedEmbeddedCacheFactoryBean<Object, Object>(); objectUnderTest.setInfinispanEmbeddedCacheManager(DEFAULT_CACHE_MANAGER); objectUnderTest.setCacheName(cacheName); objectUnderTest.setBeanName(beanName); objectUnderTest.afterPropertiesSet(); final Cache<Object, Object> cache = objectUnderTest.getObject(); objectUnderTest.destroy(); assertEquals( "InfinispanNamedEmbeddedCacheFactoryBean should have stopped the created Infinispan cache when being destroyed. " + "However, the created Infinispan is not yet terminated.", ComponentStatus.TERMINATED, cache.getStatus()); } /** * Test method for * {@link InfinispanNamedEmbeddedCacheFactoryBean#afterPropertiesSet()} * . * * @throws Exception */ @Test(expectedExceptions = IllegalStateException.class) public final void infinispanNamedEmbeddedCacheFactoryBeanShouldRejectConfigurationTemplateModeNONEIfCacheConfigurationAlreadyExistsInConfigurationFile() throws Exception { final InfinispanNamedEmbeddedCacheFactoryBean<Object, Object> objectUnderTest = new InfinispanNamedEmbeddedCacheFactoryBean<Object, Object>(); objectUnderTest.setInfinispanEmbeddedCacheManager(PRECONFIGURED_DEFAULT_CACHE_MANAGER); objectUnderTest.setCacheName(CACHE_NAME_FROM_CONFIGURATION_FILE); objectUnderTest.setBeanName(CACHE_NAME_FROM_CONFIGURATION_FILE); objectUnderTest.setConfigurationTemplateMode("NONE"); objectUnderTest.afterPropertiesSet(); } /** * Test method for * {@link InfinispanNamedEmbeddedCacheFactoryBean#afterPropertiesSet()} * . * * @throws Exception */ @Test(expectedExceptions = IllegalStateException.class) public final void infinispanNamedEmbeddedCacheFactoryBeanShouldRejectConfigurationTemplateModeDEFAULTIfCacheConfigurationAlreadyExistsInConfigurationFile() throws Exception { final InfinispanNamedEmbeddedCacheFactoryBean<Object, Object> objectUnderTest = new InfinispanNamedEmbeddedCacheFactoryBean<Object, Object>(); objectUnderTest.setInfinispanEmbeddedCacheManager(PRECONFIGURED_DEFAULT_CACHE_MANAGER); objectUnderTest.setCacheName(CACHE_NAME_FROM_CONFIGURATION_FILE); objectUnderTest.setBeanName(CACHE_NAME_FROM_CONFIGURATION_FILE); objectUnderTest.setConfigurationTemplateMode("DEFAULT"); objectUnderTest.afterPropertiesSet(); } /** * Negative test case for {@link InfinispanNamedEmbeddedCacheFactoryBean#addCustomConfiguration(ConfigurationBuilder)} * * @throws Exception */ @Test(expectedExceptions = IllegalStateException.class) public final void infinispanNamedEmbeddedCacheFactoryShouldRejectConfigurationTemplateModeCUSTOM() throws Exception { final InfinispanNamedEmbeddedCacheFactoryBean<Object, Object> objectUnderTest = new InfinispanNamedEmbeddedCacheFactoryBean<Object, Object>(); objectUnderTest.setInfinispanEmbeddedCacheManager(DEFAULT_CACHE_MANAGER); objectUnderTest.setCacheName(CACHE_NAME_FROM_CONFIGURATION_FILE); objectUnderTest.setConfigurationTemplateMode("CUSTOM"); objectUnderTest.afterPropertiesSet(); } @Test public final void infinispanNamedEmbeddedCacheFactoryShouldAcceptConfigurationTemplateModeCUSTOM() throws Exception { final InfinispanNamedEmbeddedCacheFactoryBean<Object, Object> objectUnderTest = new InfinispanNamedEmbeddedCacheFactoryBean<Object, Object>(); objectUnderTest.setInfinispanEmbeddedCacheManager(DEFAULT_CACHE_MANAGER); objectUnderTest.setCacheName(CACHE_NAME_FROM_CONFIGURATION_FILE); objectUnderTest.setConfigurationTemplateMode("CUSTOM"); ConfigurationBuilder custom = TestCacheManagerFactory.getDefaultCacheConfiguration(false); objectUnderTest.addCustomConfiguration(custom); objectUnderTest.afterPropertiesSet(); } }
12,820
42.757679
158
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/support/InfinispanEmbeddedCacheManagerFactoryBeanTest.java
package org.infinispan.spring.embedded.support; import org.infinispan.Cache; import org.infinispan.configuration.cache.CacheMode; import org.infinispan.configuration.cache.Configuration; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.infinispan.spring.embedded.provider.BasicConfiguration; import org.infinispan.spring.embedded.provider.SpringEmbeddedCacheManagerFactoryBean; import org.infinispan.test.CacheManagerCallable; import org.infinispan.transaction.TransactionMode; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.annotations.Test; import static org.infinispan.test.TestingUtil.withCacheManager; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; /** * <p> * Test {@link SpringEmbeddedCacheManagerFactoryBean}. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * */ @Test(testName = "spring.embedded.support.InfinispanEmbeddedCacheManagerFactoryBeanTest", groups = "unit") @ContextConfiguration(classes = BasicConfiguration.class) @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class InfinispanEmbeddedCacheManagerFactoryBeanTest extends AbstractTestNGSpringContextTests { private static final String CACHE_NAME_FROM_CONFIGURATION_FILE = "asyncCache"; private static final String NAMED_ASYNC_CACHE_CONFIG_LOCATION = "named-async-cache.xml"; /** * Test method for * {@link InfinispanEmbeddedCacheManagerFactoryBean#setConfigurationFileLocation(Resource)} * . * * @throws Exception */ @Test public final void infinispanEmbeddedCacheManagerFactoryBeanShouldCreateACacheManagerEvenIfNoDefaultConfigurationLocationHasBeenSet() throws Exception { final InfinispanEmbeddedCacheManagerFactoryBean objectUnderTest = new InfinispanEmbeddedCacheManagerFactoryBean(); objectUnderTest.afterPropertiesSet(); withCacheManager(new CacheManagerCallable(objectUnderTest.getObject()) { @Override public void call() { assertNotNull( "getObject() should have returned a valid EmbeddedCacheManager, even if no defaulConfigurationLocation " + "has been specified. However, it returned null.", cm); } }); } /** * Test method for * {@link InfinispanEmbeddedCacheManagerFactoryBean#setConfigurationFileLocation(Resource)} * . * * @throws Exception */ @Test public final void infinispanEmbeddedCacheManagerFactoryBeanShouldCreateACustomizedCacheManagerIfGivenADefaultConfigurationLocation() throws Exception { final Resource infinispanConfig = new ClassPathResource(NAMED_ASYNC_CACHE_CONFIG_LOCATION, getClass()); final InfinispanEmbeddedCacheManagerFactoryBean objectUnderTest = new InfinispanEmbeddedCacheManagerFactoryBean(); objectUnderTest.setConfigurationFileLocation(infinispanConfig); objectUnderTest.afterPropertiesSet(); withCacheManager(new CacheManagerCallable(objectUnderTest.getObject()) { @Override public void call() { assertNotNull( "getObject() should have returned a valid EmbeddedCacheManager, configured using the configuration file " + "set on SpringEmbeddedCacheManagerFactoryBean. However, it returned null.", cm); final Cache<Object, Object> cacheDefinedInCustomConfiguration = cm.getCache(CACHE_NAME_FROM_CONFIGURATION_FILE); final Configuration configuration = cacheDefinedInCustomConfiguration.getCacheConfiguration(); assertEquals( "The cache named [" + CACHE_NAME_FROM_CONFIGURATION_FILE + "] is configured to have asynchonous replication cache mode. Yet, the cache returned from getCache(" + CACHE_NAME_FROM_CONFIGURATION_FILE + ") has a different cache mode. Obviously, SpringEmbeddedCacheManagerFactoryBean did not use " + "the configuration file when instantiating EmbeddedCacheManager.", CacheMode.REPL_ASYNC, configuration.clustering().cacheMode()); } }); } /** * Test method for * {@link InfinispanEmbeddedCacheManagerFactoryBean#getObjectType()} * . * * @throws Exception */ @Test public final void infinispanEmbeddedCacheManagerFactoryBeanShouldReportTheCorrectObjectType() throws Exception { final InfinispanEmbeddedCacheManagerFactoryBean objectUnderTest = new InfinispanEmbeddedCacheManagerFactoryBean(); objectUnderTest.afterPropertiesSet(); withCacheManager(new CacheManagerCallable(objectUnderTest.getObject()) { @Override public void call() { assertEquals( "getObjectType() should return the most derived class of the actual EmbeddedCacheManager " + "implementation returned from getObject(). However, it didn't.", cm.getClass(), objectUnderTest.getObjectType()); } }); } /** * Test method for * {@link InfinispanEmbeddedCacheManagerFactoryBean#isSingleton()} * . */ @Test public final void infinispanEmbeddedCacheManagerFactoryBeanShouldDeclareItselfToOnlyProduceSingletons() { final InfinispanEmbeddedCacheManagerFactoryBean objectUnderTest = new InfinispanEmbeddedCacheManagerFactoryBean(); assertTrue("isSingleton() should always return true. However, it returned false", objectUnderTest.isSingleton()); } /** * Test method for * {@link InfinispanEmbeddedCacheManagerFactoryBean#destroy()} * . * * @throws Exception */ @Test public final void infinispanEmbeddedCacheManagerFactoryBeanShouldStopTheCreateEmbeddedCacheManagerWhenBeingDestroyed() throws Exception { final InfinispanEmbeddedCacheManagerFactoryBean objectUnderTest = new InfinispanEmbeddedCacheManagerFactoryBean(); objectUnderTest.afterPropertiesSet(); final EmbeddedCacheManager embeddedCacheManager = objectUnderTest.getObject(); embeddedCacheManager.defineConfiguration("cache", new ConfigurationBuilder().build()); embeddedCacheManager.getCache("cache"); // Implicitly starts EmbeddedCacheManager objectUnderTest.destroy(); withCacheManager(new CacheManagerCallable(objectUnderTest.getObject()) { @Override public void call() { assertEquals( "SpringEmbeddedCacheManagerFactoryBean should stop the created EmbeddedCacheManager when being destroyed. " + "However, the created EmbeddedCacheManager is still not terminated.", ComponentStatus.TERMINATED, embeddedCacheManager.getStatus()); } }); } // Testing the addBuilder() methods @Test public final void testAddConfigurations() throws Exception { final InfinispanEmbeddedCacheManagerFactoryBean objectUnderTest = new InfinispanEmbeddedCacheManagerFactoryBean(); try { GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder(); gcb.defaultCacheName("default"); // Now prepare a cache configuration. ConfigurationBuilder builder = new ConfigurationBuilder(); builder.transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL); // Now add them to the object that we are testing. objectUnderTest.addCustomGlobalConfiguration(gcb); objectUnderTest.addCustomCacheConfiguration(builder); objectUnderTest.afterPropertiesSet(); // Get the cache manager and make assertions. final EmbeddedCacheManager infinispanEmbeddedCacheManager = objectUnderTest.getObject(); assertEquals(infinispanEmbeddedCacheManager.getCacheManagerConfiguration().defaultCacheName(), gcb.build().defaultCacheName()); assertEquals(infinispanEmbeddedCacheManager.getDefaultCacheConfiguration().transaction() .transactionMode().isTransactional(), builder.build().transaction().transactionMode().isTransactional()); } finally { objectUnderTest.destroy(); } } }
9,056
44.285
137
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/support/InfinispanDefaultCacheFactoryBeanContextTest.java
package org.infinispan.spring.embedded.support; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertSame; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.annotations.Test; /** * <p> * Test {@link org.infinispan.spring.embedded.InfinispanDefaultCacheFactoryBean} deployed in a Spring application context. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * */ @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @ContextConfiguration("classpath:/org/infinispan/spring/embedded/support/InfinispanDefaultCacheFactoryBeanContextTest.xml") @Test(testName = "spring.embedded.support.InfinispanDefaultCacheFactoryBeanContextTest", groups = "unit") @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class InfinispanDefaultCacheFactoryBeanContextTest extends AbstractTestNGSpringContextTests { private static final String DEFAULT_CACHE_NAME = "testDefaultCache"; @Test public final void shouldProduceANonNullCache() { final Cache<Object, Object> testDefaultCache = this.applicationContext.getBean( DEFAULT_CACHE_NAME, Cache.class); assertNotNull( "Spring application context should contain an Infinispan cache under the bean name \"" + DEFAULT_CACHE_NAME + "\". However, it doesn't.", testDefaultCache); } @Test public final void shouldAlwaysReturnTheSameCache() { final Cache<Object, Object> testDefaultCache1 = this.applicationContext.getBean( DEFAULT_CACHE_NAME, Cache.class); final Cache<Object, Object> testDefaultCache2 = this.applicationContext.getBean( DEFAULT_CACHE_NAME, Cache.class); assertSame( "InfinispanDefaultCacheFactoryBean should always return the same cache instance when being " + "called repeatedly. However, the cache instances are not the same.", testDefaultCache1, testDefaultCache2); } /** * Referenced in the Spring configuration. */ public static EmbeddedCacheManager createCacheManager() { return TestCacheManagerFactory.createCacheManager(new ConfigurationBuilder()); } }
2,837
43.34375
137
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/provider/SpringEmbeddedCacheManagerFactoryBeanTest.java
package org.infinispan.spring.embedded.provider; import org.infinispan.Cache; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.spring.embedded.builders.SpringEmbeddedCacheManagerFactoryBeanBuilder; import org.infinispan.transaction.TransactionMode; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; import java.util.Optional; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertTrue; /** * <p> * Test {@link SpringEmbeddedCacheManagerFactoryBean}. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @author Marius Bogoevici * */ @Test(testName = "spring.embedded.provider.SpringEmbeddedCacheManagerFactoryBeanTest", groups = "unit") @ContextConfiguration(classes = BasicConfiguration.class) @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class SpringEmbeddedCacheManagerFactoryBeanTest extends AbstractTestNGSpringContextTests { private static final String CACHE_NAME_FROM_CONFIGURATION_FILE = "asyncCache"; private static final String NAMED_ASYNC_CACHE_CONFIG_LOCATION = "named-async-cache.xml"; private SpringEmbeddedCacheManagerFactoryBean objectUnderTest; @AfterMethod(alwaysRun = true) public void closeCacheManager() throws Exception { if(objectUnderTest != null) { objectUnderTest.destroy(); } } @Test public void testIfSpringEmbeddedCacheManagerFactoryBeanCreatesACacheManagerEvenIfNoDefaultConfigurationLocationHasBeenSet() throws Exception { objectUnderTest = SpringEmbeddedCacheManagerFactoryBeanBuilder .defaultBuilder().build(); final SpringEmbeddedCacheManager springEmbeddedCacheManager = objectUnderTest.getObject(); assertNotNull( "getObject() should have returned a valid SpringEmbeddedCacheManager, even if no defaulConfigurationLocation " + "has been specified. However, it returned null.", springEmbeddedCacheManager); } @Test public void testIfSpringEmbeddedCacheManagerFactoryBeanCreatesACustomizedCacheManagerIfGivenADefaultConfigurationLocation() throws Exception { objectUnderTest = SpringEmbeddedCacheManagerFactoryBeanBuilder .defaultBuilder().fromFile(NAMED_ASYNC_CACHE_CONFIG_LOCATION, getClass()).build(); final SpringEmbeddedCacheManager springEmbeddedCacheManager = objectUnderTest.getObject(); assertNotNull( "getObject() should have returned a valid SpringEmbeddedCacheManager, configured using the configuration file " + "set on SpringEmbeddedCacheManagerFactoryBean. However, it returned null.", springEmbeddedCacheManager); final SpringCache cacheDefinedInCustomConfiguration = springEmbeddedCacheManager .getCache(CACHE_NAME_FROM_CONFIGURATION_FILE); final org.infinispan.configuration.cache.Configuration configuration = ((Cache) cacheDefinedInCustomConfiguration.getNativeCache()) .getCacheConfiguration(); assertEquals( "The cache named [" + CACHE_NAME_FROM_CONFIGURATION_FILE + "] is configured to have asynchonous replication cache mode. Yet, the cache returned from getCache(" + CACHE_NAME_FROM_CONFIGURATION_FILE + ") has a different cache mode. Obviously, SpringEmbeddedCacheManagerFactoryBean did not use " + "the configuration file when instantiating SpringEmbeddedCacheManager.", org.infinispan.configuration.cache.CacheMode.REPL_ASYNC, configuration.clustering().cacheMode()); } @Test public void testIfSpringEmbeddedCacheManagerFactoryBeanReportsTheCorrectObjectType() throws Exception { objectUnderTest = SpringEmbeddedCacheManagerFactoryBeanBuilder .defaultBuilder().build(); final SpringEmbeddedCacheManager springEmbeddedCacheManager = objectUnderTest.getObject(); assertEquals( "getObjectType() should return the most derived class of the actual SpringEmbeddedCacheManager " + "implementation returned from getObject(). However, it didn't.", springEmbeddedCacheManager.getClass(), objectUnderTest.getObjectType()); } @Test public void testIfSpringEmbeddedCacheManagerFactoryBeanDeclaresItselfToOnlyProduceSingletons() { objectUnderTest = new SpringEmbeddedCacheManagerFactoryBean(); assertTrue("isSingleton() should always return true. However, it returned false", objectUnderTest.isSingleton()); } @Test public void testIfSpringEmbeddedCacheManagerFactoryBeanStopsTheCreatedEmbeddedCacheManagerWhenBeingDestroyed() throws Exception { GlobalConfigurationBuilder builder = new GlobalConfigurationBuilder(); builder.defaultCacheName("default"); objectUnderTest = SpringEmbeddedCacheManagerFactoryBeanBuilder .defaultBuilder().withGlobalConfiguration(builder).withConfigurationBuilder(new ConfigurationBuilder()).build(); final SpringEmbeddedCacheManager springEmbeddedCacheManager = objectUnderTest.getObject(); springEmbeddedCacheManager.getCache("default"); // Implicitly starts // SpringEmbeddedCacheManager objectUnderTest.destroy(); assertEquals( "SpringEmbeddedCacheManagerFactoryBean should stop the created SpringEmbeddedCacheManager when being destroyed. " + "However, the created SpringEmbeddedCacheManager is still not terminated.", ComponentStatus.TERMINATED, springEmbeddedCacheManager.getNativeCacheManager() .getStatus()); } @Test public void testIfSpringEmbeddedCacheManagerFactoryBeanAllowesOverridingGlobalConfiguration() throws Exception { GlobalConfigurationBuilder overriddenConfiguration = new GlobalConfigurationBuilder(); overriddenConfiguration.transport().rackId("r2"); objectUnderTest = SpringEmbeddedCacheManagerFactoryBeanBuilder .defaultBuilder().fromFile(NAMED_ASYNC_CACHE_CONFIG_LOCATION, getClass()) .withGlobalConfiguration(overriddenConfiguration).build(); final SpringEmbeddedCacheManager springEmbeddedCacheManager = objectUnderTest.getObject(); assertEquals( "Transport for cache configured in" + CACHE_NAME_FROM_CONFIGURATION_FILE + "is assigned to r1 rack. But later Global Configuration overrides " + "this setting to r2. Obviously created SpringEmbeddedCacheManagerFactoryBean does not support this kind " + "of overriding.", "r2", springEmbeddedCacheManager.getNativeCacheManager().getCacheManagerConfiguration().transport().rackId()); } @Test public void testIfSpringEmbeddedCacheManagerFactoryBeanAllowesOverridingConfigurationBuilder() throws Exception { ConfigurationBuilder overriddenBuilder = new ConfigurationBuilder(); overriddenBuilder.locking().concurrencyLevel(100); objectUnderTest = SpringEmbeddedCacheManagerFactoryBeanBuilder .defaultBuilder().fromFile(NAMED_ASYNC_CACHE_CONFIG_LOCATION, getClass()) .withConfigurationBuilder(overriddenBuilder).build(); final SpringEmbeddedCacheManager springEmbeddedCacheManager = objectUnderTest.getObject(); assertEquals( "Concurrency value of LockingLocking for cache configured in" + CACHE_NAME_FROM_CONFIGURATION_FILE + "is equal to 5000. But later Configuration Builder overrides " + "this setting to 100. Obviously created SpringEmbeddedCacheManagerFactoryBean does not support " + "this kind of overriding.", 100, springEmbeddedCacheManager.getNativeCacheManager().getDefaultCacheConfiguration().locking() .concurrencyLevel()); } @Test public void testIfSpringEmbeddedCacheManagerFactoryBeanAllowesOverridingConfigurationWithEmptyInputStream() throws Exception { objectUnderTest = new SpringEmbeddedCacheManagerFactoryBean(); GlobalConfigurationBuilder gcb = new GlobalConfigurationBuilder(); gcb.defaultCacheName("default"); // Now prepare a cache configuration. ConfigurationBuilder builder = new ConfigurationBuilder(); builder.transaction().transactionMode(TransactionMode.NON_TRANSACTIONAL); // Now add them to the object that we are testing. objectUnderTest.addCustomGlobalConfiguration(gcb); objectUnderTest.addCustomCacheConfiguration(builder); objectUnderTest.afterPropertiesSet(); // Get the cache manager and make assertions. final EmbeddedCacheManager infinispanEmbeddedCacheManager = objectUnderTest.getObject().getNativeCacheManager(); assertEquals(Optional.of("default"), infinispanEmbeddedCacheManager.getCacheManagerConfiguration().defaultCacheName()); assertEquals(TransactionMode.NON_TRANSACTIONAL, infinispanEmbeddedCacheManager.getDefaultCacheConfiguration().transaction().transactionMode()); } }
9,813
48.565657
137
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/provider/SpringCacheTest.java
package org.infinispan.spring.embedded.provider; import org.infinispan.commons.dataconversion.MediaType; import org.infinispan.commons.util.NullValue; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.spring.embedded.support.InfinispanNamedEmbeddedCacheFactoryBean; import org.infinispan.test.SingleCacheManagerTest; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.springframework.cache.Cache; import org.testng.annotations.BeforeMethod; import org.testng.annotations.DataProvider; import org.testng.annotations.Factory; import org.testng.annotations.Test; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertSame; import static org.testng.AssertJUnit.assertTrue; /** * <p> * An integration test for {@link SpringCache}. * </p> * <p> * <strong>CREDITS</strong> This test is a shameless copy of Costin Leau's * <code>org.springframework.cache.vendor.AbstractNativeCacheTest</code>. The additions made to it * are minor. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @author Marius Bogoevici * */ @Test(testName = "spring.embedded.provider.SpringCacheTest", groups = "unit") public class SpringCacheTest extends SingleCacheManagerTest { protected final static String CACHE_NAME = "testCache"; private final InfinispanNamedEmbeddedCacheFactoryBean<Object, Object> fb = new InfinispanNamedEmbeddedCacheFactoryBean<Object, Object>(); private final String mediaType; private org.infinispan.Cache<Object, Object> nativeCache; private Cache cache; @Factory(dataProvider = "encodings") public SpringCacheTest(String mediaType) { this.mediaType = mediaType; } @DataProvider public static Object[][] encodings() { return new Object[][] { {MediaType.APPLICATION_OBJECT_TYPE}, {MediaType.APPLICATION_SERIALIZED_OBJECT_TYPE}, {MediaType.APPLICATION_PROTOSTREAM_TYPE}, }; } @Override protected String parameters() { return "[" + mediaType + "]"; } @Override protected EmbeddedCacheManager createCacheManager() throws Exception { ConfigurationBuilder defaultCacheBuilder = new ConfigurationBuilder(); defaultCacheBuilder.encoding().mediaType(mediaType); return TestCacheManagerFactory.createCacheManager( new GlobalConfigurationBuilder().defaultCacheName(CACHE_NAME), defaultCacheBuilder ); } @BeforeMethod public void setUp() throws Exception { this.nativeCache = createNativeCache(); this.cache = createCache(this.nativeCache); } @Test public void testCacheName() throws Exception { assertEquals(CACHE_NAME, this.cache.getName()); } @Test public void testNativeCache() throws Exception { assertSame(this.nativeCache, this.cache.getNativeCache()); } @Test public void testCachePut() throws Exception { final Object key = "enescu"; final Object value = "george"; assertNull(this.cache.get(key)); this.cache.put(key, value); assertEquals(value, this.cache.get(key).get()); } @Test public void testCachePutSupportsNullValue() throws Exception { final Object key = "enescu"; final Object value = null; assertNull(this.cache.get(key)); this.cache.put(key, value); assertNull(this.cache.get(key).get()); } @Test public void testCacheContains() throws Exception { final Object key = "enescu"; final Object value = "george"; this.cache.put(key, value); assertTrue(this.cache.get(key) != null); } @Test public void testCacheContainsSupportsNullValue() throws Exception { final Object key = "enescu"; final Object value = null; this.cache.put(key, value); assertTrue(this.cache.get(key) != null); } @Test(expectedExceptions = NullPointerException.class) public void testThrowingNullPointerExceptionOnNullGet() throws Exception { //when cache.get(null); } @Test(expectedExceptions = NullPointerException.class) public void testThrowingNullPointerExceptionOnNullGetWithClass() throws Exception { //when cache.get(null, (Class<?>) null); } @Test public void testBypassingClassCheckWhenNullIsSpecified() throws Exception { //given this.cache.put("test", "test"); //when Object value = cache.get("test", (Class<?>) null); //then assertTrue(value instanceof String); } @Test public void testReturningProperValueFromCacheWithCast() throws Exception { //given this.cache.put("test", "test"); //when String value = cache.get("test", String.class); //then assertEquals("test", value); } @Test(expectedExceptions = IllegalStateException.class) public void testThrowingIllegalStateExceptionWhenClassCastReturnDifferentClass() throws Exception { //given this.cache.put("test", 1); //when cache.get("test", String.class); } @Test public void testReturningNullValueIfThereIsNoValue() throws Exception { //when Cache.ValueWrapper existingValue = this.cache.putIfAbsent("test", "test"); //then assertNull(existingValue); } @Test public void testReturningPreviousValue() throws Exception { //given this.cache.put("test", "test"); //when Cache.ValueWrapper existingValue = this.cache.putIfAbsent("test", "test1"); //then assertEquals("test", existingValue.get()); } @Test public void testReturningNullValueConstant() throws Exception { //given this.cache.put("test", NullValue.NULL); //when Cache.ValueWrapper existingValue = this.cache.putIfAbsent("test", "test1"); //then assertNotNull(existingValue); assertNull(existingValue.get()); } @Test public void testCacheClear() throws Exception { assertNull(this.cache.get("enescu")); this.cache.put("enescu", "george"); assertNull(this.cache.get("vlaicu")); this.cache.put("vlaicu", "aurel"); this.cache.clear(); assertNull(this.cache.get("vlaicu")); assertNull(this.cache.get("enescu")); } @Test public void testValueLoaderWithNoPreviousValue() { //given cache.get("test", () -> "test"); //when Cache.ValueWrapper valueFromCache = cache.get("test"); //then assertEquals("test", valueFromCache.get()); } /* * In this test Thread 1 should exclusively block Cache#get method so that Thread 2 won't be able to * insert "thread2" string into the cache. * * The test check this part of the Spring spec: * Return the value to which this cache maps the specified key, obtaining that value from valueLoader if necessary. * This method provides a simple substitute for the conventional "if cached, return; otherwise create, cache and return" pattern. * @see http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/cache/Cache.html#get-java.lang.Object-java.util.concurrent.Callable- */ @Test public void testValueLoaderWithLocking() throws Exception { //given CountDownLatch waitUntilThread1LocksValueGetter = new CountDownLatch(1); //when Future<String> thread1 = fork(() -> cache.get("test", () -> { waitUntilThread1LocksValueGetter.countDown(); return "thread1"; })); Future<String> thread2 = fork(() -> { waitUntilThread1LocksValueGetter.await(30, TimeUnit.SECONDS); return cache.get("test", () -> "thread2"); }); String valueObtainedByThread1 = thread1.get(); String valueObtainedByThread2 = thread2.get(); Cache.ValueWrapper valueAfterGetterIsDone = cache.get("test"); //then assertNotNull(valueAfterGetterIsDone); assertEquals("thread1", valueAfterGetterIsDone.get()); assertEquals("thread1", valueObtainedByThread1); assertEquals("thread1", valueObtainedByThread2); } @Test public void testValueLoaderWithPreviousValue() { //given cache.put("test", "test"); cache.get("test", () -> "This should not be updated"); //when Cache.ValueWrapper valueFromCache = cache.get("test"); //then assertEquals("test", valueFromCache.get()); } @Test(expectedExceptions = Cache.ValueRetrievalException.class) public void testValueLoaderWithExceptionWhenLoading() { //when//then cache.get("test", () -> {throw new IllegalStateException();}); } @Test public void testPutNullAndGetWithClass() { //when//then cache.put("key", null); assertNull(cache.get("key", String.class)); } @Test public void testGetWithNullValue() { assertNull(cache.get("null", () -> null)); } @Test public void testGetNullValueAfterPutNull() { cache.put("key", null); String result = cache.get("key", () -> "notnull"); assertNull(result); } private org.infinispan.Cache<Object, Object> createNativeCache() throws Exception { this.fb.setInfinispanEmbeddedCacheManager(cacheManager); this.fb.setBeanName(CACHE_NAME); this.fb.setCacheName(CACHE_NAME); this.fb.afterPropertiesSet(); return this.fb.getObject(); } private Cache createCache(final org.infinispan.Cache<Object, Object> nativeCache) { return new SpringCache(nativeCache); } }
9,927
28.813814
153
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/provider/BasicConfiguration.java
package org.infinispan.spring.embedded.provider; import org.springframework.context.annotation.Configuration; @Configuration public class BasicConfiguration { }
163
19.5
60
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/provider/SpringEmbeddedCacheManagerTest.java
package org.infinispan.spring.embedded.provider; import org.infinispan.commons.IllegalLifecycleStateException; import org.infinispan.commons.test.Exceptions; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.lifecycle.ComponentStatus; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.test.CacheManagerCallable; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.springframework.cache.Cache; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.testng.AbstractTestNGSpringContextTests; import org.testng.annotations.Test; import java.io.IOException; import java.util.Collection; import static org.infinispan.test.TestingUtil.withCacheManager; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNotSame; import static org.testng.AssertJUnit.assertSame; import static org.testng.AssertJUnit.assertTrue; /** * <p> * Test {@link SpringEmbeddedCacheManager}. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @author Marius Bogoevici * */ @Test(testName = "spring.embedded.provider.SpringEmbeddedCacheManagerTest", groups = "unit") @ContextConfiguration(classes = BasicConfiguration.class) @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class SpringEmbeddedCacheManagerTest extends AbstractTestNGSpringContextTests { private static final String CACHE_NAME_FROM_CONFIGURATION_FILE = "asyncCache"; private static final String NAMED_ASYNC_CACHE_CONFIG_LOCATION = "named-async-cache.xml"; /** * Test method for * {@link SpringEmbeddedCacheManager#SpringEmbeddedCacheManager(EmbeddedCacheManager)} * . */ @Test(expectedExceptions = IllegalArgumentException.class) public final void springEmbeddedCacheManagerConstructorShouldRejectNullEmbeddedCacheManager() { new SpringEmbeddedCacheManager(null); } /** * Test method for * {@link SpringEmbeddedCacheManager#getCache(String)}. * * @throws IOException */ @Test public final void getCacheShouldReturnTheCacheHavingTheProvidedName() throws IOException { final EmbeddedCacheManager nativeCacheManager = TestCacheManagerFactory.fromStream( SpringEmbeddedCacheManagerTest.class .getResourceAsStream(NAMED_ASYNC_CACHE_CONFIG_LOCATION)); final SpringEmbeddedCacheManager objectUnderTest = new SpringEmbeddedCacheManager( nativeCacheManager); final Cache cacheExpectedToHaveTheProvidedName = objectUnderTest .getCache(CACHE_NAME_FROM_CONFIGURATION_FILE); assertEquals( "getCache(" + CACHE_NAME_FROM_CONFIGURATION_FILE + ") should have returned the cache having the provided name. However, the cache returned has a different name.", CACHE_NAME_FROM_CONFIGURATION_FILE, cacheExpectedToHaveTheProvidedName.getName()); nativeCacheManager.stop(); } /** * Test method for * {@link SpringEmbeddedCacheManager#getCache(String)}. * * @throws IOException */ @Test public final void getCacheShouldReturnACacheAddedAfterCreatingTheSpringEmbeddedCache() throws IOException { final String nameOfInfinispanCacheAddedLater = "infinispan.cache.addedLater"; final EmbeddedCacheManager nativeCacheManager = TestCacheManagerFactory.fromStream( SpringEmbeddedCacheManagerTest.class .getResourceAsStream(NAMED_ASYNC_CACHE_CONFIG_LOCATION)); final SpringEmbeddedCacheManager objectUnderTest = new SpringEmbeddedCacheManager( nativeCacheManager); nativeCacheManager.defineConfiguration(nameOfInfinispanCacheAddedLater, nativeCacheManager.getDefaultCacheConfiguration()); final org.infinispan.Cache<Object, Object> infinispanCacheAddedLater = nativeCacheManager .getCache(nameOfInfinispanCacheAddedLater); final Cache springCacheAddedLater = objectUnderTest .getCache(nameOfInfinispanCacheAddedLater); assertEquals( "getCache(" + nameOfInfinispanCacheAddedLater + ") should have returned the Spring cache having the Infinispan cache added after creating " + "SpringEmbeddedCacheManager as its underlying native cache. However, the underlying native cache is different.", infinispanCacheAddedLater, springCacheAddedLater.getNativeCache()); nativeCacheManager.stop(); } /** * Test method for * {@link SpringEmbeddedCacheManager#getCacheNames()}. * * @throws IOException */ @Test public final void getCacheNamesShouldReturnAllCachesDefinedInConfigurationFile() throws IOException { final EmbeddedCacheManager nativeCacheManager = TestCacheManagerFactory.fromStream( SpringEmbeddedCacheManagerTest.class .getResourceAsStream(NAMED_ASYNC_CACHE_CONFIG_LOCATION)); final SpringEmbeddedCacheManager objectUnderTest = new SpringEmbeddedCacheManager( nativeCacheManager); final Collection<String> cacheNames = objectUnderTest.getCacheNames(); assertTrue( "SpringEmbeddedCacheManager should load all named caches found in the configuration file of the wrapped " + "native cache manager. However, it does not know about the cache named " + CACHE_NAME_FROM_CONFIGURATION_FILE + " defined in said configuration file.", cacheNames.contains(CACHE_NAME_FROM_CONFIGURATION_FILE)); nativeCacheManager.stop(); } /** * Test method for {@link SpringEmbeddedCacheManager#stop()}. * * @throws IOException */ @Test public final void stopShouldStopTheNativeEmbeddedCacheManager() { withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager(new ConfigurationBuilder())) { @Override public void call() { cm.getCache(); // Implicitly starts EmbeddedCacheManager final SpringEmbeddedCacheManager objectUnderTest = new SpringEmbeddedCacheManager( cm); objectUnderTest.stop(); assertEquals("Calling stop() on SpringEmbeddedCacheManager should stop the enclosed " + "Infinispan EmbeddedCacheManager. However, it is still running.", ComponentStatus.TERMINATED, cm.getStatus()); } }); } /** * Test method for * {@link SpringEmbeddedCacheManager#getNativeCacheManager()} ()}. * * @throws IOException */ @Test public final void getNativeCacheShouldReturnTheEmbeddedCacheManagerSuppliedAtConstructionTime() { withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager()) { @Override public void call() { final SpringEmbeddedCacheManager objectUnderTest = new SpringEmbeddedCacheManager(cm); final EmbeddedCacheManager nativeCacheManagerReturned = objectUnderTest.getNativeCacheManager(); assertSame( "getNativeCacheManager() should have returned the EmbeddedCacheManager supplied at construction time. However, it retuned a different one.", cm, nativeCacheManagerReturned); } }); } @Test public final void getCacheShouldReturnSameInstanceForSameName() { withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager()) { @Override public void call() { // Given cm.defineConfiguration("same", new ConfigurationBuilder().build()); final SpringEmbeddedCacheManager objectUnderTest = new SpringEmbeddedCacheManager(cm); final String sameCacheName = "same"; // When final SpringCache firstObtainedSpringCache = objectUnderTest.getCache(sameCacheName); final SpringCache secondObtainedSpringCache = objectUnderTest.getCache(sameCacheName); // Then assertSame( "getCache() should have returned the same SpringCache instance for the same name", firstObtainedSpringCache, secondObtainedSpringCache); } }); } @Test public final void getCacheShouldReturnDifferentInstancesForDifferentNames() { withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager()) { @Override public void call() { // Given cm.defineConfiguration("thisCache", new ConfigurationBuilder().build()); cm.defineConfiguration("thatCache", new ConfigurationBuilder().build()); final SpringEmbeddedCacheManager objectUnderTest = new SpringEmbeddedCacheManager(cm); final String firstCacheName = "thisCache"; final String secondCacheName = "thatCache"; // When final SpringCache firstObtainedSpringCache = objectUnderTest.getCache(firstCacheName); final SpringCache secondObtainedSpringCache = objectUnderTest.getCache(secondCacheName); // Then assertNotSame( "getCache() should have returned different SpringCache instances for different names", firstObtainedSpringCache, secondObtainedSpringCache); } }); } @Test public final void getCacheThrowsExceptionForSameNameAfterLifecycleStop() { withCacheManager(new CacheManagerCallable(TestCacheManagerFactory.createCacheManager()) { @Override public void call() { // Given cm.defineConfiguration("same", new ConfigurationBuilder().build()); final SpringEmbeddedCacheManager objectUnderTest = new SpringEmbeddedCacheManager(cm); final String sameCacheName = "same"; // When final SpringCache obtainedSpringCache = objectUnderTest.getCache(sameCacheName); assertNotNull( "getCache() should have returned a SpringCache instance", obtainedSpringCache ); // Given objectUnderTest.stop(); // Then Exceptions.expectException(IllegalLifecycleStateException.class, () -> objectUnderTest.getCache(sameCacheName)); } }); } }
10,793
40.837209
158
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/provider/sample/AbstractTestTemplate.java
package org.infinispan.spring.embedded.provider.sample; import java.lang.invoke.MethodHandles; import java.util.Random; import org.infinispan.commons.api.BasicCache; import org.infinispan.spring.embedded.provider.sample.entity.Book; import org.infinispan.spring.embedded.provider.sample.service.CachedBookService; import org.infinispan.spring.embedded.provider.sample.service.CachedBookServiceImpl; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.springframework.cache.CacheManager; import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Abstract template for running a set of tests under different configurations, in order to illustrate how Spring handles * the caching aspects we added to {@link CachedBookServiceImpl <code>CachedBookServiceImpl</code>}. * It calls each method defined in the class and verifies that book instances are indeed cached and removed from the * cache as specified. * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @author Marius Bogoevici * @author Matej Cimbora (mcimbora@redhat.com) */ @Test(groups = "functional") public abstract class AbstractTestTemplate extends AbstractTransactionalTestNGSpringContextTests { protected static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); @AfterMethod public void clearBookCache() { booksCache().clear(); backupCache().clear(); } /** * Demonstrates that loading a {@link Book <code>book</code>} via * {@link CachedBookServiceImpl#findBook(Integer)} does indeed cache * the returned book instance under the supplied bookId. */ @Test public void demonstrateCachingLoadedBooks() { final Integer bookToCacheId = 5; assert !booksCache().containsKey(bookToCacheId) : "Cache should not initially contain the book with id " + bookToCacheId; final Book cachedBook = getBookService().findBook(bookToCacheId); this.log.infof("Book [%s] cached", cachedBook); assert cachedBook.equals(booksCache().get(bookToCacheId)) : "findBook(" + bookToCacheId + ") should have cached book"; } /** * Demonstrate that removing a {@link Book <code>book</code>} from database via * {@link CachedBookServiceImpl#deleteBook(Integer)} does indeed remove * it from cache also. */ @Test public void demonstrateRemovingBookFromCache() { final Integer bookToDeleteId = new Random().nextInt(10) + 1; assert !booksCache().containsKey(bookToDeleteId) : "Cache should not initially contain the book with id " + bookToDeleteId; final Book bookToDelete = getBookService().findBook(bookToDeleteId); this.log.infof("Book [%s] cached", bookToDelete); assert booksCache().get(bookToDeleteId).equals(bookToDelete) : "findBook(" + bookToDeleteId + ") should have cached book"; this.log.infof("Deleting book [%s] ...", bookToDelete); getBookService().deleteBook(bookToDeleteId); this.log.infof("Book [%s] deleted", bookToDelete); assert !booksCache().containsKey(bookToDeleteId) : "deleteBook(" + bookToDelete + ") should have evicted book from cache."; } /** * Demonstrates that updating a {@link Book <code>book</code>} that has already been persisted to * database via {@link CachedBookServiceImpl (Book)} does indeed evict * that book from cache. */ @Test public void demonstrateCacheEvictionUponUpdate() { final Integer bookToUpdateId = 2; assert !booksCache().containsKey(bookToUpdateId): "Cache should not initially contain the book with id " + bookToUpdateId; this.log.infof("Caching book [ID = %d]", bookToUpdateId); final Book bookToUpdate = getBookService().findBook(bookToUpdateId); assert booksCache().get(bookToUpdateId).equals(bookToUpdate) : "findBook(" + bookToUpdateId + ") should have cached book"; this.log.infof("Updating book [%s] ...", bookToUpdate); bookToUpdate.setTitle("Work in Progress"); getBookService().updateBook(bookToUpdate); this.log.infof("Book [%s] updated", bookToUpdate); assert !booksCache().containsKey(bookToUpdateId) : "updateBook(" + bookToUpdate + ") should have removed updated book from cache"; } /** * Demonstrates that creating a new {@link Book <code>book</code>} via * {@link CachedBookServiceImpl#createBook(Book)} * does indeed cache returned book under its generated id. */ @Test public void demonstrateCachePutOnCreate() { final Book bookToCreate = new Book("112-358-132", "Random Author", "Path to Infinispan Enlightenment"); this.log.infof("Creating book [%s] ...", bookToCreate); getBookService().createBook(bookToCreate); this.log.infof("Book [%s] created", bookToCreate); assert booksCache().get(bookToCreate.getId()).equals(bookToCreate) : "createBook(" + bookToCreate + ") should have inserted created book into cache"; } @Test public void testFindCustomCacheResolver() { final Integer bookToCacheId = 5; assert !getCache("custom").containsKey(bookToCacheId): "Cache should not initially contain the book with id " + bookToCacheId; final Book cachedBook = getBookService().findBookCustomCacheResolver(bookToCacheId); this.log.infof("Book [%s] cached", cachedBook); assert cachedBook.equals(getCache("custom").get(bookToCacheId)) : "findBook(" + bookToCacheId + ") should have cached book"; } @Test public void testFindCustomKeyGenerator() { final Integer bookToCacheId = 5; assert !booksCache().containsKey(bookToCacheId): "Cache should not initially contain the book with id " + bookToCacheId; final Book cachedBook = getBookService().findBookCustomKeyGenerator(bookToCacheId); this.log.infof("Book [%s] cached", cachedBook); assert cachedBook.equals(booksCache().get(bookToCacheId)) : "findBook(" + bookToCacheId + ") should have cached book"; } @Test public void testFindConditionMet() { final Integer bookToCacheId = 5; assert !booksCache().containsKey(bookToCacheId): "Cache should not initially contain the book with id " + bookToCacheId; final Book cachedBook = getBookService().findBookCondition(bookToCacheId); this.log.infof("Book [%s] cached", cachedBook); assert cachedBook.equals(booksCache().get(bookToCacheId)) : "findBook(" + bookToCacheId + ") should have cached book"; } @Test public void testFindConditionNotMet() { final Integer bookToCacheId = 1; assert !booksCache().containsKey(bookToCacheId): "Cache should not initially contain the book with id " + bookToCacheId; final Book cachedBook = getBookService().findBookCondition(bookToCacheId); this.log.infof("Book [%s] cached", cachedBook); assert !booksCache().containsKey(bookToCacheId) : "findBook(" + bookToCacheId + ") should not have cached book"; } @Test public void testFindUnlessMet() { final Integer bookToCacheId = 1; assert !booksCache().containsKey(bookToCacheId): "Cache should not initially contain the book with id " + bookToCacheId; final Book cachedBook = getBookService().findBookUnless(bookToCacheId); this.log.infof("Book [%s] cached", cachedBook); assert cachedBook.equals(booksCache().get(bookToCacheId)) : "findBook(" + bookToCacheId + ") should have cached book"; } @Test public void testFindUnlessNotMet() { final Integer bookToCacheId = 5; assert !booksCache().containsKey(bookToCacheId): "Cache should not initially contain the book with id " + bookToCacheId; final Book cachedBook = getBookService().findBookUnless(bookToCacheId); this.log.infof("Book [%s] cached", cachedBook); assert !booksCache().containsKey(bookToCacheId) : "findBook(" + bookToCacheId + ") should not have cached book"; } @Test public void testFindCustomCacheManager() { final Integer bookToCacheId = 5; assert !booksCache().containsKey(bookToCacheId): "Cache should not initially contain the book with id " + bookToCacheId; final Book cachedBook = getBookService().findBookCustomCacheManager(bookToCacheId); this.log.infof("Book [%s] cached", cachedBook); assert cachedBook.equals(booksCache().get(bookToCacheId)) : "findBook(" + bookToCacheId + ") should have cached book"; } @Test public void testCreateCustomCacheManager() { final Book bookToCreate = new Book("112-358-132", "Random Author", "Path to Infinispan Enlightenment"); this.log.infof("Creating book [%s] ...", bookToCreate); getBookService().createBookCustomCacheManager(bookToCreate); this.log.infof("Book [%s] created", bookToCreate); assert bookToCreate.equals(booksCache().get(bookToCreate.getId())) : "createBook(" + bookToCreate + ") should have inserted created book into cache"; } @Test public void testCreateCustomCacheResolver() { final Book bookToCreate = new Book("112-358-132", "Random Author", "Path to Infinispan Enlightenment"); this.log.infof("Creating book [%s] ...", bookToCreate); getBookService().createBookCustomCacheResolver(bookToCreate); this.log.infof("Book [%s] created", bookToCreate); assert bookToCreate.equals(getCache("custom").get(bookToCreate.getId())) : "createBook(" + bookToCreate + ") should have inserted created book into cache"; } @Test public void testCreateCustomKeyGenerator() { final Book bookToCreate = new Book("112-358-132", "Random Author", "Path to Infinispan Enlightenment"); this.log.infof("Creating book [%s] ...", bookToCreate); getBookService().createBookCustomKeyGenerator(bookToCreate); this.log.infof("Book [%s] created", bookToCreate); assert booksCache().containsKey(bookToCreate) : "createBook(" + bookToCreate + ") should have inserted created book into cache"; } @Test public void testCreateConditionMet() { final Book bookToCreate = new Book("112-358-132", "Random Author", "Path to Infinispan Enlightenment"); this.log.infof("Creating book [%s] ...", bookToCreate); Book result = getBookService().createBookCondition(bookToCreate); this.log.infof("Book [%s] created", bookToCreate); assert bookToCreate.equals(booksCache().get(result.getId())) : "createBook(" + bookToCreate + ") should have inserted created book into cache"; } @Test public void testCreateConditionNotMet() { final Book bookToCreate = new Book("112-358-132", "Random Author", "Wrong Path to Infinispan Enlightenment"); this.log.infof("Creating book [%s] ...", bookToCreate); getBookService().createBookCondition(bookToCreate); this.log.infof("Book [%s] created", bookToCreate); assert bookToCreate.getId() != null : "Book.id should have been set."; assert !booksCache().containsKey(bookToCreate.getId()) : "createBook(" + bookToCreate + ") should not have inserted created book into cache"; } @Test public void testCreateUnlessMet() { final Book bookToCreate = new Book("99-999-999", "Random Author", "Path to Infinispan Enlightenment"); this.log.infof("Creating book [%s] ...", bookToCreate); getBookService().createBookUnless(bookToCreate); this.log.infof("Book [%s] created", bookToCreate); assert bookToCreate.equals(booksCache().get(bookToCreate.getId())) : "createBook(" + bookToCreate + ") should have inserted created book into cache"; } @Test public void testCreateUnlessNotMet() { final Book bookToCreate = new Book("112-358-132", "Random Author", "Path to Infinispan Enlightenment"); this.log.infof("Creating book [%s] ...", bookToCreate); getBookService().createBookUnless(bookToCreate); this.log.infof("Book [%s] created", bookToCreate); assert !booksCache().containsKey(bookToCreate.getId()) : "createBook(" + bookToCreate + ") should not have inserted created book into cache"; } @Test public void testDeleteCustomCacheResolver() { final Integer bookToDeleteId = new Random().nextInt(10) + 1; assert !getCache("custom").containsKey(bookToDeleteId): "Cache should not initially contain the book with id " + bookToDeleteId; final Book bookToDelete = getBookService().findBookCustomCacheResolver(bookToDeleteId); this.log.infof("Book [%s] cached", bookToDelete); assert bookToDelete.getId() != null : "Book.id should have been set."; assert bookToDelete.equals(getCache("custom").get(bookToDelete.getId())) : "findBook(" + bookToDeleteId + ") should have cached book"; this.log.infof("Deleting book [%s] ...", bookToDelete); getBookService().deleteBookCustomCacheResolver(bookToDeleteId); this.log.infof("Book [%s] deleted", bookToDelete); assert !getCache("custom").containsKey(bookToDelete.getId()) : "deleteBook(" + bookToDelete + ") should have evicted book from cache."; } @Test public void testDeleteCustomKeyGenerator() { final Integer bookToDeleteId = new Random().nextInt(10) + 1; assert !booksCache().containsKey(bookToDeleteId): "Cache should not initially contain the book with id " + bookToDeleteId; final Book bookToDelete = getBookService().findBook(bookToDeleteId); this.log.infof("Book [%s] cached", bookToDelete); assert bookToDelete.equals(booksCache().get(bookToDeleteId)) : "findBook(" + bookToDeleteId + ") should have cached book"; this.log.infof("Deleting book [%s] ...", bookToDelete); getBookService().deleteBookCustomKeyGenerator(bookToDeleteId); this.log.infof("Book [%s] deleted", bookToDelete); assert !booksCache().containsKey(bookToDelete.getId()) : "deleteBook(" + bookToDelete + ") should have evicted book from cache."; } @Test public void testDeleteConditionMet() { final Integer bookToDeleteId = 2; assert !booksCache().containsKey(bookToDeleteId): "Cache should not initially contain the book with id " + bookToDeleteId; final Book bookToDelete = getBookService().findBook(bookToDeleteId); this.log.infof("Book [%s] cached", bookToDelete); assert bookToDelete.equals(booksCache().get(bookToDeleteId)) : "findBook(" + bookToDeleteId + ") should have cached book"; this.log.infof("Deleting book [%s] ...", bookToDelete); getBookService().deleteBookCondition(bookToDeleteId); this.log.infof("Book [%s] deleted", bookToDelete); assert !booksCache().containsKey(bookToDelete.getId()) : "deleteBook(" + bookToDelete + ") should have evicted book from cache."; } @Test public void testDeleteConditionNotMet() { final Integer bookToDeleteId = 1; assert !booksCache().containsKey(bookToDeleteId): "Cache should not initially contain the book with id " + bookToDeleteId; final Book bookToDelete = getBookService().findBook(bookToDeleteId); this.log.infof("Book [%s] cached", bookToDelete); assert bookToDelete.equals(booksCache().get(bookToDeleteId)) : "findBook(" + bookToDeleteId + ") should have cached book"; this.log.infof("Deleting book [%s] ...", bookToDelete); getBookService().deleteBookCondition(bookToDeleteId); this.log.infof("Book [%s] deleted", bookToDelete); assert bookToDelete.equals(booksCache().get(bookToDeleteId)) : "deleteBook(" + bookToDelete + ") should have evicted book from cache."; } @Test public void testDeleteAllEntries() { final Integer bookToDeleteId1 = 5; final Integer bookToDeleteId2 = 6; assert !booksCache().containsKey(bookToDeleteId1): "Cache should not initially contain the book with id " + bookToDeleteId1; assert !booksCache().containsKey(bookToDeleteId2): "Cache should not initially contain the book with id " + bookToDeleteId2; final Book bookToDelete1 = getBookService().findBook(bookToDeleteId1); this.log.infof("Book [%s] cached", bookToDelete1); assert bookToDelete1.equals(booksCache().get(bookToDeleteId1)) : "findBook(" + bookToDeleteId1 + ") should have cached book"; final Book bookToDelete2 = getBookService().findBook(bookToDeleteId2); this.log.infof("Book [%s] cached", bookToDelete2); assert bookToDelete2.equals(booksCache().get(bookToDeleteId2)) : "findBook(" + bookToDeleteId2 + ") should have cached book"; this.log.infof("Deleting book [%s] ...", bookToDelete1); getBookService().deleteBookAllEntries(bookToDeleteId1); this.log.infof("Book [%s] deleted", bookToDelete1); assert !booksCache().containsKey(bookToDelete1.getId()) : "deleteBook(" + bookToDelete1 + ") should have evicted book from cache."; assert !booksCache().containsKey(bookToDelete2.getId()) : "deleteBook(" + bookToDelete2 + ") should have evicted book from cache."; } @Test public void testDeleteCustomCacheManager() { final Integer bookToDeleteId = new Random().nextInt(10) + 1; assert !booksCache().containsKey(bookToDeleteId): "Cache should not initially contain the book with id " + bookToDeleteId; final Book bookToDelete = getBookService().findBookCustomCacheManager(bookToDeleteId); this.log.infof("Book [%s] cached", bookToDelete); assert bookToDelete.getId() != null : "Book.id should have been set."; assert bookToDelete.equals(booksCache().get(bookToDelete.getId())) : "findBook(" + bookToDeleteId + ") should have cached book"; this.log.infof("Deleting book [%s] ...", bookToDelete); getBookService().deleteBookCustomCacheManager(bookToDeleteId); this.log.infof("Book [%s] deleted", bookToDelete); assert !booksCache().containsKey(bookToDelete.getId()) : "deleteBook(" + bookToDelete + ") should have evicted book from cache."; } @Test public void testDeleteBookBeforeInvocation() { final Integer bookToDeleteId = new Random().nextInt(10) + 1; assert !booksCache().containsKey(bookToDeleteId): "Cache should not initially contain the book with id " + bookToDeleteId; final Book bookToDelete = getBookService().findBook(bookToDeleteId); this.log.infof("Book [%s] cached", bookToDelete); assert bookToDelete.equals(booksCache().get(bookToDelete.getId())) : "findBook(" + bookToDeleteId + ") should have cached book"; this.log.infof("Deleting book [%s] ...", bookToDelete); try { getBookService().deleteBookBeforeInvocation(bookToDeleteId); } catch (IllegalStateException e) { // ok, expected } this.log.infof("Book [%s] deleted", bookToDelete); assert !booksCache().containsKey(bookToDelete.getId()) : "deleteBook(" + bookToDelete + ") should have evicted book from cache."; } @Test public void testCachingCreate() { Book bookToCreate = new Book("112-358-132", "Random Author", "Path to Infinispan Enlightenment"); this.log.infof("Creating book [%s] ...", bookToCreate); getBookService().createBookCachingBackup(bookToCreate); this.log.infof("Book [%s] created", bookToCreate); assert bookToCreate.equals(booksCache().get(bookToCreate.getId())) : "createBook(" + bookToCreate + ") should have inserted created book into cache"; assert bookToCreate.equals(backupCache().get(bookToCreate.getId())) : "createBook(" + bookToCreate + ") should have inserted created book into cache"; } @Test public void testCachingFind() { final Integer bookToCacheId = 5; assert !booksCache().containsKey(bookToCacheId) : "Cache should not initially contain the book with id " + bookToCacheId; assert !backupCache().containsKey(bookToCacheId) : "Cache should not initially contain the book with id " + bookToCacheId; final Book cachedBook = getBookService().findBookCachingBackup(bookToCacheId); this.log.infof("Book [%s] cached", cachedBook); assert cachedBook.equals(booksCache().get(cachedBook.getId())) : "findBook(" + bookToCacheId + ") should have cached book"; assert cachedBook.equals(backupCache().get(cachedBook.getId())) : "findBook(" + bookToCacheId + ") should have cached book"; } @Test public void testCachingDelete() { final Integer bookToDeleteId = new Random().nextInt(10) + 1; assert !booksCache().containsKey(bookToDeleteId) : "Cache should not initially contain the book with id " + bookToDeleteId; assert !backupCache().containsKey(bookToDeleteId) : "Cache should not initially contain the book with id " + bookToDeleteId; final Book bookToDelete1 = getBookService().findBook(bookToDeleteId); this.log.infof("Book [%s] cached", bookToDelete1); final Book bookToDelete2 = getBookService().findBookBackup(bookToDeleteId); this.log.infof("Book [%s] cached", bookToDelete2); assert bookToDelete1.equals(booksCache().get(bookToDeleteId)) : "findBook(" + bookToDeleteId + ") should have cached book"; assert bookToDelete1.equals(backupCache().get(bookToDeleteId)) : "findBook(" + bookToDeleteId + ") should have cached book"; this.log.infof("Deleting book [%s] ...", bookToDelete1); getBookService().deleteBookCachingBackup(bookToDeleteId); this.log.infof("Book [%s] deleted", bookToDelete1); assert !booksCache().containsKey(bookToDelete1.getId()) : "deleteBook(" + bookToDelete1 + ") should have evicted book from cache."; assert !backupCache().containsKey(bookToDelete1.getId()) : "deleteBook(" + bookToDelete2 + ") should have evicted book from cache."; } protected BasicCache<Object, Object> booksCache() { return (BasicCache<Object, Object>) getCacheManager().getCache("books").getNativeCache(); } protected BasicCache<Object, Object> backupCache() { return (BasicCache<Object, Object>) getCacheManager().getCache("backup").getNativeCache(); } protected BasicCache<Object, Object> getCache(String name) { return (BasicCache<Object, Object>) getCacheManager().getCache(name).getNativeCache(); } public abstract CachedBookService getBookService(); public abstract CacheManager getCacheManager(); }
22,749
42.005671
134
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/provider/sample/SampleXmlConfigurationTest.java
package org.infinispan.spring.embedded.provider.sample; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.infinispan.spring.embedded.provider.sample.service.CachedBookService; import org.infinispan.spring.embedded.provider.SpringEmbeddedCacheManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.cache.CacheManager; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.testng.annotations.Test; /** * Tests using XML based cache configuration. * * @author Matej Cimbora (mcimbora@redhat.com) */ @Test(testName = "spring.embedded.provider.SampleXmlConfigurationTest", groups = "functional") @ContextConfiguration(locations = "classpath:/org/infinispan/spring/embedded/provider/sample/SampleXmlConfigurationTestConfig.xml") @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class SampleXmlConfigurationTest extends AbstractTestTemplate { @Qualifier(value = "cachedBookServiceImpl") @Autowired(required = true) private CachedBookService bookService; @Autowired(required = true) private SpringEmbeddedCacheManager cacheManager; @Override public CachedBookService getBookService() { return bookService; } @Override public CacheManager getCacheManager() { return cacheManager; } }
1,672
38.833333
138
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/provider/sample/DataSourceResolver.java
package org.infinispan.spring.embedded.provider.sample; import javax.sql.XADataSource; import org.h2.jdbcx.JdbcDataSource; import com.arjuna.ats.internal.jdbc.DynamicClass; /** * Required by JBoss Transactions for DataSource resolving. * * @author Matej Cimbora (mcimbora@redhat.com) */ public class DataSourceResolver implements DynamicClass { @Override public XADataSource getDataSource(String url) { JdbcDataSource dataSource = new JdbcDataSource(); dataSource.setURL(String.format("jdbc:%s;DB_CLOSE_DELAY=-1", url)); dataSource.setUser("sa"); dataSource.setPassword(""); return dataSource; } }
646
24.88
73
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/provider/sample/SampleHotrodServerLifecycleBean.java
package org.infinispan.spring.embedded.provider.sample; import org.infinispan.client.hotrod.test.HotRodClientTestingUtil; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.server.hotrod.HotRodServer; import org.infinispan.server.hotrod.configuration.HotRodServerConfigurationBuilder; import org.infinispan.server.hotrod.test.HotRodTestingUtil; import org.infinispan.test.fwk.TestCacheManagerFactory; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; /** * Starts test HotRod server instance with pre-defined set of caches. * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @author Matej Cimbora (mcimbora@redhat.com) */ public class SampleHotrodServerLifecycleBean implements InitializingBean, DisposableBean { private EmbeddedCacheManager cacheManager; private HotRodServer hotrodServer; private String remoteCacheName; private String remoteBackupCacheName; private String customCacheName; public void setRemoteCacheName(String remoteCacheName) { this.remoteCacheName = remoteCacheName; } public void setRemoteBackupCacheName(String remoteBackupCacheName) { this.remoteBackupCacheName = remoteBackupCacheName; } public void setCustomCacheName(String customCacheName) { this.customCacheName = customCacheName; } @Override public void afterPropertiesSet() throws Exception { cacheManager = TestCacheManagerFactory.createCacheManager(HotRodTestingUtil.hotRodCacheConfiguration()); cacheManager.defineConfiguration(remoteCacheName, HotRodTestingUtil.hotRodCacheConfiguration().build()); cacheManager.defineConfiguration(remoteBackupCacheName, HotRodTestingUtil.hotRodCacheConfiguration().build()); cacheManager.defineConfiguration(customCacheName, HotRodTestingUtil.hotRodCacheConfiguration().build()); HotRodServerConfigurationBuilder hcb = new HotRodServerConfigurationBuilder(); hcb.port(15233); hotrodServer = HotRodClientTestingUtil.startHotRodServer(cacheManager, hcb); } @Override public void destroy() throws Exception { cacheManager.stop(); hotrodServer.stop(); } }
2,231
36.830508
116
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/provider/sample/SampleTransactionIntegrationTest.java
package org.infinispan.spring.embedded.provider.sample; import jakarta.transaction.HeuristicMixedException; import jakarta.transaction.HeuristicRollbackException; import jakarta.transaction.RollbackException; import jakarta.transaction.SystemException; import jakarta.transaction.TransactionManager; import org.infinispan.Cache; import org.infinispan.commons.api.BasicCache; import org.infinispan.spring.common.InfinispanTestExecutionListener; import org.infinispan.spring.embedded.provider.sample.entity.Book; import org.infinispan.spring.embedded.provider.sample.service.CachedTransactionBookService; import org.infinispan.spring.embedded.provider.SpringEmbeddedCacheManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.TestExecutionListeners; import org.springframework.test.context.testng.AbstractTransactionalTestNGSpringContextTests; import org.testng.annotations.AfterMethod; import org.testng.annotations.Test; /** * Transaction integration tests. Verifies transaction manager functioning across DB/service/cache level. * * @author Matej Cimbora (mcimbora@redhat.com) */ @Test(testName = "spring.embedded.provider.SampleTransactionIntegrationTest", groups = "functional") @ContextConfiguration(locations = "classpath:/org/infinispan/spring/embedded/provider/sample/SampleTransactionIntegrationTestConfig.xml") @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) @TestExecutionListeners(value = InfinispanTestExecutionListener.class, mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS) public class SampleTransactionIntegrationTest extends AbstractTransactionalTestNGSpringContextTests { @Qualifier(value = "cachedTransactionBookServiceImpl") @Autowired private CachedTransactionBookService bookService; @Autowired private SpringEmbeddedCacheManager cacheManager; @AfterMethod public void clean() { transactionalCache().clear(); nonTransactionalCache().clear(); } @Test public void testUsingTemplate() throws SystemException { final Book[] created = new Book[2]; final Book[] found = new Book[2]; TransactionManager tm = getTransactionManager("booksTransactional"); assert tm.getStatus() == 0 : "Transaction should be in state 'RUNNING'"; Book nonTxBook = new Book("1-1-2-3-5", "Random author", "Title"); Book txBook = new Book("1-2-2-4-8", "Not so random author", "Title"); created[0] = bookService.createBookTransactionalCache(nonTxBook); found[0] = bookService.findBookTransactionalCache(Integer.valueOf(9)); created[1] = bookService.createBookNonTransactionalCache(txBook); found[1] = bookService.findBookNonTransactionalCache(Integer.valueOf(9)); // rollback transaction tm.rollback(); // check whether rollback caused cached items to be removed from transactional cache assert !transactionalCache().values().contains(created[0]); assert !transactionalCache().values().contains(found[0]); // rollback should not have any impact on non-transactional cache assert nonTransactionalCache().values().contains(created[1]); assert nonTransactionalCache().values().contains(found[1]); // make sure books have not been persisted assert bookService.findBookCacheDisabled(created[0].getId()) == null; assert bookService.findBookCacheDisabled(created[1].getId()) == null; } @Test public void testUsingTemplateNoRollback() throws SystemException, HeuristicRollbackException, HeuristicMixedException, RollbackException { final Book[] created = new Book[2]; final Book[] found = new Book[2]; assert !transactionalCache().containsKey(Integer.valueOf(9)); TransactionManager tm = getTransactionManager("booksTransactional"); assert tm.getStatus() == 0 : "Transaction should be in state 'RUNNING'"; Book nonTxBook = new Book("1-1-2-3-5", "Random author", "Title"); Book txBook = new Book("1-2-2-4-8", "Not so random author", "Title"); created[0] = bookService.createBookTransactionalCache(nonTxBook); found[0] = bookService.findBookTransactionalCache(Integer.valueOf(9)); created[1] = bookService.createBookNonTransactionalCache(txBook); found[1] = bookService.findBookNonTransactionalCache(Integer.valueOf(9)); // commit changes tm.commit(); // all items should be cached regardless of cache type assert transactionalCache().values().contains(created[0]); assert transactionalCache().values().contains(found[0]); assert nonTransactionalCache().values().contains(created[1]); assert nonTransactionalCache().values().contains(found[1]); // check whether books have been persisted assert bookService.findBookCacheDisabled(created[0].getId()) != null; assert bookService.findBookCacheDisabled(created[1].getId()) != null; } private TransactionManager getTransactionManager(String cacheName) { Cache cache = (Cache) cacheManager.getCache(cacheName).getNativeCache(); return cache.getAdvancedCache().getTransactionManager(); } private BasicCache<Object, Object> nonTransactionalCache() { return (BasicCache<Object, Object>) cacheManager.getCache("books").getNativeCache(); } private BasicCache<Object, Object> transactionalCache() { return (BasicCache<Object, Object>) cacheManager.getCache("booksTransactional").getNativeCache(); } }
5,668
46.638655
141
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/provider/sample/dao/BaseBookDao.java
package org.infinispan.spring.embedded.provider.sample.dao; import org.infinispan.spring.embedded.provider.sample.entity.Book; /** * <p> * A simple, woefully incomplete {@code DAO} for storing, retrieving and removing {@link Book * <code>Books</code>}. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @since 5.1 */ public interface BaseBookDao { /** * <p> * Look up and return the {@code Book} identified by the supplied {@code bookId}, or {@code null} * if no such book exists. * </p> * * @param bookId * @return The {@code Book} identified by the supplied {@code bookId}, or {@code null} */ Book findBook(Integer bookId); /** * <p> * Remove the {@code Book} identified by the supplied {@code bookId} from this store. * </p> * * @param bookId */ void deleteBook(Integer bookId); /** * <p> * Update provided {@code book} and return its updated version. * </p> * * @param book * The book to update * @return Updated book */ Book updateBook(Book book); /** * <p> * Create new book and return it. If the book already exists, throw exception. * </p> * * @param book The book to create * @return Created book. */ Book createBook(Book book); }
1,340
22.526316
100
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/provider/sample/dao/JdbcBookDao.java
package org.infinispan.spring.embedded.provider.sample.dao; import java.lang.invoke.MethodHandles; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collection; import javax.sql.DataSource; import org.infinispan.spring.embedded.provider.sample.entity.Book; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.jdbc.core.RowMapper; import org.springframework.jdbc.core.namedparam.MapSqlParameterSource; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.namedparam.SqlParameterSource; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.stereotype.Repository; /** * <p> * {@link BaseBookDao <code>BookDao</code>} implementation that fronts a relational database, using * {@code JDBC} to store and retrieve {@link Book <code>books</code>}. Serves as an example of how * to use <a href="http://www.springframework.org">Spring</a>'s * {@link org.springframework.cache.annotation.Cacheable <code>@Cacheable</code>} and * {@link org.springframework.cache.annotation.CacheEvict <code>@CacheEvict</code>}. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @since 5.1 */ @Repository(value = "jdbcBookDao") public class JdbcBookDao implements BaseBookDao { private static final Log log = LogFactory.getLog(MethodHandles.lookup().lookupClass()); private NamedParameterJdbcTemplate jdbcTemplate; private SimpleJdbcInsert bookInsert; @Autowired(required = true) public void initialize(final DataSource dataSource) { this.jdbcTemplate = new NamedParameterJdbcTemplate(dataSource); this.bookInsert = new SimpleJdbcInsert(dataSource).withTableName("books") .usingGeneratedKeyColumns("id"); } public Book findBook(Integer bookId) { try { this.log.infof("Loading book [ID = %d]", bookId); return this.jdbcTemplate.queryForObject("SELECT * FROM books WHERE id = :id", new MapSqlParameterSource("id", bookId), new BookRowMapper()); } catch (EmptyResultDataAccessException e) { return null; } } private static final class BookRowMapper implements RowMapper<Book> { @Override public Book mapRow(ResultSet rs, int rowNum) throws SQLException { final Book mappedBook = new Book(); mappedBook.setId(rs.getInt("id")); mappedBook.setIsbn(rs.getString("isbn")); mappedBook.setAuthor(rs.getString("author")); mappedBook.setTitle(rs.getString("title")); return mappedBook; } } @Override public void deleteBook(Integer bookId) { this.log.infof("Deleting book [ID = %d]", bookId); this.jdbcTemplate.update("DELETE FROM books WHERE id = :id", new MapSqlParameterSource("id", bookId)); } public Collection<Book> getBooks() { return this.jdbcTemplate.query("SELECT * FROM books", new BookRowMapper()); } @Override public Book updateBook(Book bookToUpdate) { this.log.infof("Updating book [%s]", bookToUpdate); this.jdbcTemplate.update( "UPDATE books SET isbn = :isbn WHERE id = :id", createParameterSourceFor(bookToUpdate)); this.log.infof("Book [%s] updated", bookToUpdate); return bookToUpdate; } @Override public Book createBook(Book bookToCreate) { final Number newBookId = this.bookInsert .executeAndReturnKey(createParameterSourceFor(bookToCreate)); bookToCreate.setId(newBookId.intValue()); this.log.infof("Book [%s] persisted for the first time", bookToCreate); return bookToCreate; } private SqlParameterSource createParameterSourceFor(final Book book) { return new MapSqlParameterSource().addValue("id", book.getId()) .addValue("isbn", book.getIsbn()).addValue("author", book.getAuthor()) .addValue("title", book.getTitle()); } }
4,136
36.954128
108
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/provider/sample/entity/Book.java
package org.infinispan.spring.embedded.provider.sample.entity; import java.io.Serializable; /** * Book. * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @since 5.1 */ public class Book implements Serializable { private Integer id; private String isbn; private String author; private String title; public Book() { } public Book(String isbn, String author, String title) { this(null, isbn, author, title); } public Book(Integer id, String isbn, String author, String title) { this.id = id; this.isbn = isbn; this.author = author; this.title = title; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getIsbn() { return isbn; } public void setIsbn(String isbn) { this.isbn = isbn; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((author == null) ? 0 : author.hashCode()); result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((isbn == null) ? 0 : isbn.hashCode()); result = prime * result + ((title == null) ? 0 : title.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Book other = (Book) obj; if (author == null) { if (other.author != null) return false; } else if (!author.equals(other.author)) return false; if (id == null) { if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (isbn == null) { if (other.isbn != null) return false; } else if (!isbn.equals(other.isbn)) return false; if (title == null) { if (other.title != null) return false; } else if (!title.equals(other.title)) return false; return true; } @Override public String toString() { return "Book [id=" + id + ", isbn=" + isbn + ", author=" + author + ", title=" + title + "]"; } }
2,467
22.730769
99
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/provider/sample/generators/SingleArgKeyGenerator.java
package org.infinispan.spring.embedded.provider.sample.generators; import java.lang.reflect.Method; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.stereotype.Component; /** * Simple implementation of {@link KeyGenerator} interface. It returns the first * argument passed to a method. * * @author Matej Cimbora (mcimbora@redhat.com) */ @Component public class SingleArgKeyGenerator implements KeyGenerator { @Override public Object generate(Object o, Method method, Object... params) { if (params != null && params.length == 1) { return params[0]; } else { throw new IllegalArgumentException("This generator requires exactly one parameter to be specified."); } } }
757
28.153846
110
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/provider/sample/service/CachedTransactionBookService.java
package org.infinispan.spring.embedded.provider.sample.service; import org.infinispan.spring.embedded.provider.sample.entity.Book; /** * Service providing basic create/find operations on both transactional and non-transactional caches. * * @author Matej Cimbora (mcimbora@redhat.com) */ public interface CachedTransactionBookService { Book createBookNonTransactionalCache(Book book); Book createBookTransactionalCache(Book book); Book findBookNonTransactionalCache(Integer id); Book findBookTransactionalCache(Integer id); Book findBookCacheDisabled(Integer id); }
591
25.909091
101
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/provider/sample/service/CachedBookService.java
package org.infinispan.spring.embedded.provider.sample.service; import org.infinispan.spring.embedded.provider.sample.entity.Book; /** * Service providing extension to basic CRUD operations in order to test individual caching annotations and parameters * they support. * * @author Matej Cimbora (mcimbora@redhat.com) */ public interface CachedBookService { Book findBook(Integer bookId); Book findBookCondition(Integer bookId); Book findBookUnless(Integer bookId); Book findBookCustomKeyGenerator(Integer bookId); Book findBookCustomCacheResolver(Integer bookId); Book findBookBackup(Integer bookId); Book findBookCachingBackup(Integer bookId); Book findBookCustomCacheManager(Integer bookId); Book createBook(Book book); Book createBookCondition(Book book); Book createBookUnless(Book book); Book createBookCustomKeyGenerator(Book book); Book createBookCustomCacheResolver(Book book); Book createBookCustomCacheManager(Book book); Book createBookCachingBackup(Book book); void deleteBook(Integer bookId); void deleteBookCondition(Integer bookId); void deleteBookCustomKeyGenerator(Integer bookId); void deleteBookCustomCacheResolver(Integer bookId); void deleteBookAllEntries(Integer bookId); void deleteBookCachingBackup(Integer bookId); void deleteBookCustomCacheManager(Integer bookId); void deleteBookBeforeInvocation(Integer bookId); Book updateBook(Book book); }
1,473
23.163934
118
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/provider/sample/service/CachedBookServiceImpl.java
package org.infinispan.spring.embedded.provider.sample.service; import org.infinispan.spring.embedded.provider.sample.dao.JdbcBookDao; import org.infinispan.spring.embedded.provider.sample.entity.Book; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.cache.annotation.Caching; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @author Matej Cimbora (mcimbora@redhat.com) */ @Transactional @Service public class CachedBookServiceImpl implements CachedBookService { @Autowired private JdbcBookDao baseDao; /** * <p> * Look up and return the {@code Book} identified by the supplied {@code bookId}. By annotating * this method with {@code @Cacheable(value = "books", key = "#bookId")} we achieve the * following: * <ol> * <li> * {@code Book} instances returned from this method will be cached in a named * {@link org.springframework.cache.Cache <code>Cache</code>} &quot;books&quot;</li> * <li> * The key used to cache {@code Book} instances will be the supplied {@code bookId}.</li> * </ol> * </p> * <p> * Note that it is <strong>important</strong> that we explicitly tell Spring to use {@code bookId} * as the cache key. Otherwise, Spring would <strong>derive</strong> a cache key from the * parameters passed in (in our case only {@code bookId}), a cache key we have no control over. * This would get us into trouble when in {@link #updateBook(Book)} we need a book's cache key to * remove it from the cache. But we wouldn't know that cache key since we don't know Spring's key * generation algorithm. Therefore, we consistently use {@code key = "#bookId"} or * {@code key = "#book.id"} to tell Spring to <strong>always</strong> use a book's id as its * cache key. * </p> */ @Override @Cacheable(value = "books", key = "#bookId") public Book findBook(Integer bookId) { return baseDao.findBook(bookId); } /** * <p> * Remove the book identified by the supplied {@code bookId} from database. By annotating this * method with {@code @CacheEvict(value = "books", key = "#bookId")} we make sure that Spring * will remove the book cache under key {@code bookId} (if any) from the * {@link org.springframework.cache.Cache <code>Cache</code>} &quot;books&quot;. * </p> */ @Override @CacheEvict(value = "books", key = "#bookId") public void deleteBook(Integer bookId) { baseDao.deleteBook(bookId); } /** * <p> * Store the supplied {@code bookToStore} in database. Since it is annotated with * {@code @CacheEvict(value = "books", key = "#book.id", condition = "#book.id != null")} * this method will tell Spring to remove any book cached under the key * {@code book.getId()} from the {@link org.springframework.cache.Cache * <code>Cache</code>} &quot;books&quot;. This eviction will only be triggered if that id is not * {@code null}. * </p> */ @Override @CacheEvict(value = "books", key = "#book.id", condition = "#book.id != null") public Book updateBook(Book book) { return baseDao.updateBook(book); } @Override @CachePut(value = "books", key = "#book.id") public Book createBook(Book book) { return baseDao.createBook(book); } @Override @Cacheable(value = "books", key = "#bookId", condition = "#bookId > 1") public Book findBookCondition(Integer bookId) { return baseDao.findBook(bookId); } @Override @Cacheable(value = "books", key = "#bookId", unless = "#bookId > 1") public Book findBookUnless(Integer bookId) { return baseDao.findBook(bookId); } @Override @Cacheable(value = "books", keyGenerator = "singleArgKeyGenerator") public Book findBookCustomKeyGenerator(Integer bookId) { return baseDao.findBook(bookId); } @Override @Cacheable(value = "books", key = "#bookId", cacheResolver = "customCacheResolver") public Book findBookCustomCacheResolver(Integer bookId) { return baseDao.findBook(bookId); } @Override @Cacheable(value = "backup", key = "#bookId") public Book findBookBackup(Integer bookId) { return baseDao.findBook(bookId); } @Override @CachePut(value = "books", key = "#book.id", condition = "#book.title == 'Path to Infinispan Enlightenment'") public Book createBookCondition(Book book) { return baseDao.createBook(book); } @Override @CachePut(value = "books", key = "#book.id", unless = "#book.isbn == '112-358-132'") public Book createBookUnless(Book book) { return baseDao.createBook(book); } @Override @CachePut(value = "books", keyGenerator = "singleArgKeyGenerator") public Book createBookCustomKeyGenerator(Book book) { return baseDao.createBook(book); } @Override @CachePut(value = "books", key = "#book.id", cacheResolver = "customCacheResolver") public Book createBookCustomCacheResolver(Book book) { return baseDao.createBook(book); } @Override @CachePut(value = "books", key = "#book.id", cacheManager = "cacheManager") public Book createBookCustomCacheManager(Book book) { return baseDao.createBook(book); } @Override @CacheEvict(value = "books", key = "#bookId", condition = "#bookId > 1") public void deleteBookCondition(Integer bookId) { baseDao.deleteBook(bookId); } @Override @CacheEvict(value = "books", keyGenerator = "singleArgKeyGenerator") public void deleteBookCustomKeyGenerator(Integer bookId) { baseDao.deleteBook(bookId); } @Override @CacheEvict(value = "books", key = "#bookId", cacheResolver = "customCacheResolver") public void deleteBookCustomCacheResolver(Integer bookId) { baseDao.deleteBook(bookId); } @Override @CacheEvict(value = "books", key = "#bookId", allEntries = true) public void deleteBookAllEntries(Integer bookId) { baseDao.deleteBook(bookId); } @Override @Caching(put = {@CachePut(value = "books", key = "#book.id"), @CachePut(value = "backup", key = "#book.id")}) public Book createBookCachingBackup(Book book) { return baseDao.createBook(book); } @Override @Caching(cacheable = {@Cacheable(value = "books", key = "#bookId"), @Cacheable(value = "backup", key = "#bookId")}) public Book findBookCachingBackup(Integer bookId) { return baseDao.findBook(bookId); } @Override @Cacheable(value = "books", cacheManager = "cacheManager") public Book findBookCustomCacheManager(Integer bookId) { return baseDao.findBook(bookId); } @Override @Caching(evict = {@CacheEvict(value = "books"), @CacheEvict(value = "backup")}) public void deleteBookCachingBackup(Integer bookId) { baseDao.deleteBook(bookId); } @Override @CacheEvict(value = "books", cacheManager = "cacheManager") public void deleteBookCustomCacheManager(Integer bookId) { baseDao.deleteBook(bookId); } @Override @CacheEvict(value = "books", beforeInvocation = true) public void deleteBookBeforeInvocation(Integer bookId) { throw new IllegalStateException("This method throws exception by default."); } }
7,501
34.554502
118
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/provider/sample/service/CachedTransactionBookServiceImpl.java
package org.infinispan.spring.embedded.provider.sample.service; import org.infinispan.spring.embedded.provider.sample.dao.BaseBookDao; import org.infinispan.spring.embedded.provider.sample.entity.Book; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CachePut; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** * @author Matej Cimbora (mcimbora@redhat.com) */ @Transactional @Service public class CachedTransactionBookServiceImpl implements CachedTransactionBookService { @Autowired private BaseBookDao baseDao; @CachePut(value = "books", key = "#book.id") @Override public Book createBookNonTransactionalCache(Book book) { return baseDao.createBook(book); } @CachePut(value = "booksTransactional", key = "#book.id") @Override public Book createBookTransactionalCache(Book book) { return baseDao.createBook(book); } @Cacheable(value = "books") @Override public Book findBookNonTransactionalCache(Integer id) { return baseDao.findBook(id); } @Cacheable(value = "booksTransactional") @Override public Book findBookTransactionalCache(Integer id) { return baseDao.findBook(id); } @Override public Book findBookCacheDisabled(Integer id) { return baseDao.findBook(id); } }
1,449
28
87
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/provider/sample/resolvers/CustomCacheResolver.java
package org.infinispan.spring.embedded.provider.sample.resolvers; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.Cache; import org.springframework.cache.CacheManager; import org.springframework.cache.interceptor.CacheOperationInvocationContext; import org.springframework.cache.interceptor.CacheResolver; import org.springframework.stereotype.Component; /** * Simple implementation of {@link CacheResolver} interface. It returns a single * instance of {@link Cache} with name 'custom'. * * @author Matej Cimbora (mcimbora@redhat.com) */ @Component public class CustomCacheResolver implements CacheResolver { private static final String CACHE_NAME = "custom"; @Autowired private CacheManager cacheManager; @Override public Collection<? extends Cache> resolveCaches(CacheOperationInvocationContext<?> cacheOperationInvocationContext) { return new ArrayList<>(Arrays.asList(cacheManager.getCache(CACHE_NAME))); } }
1,078
31.69697
121
java
null
infinispan-main/spring/spring6/spring6-embedded/src/test/java/org/infinispan/spring/embedded/builders/SpringEmbeddedCacheManagerFactoryBeanBuilder.java
package org.infinispan.spring.embedded.builders; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.spring.embedded.provider.SpringEmbeddedCacheManagerFactoryBean; import org.springframework.core.io.ClassPathResource; /** * Builder for tests of SpringEmbeddedCacheManagerFactoryBean. * * @author Sebastian Laskawiec */ public class SpringEmbeddedCacheManagerFactoryBeanBuilder { private SpringEmbeddedCacheManagerFactoryBean buildingBean = new SpringEmbeddedCacheManagerFactoryBean(); private SpringEmbeddedCacheManagerFactoryBeanBuilder() { } public static SpringEmbeddedCacheManagerFactoryBeanBuilder defaultBuilder() { return new SpringEmbeddedCacheManagerFactoryBeanBuilder(); } public SpringEmbeddedCacheManagerFactoryBeanBuilder fromFile(String configurationFile, Class<?> aClass) { buildingBean.setConfigurationFileLocation(new ClassPathResource(configurationFile, aClass)); return this; } public SpringEmbeddedCacheManagerFactoryBeanBuilder withGlobalConfiguration(GlobalConfigurationBuilder globalConfigurationBuilder) { buildingBean.addCustomGlobalConfiguration(globalConfigurationBuilder); return this; } public SpringEmbeddedCacheManagerFactoryBean build() throws Exception { buildingBean.afterPropertiesSet(); return buildingBean; } public SpringEmbeddedCacheManagerFactoryBeanBuilder withConfigurationBuilder(ConfigurationBuilder configurationBuilder) { buildingBean.addCustomCacheConfiguration(configurationBuilder); return this; } }
1,662
35.955556
135
java
null
infinispan-main/spring/spring6/spring6-embedded/src/main/java/org/infinispan/spring/embedded/SpringEmbeddedModule.java
package org.infinispan.spring.embedded; import static org.infinispan.marshall.protostream.impl.SerializationContextRegistry.MarshallerType.GLOBAL; import static org.infinispan.marshall.protostream.impl.SerializationContextRegistry.MarshallerType.PERSISTENCE; import org.infinispan.commons.configuration.ClassAllowList; import org.infinispan.commons.logging.Log; import org.infinispan.commons.marshall.JavaSerializationMarshaller; import org.infinispan.commons.util.NullValue; import org.infinispan.configuration.global.GlobalConfiguration; import org.infinispan.factories.GlobalComponentRegistry; import org.infinispan.factories.annotations.InfinispanModule; import org.infinispan.lifecycle.ModuleLifecycle; import org.infinispan.marshall.protostream.impl.SerializationContextRegistry; import org.infinispan.protostream.BaseMarshaller; import org.infinispan.spring.common.session.MapSessionProtoAdapter; import org.springframework.session.MapSession; /** * Add support for Spring-specific classes like {@link NullValue} in embedded caches. * * @author Dan Berindei * @since 12.1 */ @InfinispanModule(name = "spring-embedded", requiredModules = "core") public class SpringEmbeddedModule implements ModuleLifecycle { @Override public void cacheManagerStarting(GlobalComponentRegistry gcr, GlobalConfiguration globalConfiguration) { ClassAllowList serializationAllowList = gcr.getCacheManager().getClassAllowList(); serializationAllowList.addClasses(NullValue.class); serializationAllowList.addRegexps("java.util\\..*", "org.springframework\\..*"); JavaSerializationMarshaller serializationMarshaller = new JavaSerializationMarshaller(serializationAllowList); SerializationContextRegistry ctxRegistry = gcr.getComponent(SerializationContextRegistry.class); addSessionContextInitializerAndMarshaller(ctxRegistry, serializationMarshaller); } private void addSessionContextInitializerAndMarshaller(SerializationContextRegistry ctxRegistry, JavaSerializationMarshaller serializationMarshaller) { // Skip registering the marshallers if the MapSession class is not available try { new MapSession(); } catch (NoClassDefFoundError e) { Log.CONFIG.debug("spring-session classes not found, skipping the session context initializer registration"); return; } org.infinispan.spring.common.session.PersistenceContextInitializerImpl sessionSci = new org.infinispan.spring.common.session.PersistenceContextInitializerImpl(); ctxRegistry.addContextInitializer(SerializationContextRegistry.MarshallerType.PERSISTENCE, sessionSci); ctxRegistry.addContextInitializer(SerializationContextRegistry.MarshallerType.GLOBAL, sessionSci); BaseMarshaller sessionAttributeMarshaller = new MapSessionProtoAdapter.SessionAttributeRawMarshaller(serializationMarshaller); ctxRegistry.addMarshaller(PERSISTENCE, sessionAttributeMarshaller); ctxRegistry.addMarshaller(GLOBAL, sessionAttributeMarshaller); } }
3,080
52.12069
167
java
null
infinispan-main/spring/spring6/spring6-embedded/src/main/java/org/infinispan/spring/embedded/AbstractEmbeddedCacheManagerFactory.java
package org.infinispan.spring.embedded; import java.io.IOException; import org.infinispan.configuration.cache.ConfigurationBuilder; import org.infinispan.configuration.global.GlobalConfigurationBuilder; import org.infinispan.configuration.parsing.ConfigurationBuilderHolder; import org.infinispan.configuration.parsing.ParserRegistry; import org.infinispan.manager.DefaultCacheManager; import org.infinispan.manager.EmbeddedCacheManager; import org.infinispan.util.logging.Log; import org.infinispan.util.logging.LogFactory; import org.springframework.core.io.Resource; /** * <p> * An abstract base class for factories creating cache managers that are backed by an * EmbeddedCacheManager. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * @author Marius Bogoevici */ public class AbstractEmbeddedCacheManagerFactory { private static final Log logger = LogFactory.getLog(AbstractEmbeddedCacheManagerFactory.class); private Resource configurationFileLocation; private GlobalConfigurationBuilder gcb; private ConfigurationBuilder builder; // ------------------------------------------------------------------------ // Create fully configured EmbeddedCacheManager instance // ------------------------------------------------------------------------ protected EmbeddedCacheManager createBackingEmbeddedCacheManager() throws IOException { if (configurationFileLocation != null) { ConfigurationBuilderHolder configurationBuilderHolder = new ParserRegistry(Thread.currentThread().getContextClassLoader()) .parse(configurationFileLocation.getURL()); if(gcb != null) { configurationBuilderHolder.getGlobalConfigurationBuilder().read(gcb.build()); } if (builder != null) { ConfigurationBuilder dcb = configurationBuilderHolder.getDefaultConfigurationBuilder(); if (dcb != null) dcb.read(builder.build()); else throw logger.noDefaultCache(); } return new DefaultCacheManager(configurationBuilderHolder, true); } else { if (gcb == null) { if (logger.isDebugEnabled()) logger.debug("GlobalConfigurationBuilder is null. Using default new " + "instance."); gcb = new GlobalConfigurationBuilder(); } if (builder != null) { ConfigurationBuilderHolder configurationBuilderHolder = new ConfigurationBuilderHolder(Thread.currentThread().getContextClassLoader(), gcb); configurationBuilderHolder.getGlobalConfigurationBuilder().read(gcb.build()); if (gcb.defaultCacheName().isPresent()) { configurationBuilderHolder.getNamedConfigurationBuilders().put(gcb.defaultCacheName().get(), builder); } else { throw logger.noDefaultCache(); } return new DefaultCacheManager(configurationBuilderHolder, true); } else { return new DefaultCacheManager(gcb.build()); } } } // ------------------------------------------------------------------------ // Setter for location of configuration file // ------------------------------------------------------------------------ /** * <p> * Sets the {@link Resource <code>location</code>} of the * configuration file which will be used to configure the * {@link EmbeddedCacheManager <code>EmbeddedCacheManager</code>} the * {@link org.infinispan.spring.embedded.provider.SpringEmbeddedCacheManager * <code>SpringEmbeddedCacheManager</code>} created by this <code>FactoryBean</code> delegates * to. If no location is supplied, <tt>Infinispan</tt>'s default configuration will be used. * </p> * <p> * Note that configuration settings defined via using explicit setters exposed by this * <code>FactoryBean</code> take precedence over those defined in the configuration file pointed * to by <code>configurationFileLocation</code>. * </p> * * @param configurationFileLocation * The {@link Resource <code>location</code>} of the * configuration file which will be used to configure the * {@link EmbeddedCacheManager * <code>EmbeddedCacheManager</code>} the * {@link org.infinispan.spring.embedded.provider.SpringEmbeddedCacheManager * <code>SpringEmbeddedCacheManager</code>} created by this <code>FactoryBean</code> * delegates to */ public void setConfigurationFileLocation(final Resource configurationFileLocation) { this.configurationFileLocation = configurationFileLocation; } /** * Sets the {@link GlobalConfigurationBuilder} to use when creating an <code>EmbeddedCacheManager</code>. * * @param gcb the <code>GlobalConfigurationBuilder</code> instance. */ public void addCustomGlobalConfiguration(final GlobalConfigurationBuilder gcb) { this.gcb = gcb; } /** * Sets the {@link ConfigurationBuilder} to use when creating an <code>EmbeddedCacheManager</code>. * * @param builder the <code>ConfigurationBuilder</code> instance. */ public void addCustomCacheConfiguration(final ConfigurationBuilder builder) { this.builder = builder; } }
5,421
41.692913
117
java
null
infinispan-main/spring/spring6/spring6-embedded/src/main/java/org/infinispan/spring/embedded/InfinispanDefaultCacheFactoryBean.java
package org.infinispan.spring.embedded; import java.lang.invoke.MethodHandles; import org.infinispan.Cache; import org.infinispan.commons.logging.Log; import org.infinispan.commons.logging.LogFactory; import org.infinispan.manager.CacheContainer; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; /** * <p> * A {@link FactoryBean <code>FactoryBean</code>} for creating a * native <em>default</em> Infinispan {@link Cache <code>org.infinispan.Cache</code>} * , delegating to a {@link #setInfinispanCacheContainer(CacheContainer) <code>configurable</code>} * {@link CacheContainer <code>org.infinispan.manager.CacheContainer</code>}. * A default <code>Cache</code> is a <code>Cache</code> that uses its <code>CacheContainer</code>'s * default settings. This is contrary to a <em>named</em> <code>Cache</code> where select settings * from a <code>CacheContainer</code>'s default configuration may be overridden with settings * specific to that <code>Cache</code>. * </p> * <p> * In addition to creating a <code>Cache</code> this <code>FactoryBean</code> does also control that * <code>Cache</code>'s {@link org.infinispan.commons.api.Lifecycle lifecycle} by shutting it down * when the enclosing Spring application context is closed. It is therefore advisable to * <em>always</em> use this <code>FactoryBean</code> when creating a <code>Cache</code>. * </p> * * @author <a href="mailto:olaf DOT bergner AT gmx DOT de">Olaf Bergner</a> * */ public class InfinispanDefaultCacheFactoryBean<K, V> implements FactoryBean<Cache<K, V>>, InitializingBean, DisposableBean { protected static final Log logger = LogFactory.getLog(MethodHandles.lookup().lookupClass()); private CacheContainer infinispanCacheContainer; private Cache<K, V> infinispanCache; /** * <p> * Sets the {@link CacheContainer * <code>org.infinispan.manager.CacheContainer</code>} to be used for creating our * {@link Cache <code>Cache</code>} instance. Note that this is a * <strong>mandatory</strong> property. * </p> * * @param infinispanCacheContainer * The {@link CacheContainer * <code>org.infinispan.manager.CacheContainer</code>} to be used for creating our * {@link Cache <code>Cache</code>} instance */ public void setInfinispanCacheContainer(final CacheContainer infinispanCacheContainer) { this.infinispanCacheContainer = infinispanCacheContainer; } /** * @see InitializingBean#afterPropertiesSet() */ @Override public void afterPropertiesSet() throws Exception { if (this.infinispanCacheContainer == null) { throw new IllegalStateException("No Infinispan CacheContainer has been set"); } this.logger.info("Initializing named Infinispan cache ..."); this.infinispanCache = this.infinispanCacheContainer.getCache(); this.logger.info("New Infinispan cache [" + this.infinispanCache + "] initialized"); } /** * @see FactoryBean#getObject() */ @Override public Cache<K, V> getObject() throws Exception { return this.infinispanCache; } /** * @see FactoryBean#getObjectType() */ @Override public Class<? extends Cache> getObjectType() { return this.infinispanCache != null ? this.infinispanCache.getClass() : Cache.class; } /** * Always returns <code>true</code>. * * @return Always <code>true</code> * * @see FactoryBean#isSingleton() */ @Override public boolean isSingleton() { return true; } /** * Shuts down the <code>org.infinispan.Cache</code> created by this <code>FactoryBean</code>. * * @see DisposableBean#destroy() * @see Cache#stop() */ @Override public void destroy() throws Exception { // Probably being paranoid here ... if (this.infinispanCache != null) { this.infinispanCache.stop(); } } }
4,044
33.57265
100
java
null
infinispan-main/spring/spring6/spring6-embedded/src/main/java/org/infinispan/spring/embedded/session/EmbeddedApplicationPublishedBridge.java
package org.infinispan.spring.embedded.session; import org.infinispan.AdvancedCache; import org.infinispan.notifications.Listener; import org.infinispan.notifications.cachelistener.annotation.CacheEntryCreated; import org.infinispan.notifications.cachelistener.annotation.CacheEntryExpired; import org.infinispan.notifications.cachelistener.annotation.CacheEntryRemoved; import org.infinispan.notifications.cachelistener.event.CacheEntryCreatedEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryExpiredEvent; import org.infinispan.notifications.cachelistener.event.CacheEntryRemovedEvent; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.spring.common.session.AbstractApplicationPublisherBridge; import org.springframework.session.Session; /** * A bridge between Infinispan Embedded events and Spring. * * @author Sebastian Łaskawiec * @since 9.0 */ @Listener(observation = Listener.Observation.POST, clustered = true) public class EmbeddedApplicationPublishedBridge extends AbstractApplicationPublisherBridge { public EmbeddedApplicationPublishedBridge(SpringCache eventSource) { super(eventSource); } @Override protected void registerListener() { ((AdvancedCache<?, ?>) eventSource.getNativeCache()).addListener(this); } @Override public void unregisterListener() { ((AdvancedCache<?, ?>) eventSource.getNativeCache()).removeListener(this); } @CacheEntryCreated public void processCacheEntryCreated(CacheEntryCreatedEvent event) { emitSessionCreatedEvent((Session) event.getValue()); } @CacheEntryExpired public void processCacheEntryExpired(CacheEntryExpiredEvent event) { emitSessionExpiredEvent((Session) event.getValue()); } @CacheEntryRemoved public void processCacheEntryDestroyed(CacheEntryRemovedEvent event) { emitSessionDestroyedEvent((Session) event.getOldValue()); } }
1,936
35.54717
92
java
null
infinispan-main/spring/spring6/spring6-embedded/src/main/java/org/infinispan/spring/embedded/session/InfinispanEmbeddedSessionRepository.java
package org.infinispan.spring.embedded.session; import java.util.Collection; import java.util.Collections; import java.util.Map; import java.util.stream.Collectors; import org.infinispan.Cache; import org.infinispan.context.Flag; import org.infinispan.spring.common.provider.SpringCache; import org.infinispan.spring.common.session.AbstractInfinispanSessionRepository; import org.infinispan.spring.common.session.PrincipalNameResolver; import org.springframework.session.MapSession; /** * Session Repository for Infinispan in Embedded mode. * * @author Sebastian Łaskawiec * @since 9.0 */ public class InfinispanEmbeddedSessionRepository extends AbstractInfinispanSessionRepository { /** * Creates new repository based on {@link SpringCache} * * @param cache Cache which shall be used for session repository. */ public InfinispanEmbeddedSessionRepository(SpringCache cache) { super(cache, new EmbeddedApplicationPublishedBridge(cache)); } @Override protected void removeFromCacheWithoutNotifications(String originalId) { Cache<String, MapSession> embeddedCache = (Cache<String, MapSession>) nativeCache; embeddedCache.getAdvancedCache().withFlags(Flag.SKIP_LISTENER_NOTIFICATION).remove(originalId); } @Override public Map<String, InfinispanSession> findByIndexNameAndIndexValue(String indexName, String indexValue) { if (!PRINCIPAL_NAME_INDEX_NAME.equals(indexName)) { return Collections.emptyMap(); } Cache<String, MapSession> embeddedCache = (Cache<String, MapSession>) nativeCache; Collection<MapSession> sessions = embeddedCache.values().stream() .filter(session -> indexValue.equals(PrincipalNameResolver.getInstance().resolvePrincipal(session))) .collect(Collectors::toList); return sessions.stream().collect(Collectors.toMap(MapSession::getId, session -> new InfinispanSession(session, false))); } }
1,968
36.865385
126
java
null
infinispan-main/spring/spring6/spring6-embedded/src/main/java/org/infinispan/spring/embedded/session/configuration/InfinispanEmbeddedHttpSessionConfiguration.java
package org.infinispan.spring.embedded.session.configuration; import java.time.Duration; import java.util.Map; import java.util.Objects; import org.infinispan.spring.embedded.provider.SpringEmbeddedCacheManager; import org.infinispan.spring.embedded.session.InfinispanEmbeddedSessionRepository; import org.infinispan.spring.common.provider.SpringCache; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportAware; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.AnnotationMetadata; import org.springframework.session.config.annotation.web.http.SpringHttpSessionConfiguration; @Configuration public class InfinispanEmbeddedHttpSessionConfiguration extends SpringHttpSessionConfiguration implements ImportAware { private String cacheName; private int maxInactiveIntervalInSeconds; @Bean public InfinispanEmbeddedSessionRepository sessionRepository(SpringEmbeddedCacheManager cacheManager, ApplicationEventPublisher eventPublisher) { Objects.requireNonNull(cacheName, "Cache name can not be null"); Objects.requireNonNull(cacheManager, "Cache Manager can not be null"); Objects.requireNonNull(eventPublisher, "Event Publisher can not be null"); SpringCache cacheForSessions = cacheManager.getCache(cacheName); InfinispanEmbeddedSessionRepository sessionRepository = new InfinispanEmbeddedSessionRepository(cacheForSessions); sessionRepository.setDefaultMaxInactiveInterval(Duration.ofSeconds(maxInactiveIntervalInSeconds)); sessionRepository.setApplicationEventPublisher(eventPublisher); return sessionRepository; } @Override public void setImportMetadata(AnnotationMetadata importMetadata) { Map<String, Object> enableAttrMap = importMetadata .getAnnotationAttributes(EnableInfinispanEmbeddedHttpSession.class.getName()); AnnotationAttributes annotationAttributes = AnnotationAttributes.fromMap(enableAttrMap); cacheName = annotationAttributes.getString("cacheName"); maxInactiveIntervalInSeconds = annotationAttributes.getNumber("maxInactiveIntervalInSeconds").intValue(); } }
2,321
46.387755
148
java
null
infinispan-main/spring/spring6/spring6-embedded/src/main/java/org/infinispan/spring/embedded/session/configuration/EnableInfinispanEmbeddedHttpSession.java
package org.infinispan.spring.embedded.session.configuration; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.session.MapSession; import org.springframework.session.config.annotation.web.http.EnableSpringHttpSession; /** * Add this annotation to a {@code @Configuration} class to expose the SessionRepositoryFilter as a bean named * "springSessionRepositoryFilter" and backed on Infinispan. * <p> * The configuration requires creating a {@link org.infinispan.spring.common.provider.SpringCache} (for either remote or * embedded configuration). Here's an example: * <pre> <code> * {@literal @Configuration} * {@literal @EnableInfinispanEmbeddednHttpSession} * public class InfinispanConfiguration { * * {@literal @Bean} * public SpringEmbeddedCacheManagerFactoryBean springCache() { * return new SpringEmbeddedCacheManagerFactoryBean(); * } * } * </code> </pre> * * Configuring advanced features requires putting everything together manually or extending * {@link InfinispanEmbeddedHttpSessionConfiguration}. * * @author Sebastian Łaskawiec * @see EnableSpringHttpSession * @since 9.0 */ @Retention(java.lang.annotation.RetentionPolicy.RUNTIME) @Target({java.lang.annotation.ElementType.TYPE}) @Documented @Import(InfinispanEmbeddedHttpSessionConfiguration.class) @Configuration public @interface EnableInfinispanEmbeddedHttpSession { String DEFAULT_CACHE_NAME = "sessions"; /** * This is the session timeout in seconds. By default, it is set to 1800 seconds (30 minutes). This should be a * non-negative integer. * * @return the seconds a session can be inactive before expiring */ int maxInactiveIntervalInSeconds() default MapSession.DEFAULT_MAX_INACTIVE_INTERVAL_SECONDS; /** * Cache name used for storing session data. * * @return the cache name for storing data. */ String cacheName() default DEFAULT_CACHE_NAME; }
2,131
33.387097
120
java